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 "ARMRegisterInfo.h"
19 #include "ARMUnwindOpAsm.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/MC/MCAsmBackend.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCAssembler.h"
25 #include "llvm/MC/MCCodeEmitter.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCELF.h"
28 #include "llvm/MC/MCELFStreamer.h"
29 #include "llvm/MC/MCELFSymbolFlags.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCInstPrinter.h"
33 #include "llvm/MC/MCObjectFileInfo.h"
34 #include "llvm/MC/MCObjectStreamer.h"
35 #include "llvm/MC/MCRegisterInfo.h"
36 #include "llvm/MC/MCSection.h"
37 #include "llvm/MC/MCSectionELF.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/MC/MCValue.h"
41 #include "llvm/Support/ARMBuildAttributes.h"
42 #include "llvm/Support/ARMEHABI.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ELF.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/LEB128.h"
47 #include "llvm/Support/raw_ostream.h"
52 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
53 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX &&
54 "Invalid personality index");
55 return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
58 static const char *GetFPUName(unsigned ID) {
61 llvm_unreachable("Unknown FPU kind");
63 #define ARM_FPU_NAME(NAME, ID) case ARM::ID: return NAME;
64 #include "ARMFPUName.def"
69 static const char *GetArchName(unsigned ID) {
72 llvm_unreachable("Unknown ARCH kind");
74 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
75 case ARM::ID: return NAME;
76 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
77 #include "ARMArchName.def"
82 static const char *GetArchDefaultCPUName(unsigned ID) {
85 llvm_unreachable("Unknown ARCH kind");
87 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
88 case ARM::ID: return DEFAULT_CPU_NAME;
89 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
90 #include "ARMArchName.def"
95 static unsigned GetArchDefaultCPUArch(unsigned ID) {
98 llvm_unreachable("Unknown ARCH kind");
100 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
101 case ARM::ID: return ARMBuildAttrs::DEFAULT_CPU_ARCH;
102 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
103 #include "ARMArchName.def"
110 class ARMELFStreamer;
112 class ARMTargetAsmStreamer : public ARMTargetStreamer {
113 formatted_raw_ostream &OS;
114 MCInstPrinter &InstPrinter;
117 void emitFnStart() override;
118 void emitFnEnd() override;
119 void emitCantUnwind() override;
120 void emitPersonality(const MCSymbol *Personality) override;
121 void emitPersonalityIndex(unsigned Index) override;
122 void emitHandlerData() override;
123 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
124 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
125 void emitPad(int64_t Offset) override;
126 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
127 bool isVector) override;
128 void emitUnwindRaw(int64_t Offset,
129 const SmallVectorImpl<uint8_t> &Opcodes) override;
131 void switchVendor(StringRef Vendor) override;
132 void emitAttribute(unsigned Attribute, unsigned Value) override;
133 void emitTextAttribute(unsigned Attribute, StringRef String) override;
134 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
135 StringRef StrinValue) override;
136 void emitArch(unsigned Arch) override;
137 void emitObjectArch(unsigned Arch) override;
138 void emitFPU(unsigned FPU) override;
139 void emitInst(uint32_t Inst, char Suffix = '\0') override;
140 void finishAttributeSection() override;
142 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
143 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
146 ARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS,
147 MCInstPrinter &InstPrinter, bool VerboseAsm);
150 ARMTargetAsmStreamer::ARMTargetAsmStreamer(MCStreamer &S,
151 formatted_raw_ostream &OS,
152 MCInstPrinter &InstPrinter,
154 : ARMTargetStreamer(S), OS(OS), InstPrinter(InstPrinter),
155 IsVerboseAsm(VerboseAsm) {}
156 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
157 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
158 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
159 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
160 OS << "\t.personality " << Personality->getName() << '\n';
162 void ARMTargetAsmStreamer::emitPersonalityIndex(unsigned Index) {
163 OS << "\t.personalityindex " << Index << '\n';
165 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
166 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
169 InstPrinter.printRegName(OS, FpReg);
171 InstPrinter.printRegName(OS, SpReg);
173 OS << ", #" << Offset;
176 void ARMTargetAsmStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
177 assert((Reg != ARM::SP && Reg != ARM::PC) &&
178 "the operand of .movsp cannot be either sp or pc");
181 InstPrinter.printRegName(OS, Reg);
183 OS << ", #" << Offset;
186 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
187 OS << "\t.pad\t#" << Offset << '\n';
189 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
191 assert(RegList.size() && "RegList should not be empty");
197 InstPrinter.printRegName(OS, RegList[0]);
199 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
201 InstPrinter.printRegName(OS, RegList[i]);
206 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
208 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
209 OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value);
211 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
213 OS << "\t@ " << Name;
217 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
220 case ARMBuildAttrs::CPU_name:
221 OS << "\t.cpu\t" << String.lower();
224 OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
226 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
228 OS << "\t@ " << Name;
234 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
236 StringRef StringValue) {
238 default: llvm_unreachable("unsupported multi-value attribute in asm mode");
239 case ARMBuildAttrs::compatibility:
240 OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
241 if (!StringValue.empty())
242 OS << ", \"" << StringValue << "\"";
244 OS << "\t@ " << ARMBuildAttrs::AttrTypeAsString(Attribute);
249 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
250 OS << "\t.arch\t" << GetArchName(Arch) << "\n";
252 void ARMTargetAsmStreamer::emitObjectArch(unsigned Arch) {
253 OS << "\t.object_arch\t" << GetArchName(Arch) << '\n';
255 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
256 OS << "\t.fpu\t" << GetFPUName(FPU) << "\n";
258 void ARMTargetAsmStreamer::finishAttributeSection() {
261 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
262 OS << "\t.tlsdescseq\t" << S->getSymbol().getName();
265 void ARMTargetAsmStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
266 OS << "\t.thumb_set\t" << *Symbol << ", " << *Value << '\n';
269 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
273 OS << "\t0x" << utohexstr(Inst) << "\n";
276 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
277 const SmallVectorImpl<uint8_t> &Opcodes) {
278 OS << "\t.unwind_raw " << Offset;
279 for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
282 OS << ", 0x" << utohexstr(*OCI);
286 class ARMTargetELFStreamer : public ARMTargetStreamer {
288 // This structure holds all attributes, accounting for
289 // their string/numeric value, so we can later emmit them
290 // in declaration order, keeping all in the same vector
291 struct AttributeItem {
296 NumericAndTextAttributes
300 StringRef StringValue;
302 static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
303 return (LHS.Tag < RHS.Tag);
307 StringRef CurrentVendor;
310 unsigned EmittedArch;
311 SmallVector<AttributeItem, 64> Contents;
313 const MCSection *AttributeSection;
315 AttributeItem *getAttributeItem(unsigned Attribute) {
316 for (size_t i = 0; i < Contents.size(); ++i)
317 if (Contents[i].Tag == Attribute)
322 void setAttributeItem(unsigned Attribute, unsigned Value,
323 bool OverwriteExisting) {
324 // Look for existing attribute item
325 if (AttributeItem *Item = getAttributeItem(Attribute)) {
326 if (!OverwriteExisting)
328 Item->Type = AttributeItem::NumericAttribute;
329 Item->IntValue = Value;
333 // Create new attribute item
334 AttributeItem Item = {
335 AttributeItem::NumericAttribute,
340 Contents.push_back(Item);
343 void setAttributeItem(unsigned Attribute, StringRef Value,
344 bool OverwriteExisting) {
345 // Look for existing attribute item
346 if (AttributeItem *Item = getAttributeItem(Attribute)) {
347 if (!OverwriteExisting)
349 Item->Type = AttributeItem::TextAttribute;
350 Item->StringValue = Value;
354 // Create new attribute item
355 AttributeItem Item = {
356 AttributeItem::TextAttribute,
361 Contents.push_back(Item);
364 void setAttributeItems(unsigned Attribute, unsigned IntValue,
365 StringRef StringValue, bool OverwriteExisting) {
366 // Look for existing attribute item
367 if (AttributeItem *Item = getAttributeItem(Attribute)) {
368 if (!OverwriteExisting)
370 Item->Type = AttributeItem::NumericAndTextAttributes;
371 Item->IntValue = IntValue;
372 Item->StringValue = StringValue;
376 // Create new attribute item
377 AttributeItem Item = {
378 AttributeItem::NumericAndTextAttributes,
383 Contents.push_back(Item);
386 void emitArchDefaultAttributes();
387 void emitFPUDefaultAttributes();
389 ARMELFStreamer &getStreamer();
391 void emitFnStart() override;
392 void emitFnEnd() override;
393 void emitCantUnwind() override;
394 void emitPersonality(const MCSymbol *Personality) override;
395 void emitPersonalityIndex(unsigned Index) override;
396 void emitHandlerData() override;
397 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
398 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
399 void emitPad(int64_t Offset) override;
400 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
401 bool isVector) override;
402 void emitUnwindRaw(int64_t Offset,
403 const SmallVectorImpl<uint8_t> &Opcodes) override;
405 void switchVendor(StringRef Vendor) override;
406 void emitAttribute(unsigned Attribute, unsigned Value) override;
407 void emitTextAttribute(unsigned Attribute, StringRef String) override;
408 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
409 StringRef StringValue) override;
410 void emitArch(unsigned Arch) override;
411 void emitObjectArch(unsigned Arch) override;
412 void emitFPU(unsigned FPU) override;
413 void emitInst(uint32_t Inst, char Suffix = '\0') override;
414 void finishAttributeSection() override;
415 void emitLabel(MCSymbol *Symbol) override;
417 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
418 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
420 size_t calculateContentSize() const;
423 ARMTargetELFStreamer(MCStreamer &S)
424 : ARMTargetStreamer(S), CurrentVendor("aeabi"), FPU(ARM::INVALID_FPU),
425 Arch(ARM::INVALID_ARCH), EmittedArch(ARM::INVALID_ARCH),
426 AttributeSection(nullptr) {}
429 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
430 /// the appropriate points in the object files. These symbols are defined in the
431 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
433 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
434 /// region of ARM code, Thumb code or data in a section. In practice, this
435 /// emission does not rely on explicit assembler directives but on inherent
436 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
437 /// r0, r0, r0" an instruction).
439 /// As a result this system is orthogonal to the DataRegion infrastructure used
440 /// by MachO. Beware!
441 class ARMELFStreamer : public MCELFStreamer {
443 friend class ARMTargetELFStreamer;
445 ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_ostream &OS,
446 MCCodeEmitter *Emitter, bool IsThumb)
447 : MCELFStreamer(Context, TAB, OS, Emitter), IsThumb(IsThumb),
448 MappingSymbolCounter(0), LastEMS(EMS_None) {
454 void FinishImpl() override;
456 // ARM exception handling directives
459 void emitCantUnwind();
460 void emitPersonality(const MCSymbol *Per);
461 void emitPersonalityIndex(unsigned index);
462 void emitHandlerData();
463 void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
464 void emitMovSP(unsigned Reg, int64_t Offset = 0);
465 void emitPad(int64_t Offset);
466 void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
467 void emitUnwindRaw(int64_t Offset, const SmallVectorImpl<uint8_t> &Opcodes);
469 void ChangeSection(const MCSection *Section,
470 const MCExpr *Subsection) override {
471 // We have to keep track of the mapping symbol state of any sections we
472 // use. Each one should start off as EMS_None, which is provided as the
473 // default constructor by DenseMap::lookup.
474 LastMappingSymbols[getPreviousSection().first] = LastEMS;
475 LastEMS = LastMappingSymbols.lookup(Section);
477 MCELFStreamer::ChangeSection(Section, Subsection);
480 /// This function is the one used to emit instruction data into the ELF
481 /// streamer. We override it to add the appropriate mapping symbol if
483 void EmitInstruction(const MCInst& Inst,
484 const MCSubtargetInfo &STI) override {
486 EmitThumbMappingSymbol();
488 EmitARMMappingSymbol();
490 MCELFStreamer::EmitInstruction(Inst, STI);
493 void emitInst(uint32_t Inst, char Suffix) {
496 const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
503 EmitARMMappingSymbol();
504 for (unsigned II = 0, IE = Size; II != IE; II++) {
505 const unsigned I = LittleEndian ? (Size - II - 1) : II;
506 Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
512 Size = (Suffix == 'n' ? 2 : 4);
515 EmitThumbMappingSymbol();
516 for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
517 const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
518 const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
519 Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
520 Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
525 llvm_unreachable("Invalid Suffix");
528 MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
531 /// This is one of the functions used to emit data into an ELF section, so the
532 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
534 void EmitBytes(StringRef Data) override {
535 EmitDataMappingSymbol();
536 MCELFStreamer::EmitBytes(Data);
539 /// This is one of the functions used to emit data into an ELF section, so the
540 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
542 void EmitValueImpl(const MCExpr *Value, unsigned Size,
543 const SMLoc &Loc) override {
544 EmitDataMappingSymbol();
545 MCELFStreamer::EmitValueImpl(Value, Size);
548 void EmitAssemblerFlag(MCAssemblerFlag Flag) override {
549 MCELFStreamer::EmitAssemblerFlag(Flag);
552 case MCAF_SyntaxUnified:
553 return; // no-op here.
556 return; // Change to Thumb mode
559 return; // Change to ARM mode
562 case MCAF_SubsectionsViaSymbols:
568 enum ElfMappingSymbol {
575 void EmitDataMappingSymbol() {
576 if (LastEMS == EMS_Data) return;
577 EmitMappingSymbol("$d");
581 void EmitThumbMappingSymbol() {
582 if (LastEMS == EMS_Thumb) return;
583 EmitMappingSymbol("$t");
587 void EmitARMMappingSymbol() {
588 if (LastEMS == EMS_ARM) return;
589 EmitMappingSymbol("$a");
593 void EmitMappingSymbol(StringRef Name) {
594 MCSymbol *Start = getContext().CreateTempSymbol();
598 getContext().GetOrCreateSymbol(Name + "." +
599 Twine(MappingSymbolCounter++));
601 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
602 MCELF::SetType(SD, ELF::STT_NOTYPE);
603 MCELF::SetBinding(SD, ELF::STB_LOCAL);
604 SD.setExternal(false);
605 AssignSection(Symbol, getCurrentSection().first);
607 const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
608 Symbol->setVariableValue(Value);
611 void EmitThumbFunc(MCSymbol *Func) override {
612 // FIXME: Anything needed here to flag the function as thumb?
614 getAssembler().setIsThumbFunc(Func);
616 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Func);
617 SD.setFlags(SD.getFlags() | ELF_Other_ThumbFunc);
620 // Helper functions for ARM exception handling directives
623 void EmitPersonalityFixup(StringRef Name);
624 void FlushPendingOffset();
625 void FlushUnwindOpcodes(bool NoHandlerData);
627 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
628 SectionKind Kind, const MCSymbol &Fn);
629 void SwitchToExTabSection(const MCSymbol &FnStart);
630 void SwitchToExIdxSection(const MCSymbol &FnStart);
632 void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
635 int64_t MappingSymbolCounter;
637 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
638 ElfMappingSymbol LastEMS;
640 // ARM Exception Handling Frame Information
643 const MCSymbol *Personality;
644 unsigned PersonalityIndex;
645 unsigned FPReg; // Frame pointer register
646 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
647 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
648 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
651 SmallVector<uint8_t, 64> Opcodes;
652 UnwindOpcodeAssembler UnwindOpAsm;
654 } // end anonymous namespace
656 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
657 return static_cast<ARMELFStreamer &>(Streamer);
660 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
661 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
662 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
663 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
664 getStreamer().emitPersonality(Personality);
666 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
667 getStreamer().emitPersonalityIndex(Index);
669 void ARMTargetELFStreamer::emitHandlerData() {
670 getStreamer().emitHandlerData();
672 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
674 getStreamer().emitSetFP(FpReg, SpReg, Offset);
676 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
677 getStreamer().emitMovSP(Reg, Offset);
679 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
680 getStreamer().emitPad(Offset);
682 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
684 getStreamer().emitRegSave(RegList, isVector);
686 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
687 const SmallVectorImpl<uint8_t> &Opcodes) {
688 getStreamer().emitUnwindRaw(Offset, Opcodes);
690 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
691 assert(!Vendor.empty() && "Vendor cannot be empty.");
693 if (CurrentVendor == Vendor)
696 if (!CurrentVendor.empty())
697 finishAttributeSection();
699 assert(Contents.empty() &&
700 ".ARM.attributes should be flushed before changing vendor");
701 CurrentVendor = Vendor;
704 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
705 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
707 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
709 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
711 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
713 StringRef StringValue) {
714 setAttributeItems(Attribute, IntValue, StringValue,
715 /* OverwriteExisting= */ true);
717 void ARMTargetELFStreamer::emitArch(unsigned Value) {
720 void ARMTargetELFStreamer::emitObjectArch(unsigned Value) {
723 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
724 using namespace ARMBuildAttrs;
726 setAttributeItem(CPU_name, GetArchDefaultCPUName(Arch), false);
727 if (EmittedArch == ARM::INVALID_ARCH)
728 setAttributeItem(CPU_arch, GetArchDefaultCPUArch(Arch), false);
730 setAttributeItem(CPU_arch, GetArchDefaultCPUArch(EmittedArch), false);
739 setAttributeItem(ARM_ISA_use, Allowed, false);
747 setAttributeItem(ARM_ISA_use, Allowed, false);
748 setAttributeItem(THUMB_ISA_use, Allowed, false);
752 setAttributeItem(ARM_ISA_use, Allowed, false);
753 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
758 setAttributeItem(ARM_ISA_use, Allowed, false);
759 setAttributeItem(THUMB_ISA_use, Allowed, false);
760 setAttributeItem(Virtualization_use, AllowTZ, false);
764 setAttributeItem(THUMB_ISA_use, Allowed, false);
768 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
772 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
773 setAttributeItem(ARM_ISA_use, Allowed, false);
774 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
778 setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
779 setAttributeItem(ARM_ISA_use, Allowed, false);
780 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
784 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
785 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
789 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
790 setAttributeItem(ARM_ISA_use, Allowed, false);
791 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
792 setAttributeItem(MPextension_use, Allowed, false);
793 setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
797 setAttributeItem(ARM_ISA_use, Allowed, false);
798 setAttributeItem(THUMB_ISA_use, Allowed, false);
799 setAttributeItem(WMMX_arch, AllowWMMXv1, false);
803 setAttributeItem(ARM_ISA_use, Allowed, false);
804 setAttributeItem(THUMB_ISA_use, Allowed, false);
805 setAttributeItem(WMMX_arch, AllowWMMXv2, false);
809 report_fatal_error("Unknown Arch: " + Twine(Arch));
813 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
816 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
820 setAttributeItem(ARMBuildAttrs::FP_arch,
821 ARMBuildAttrs::AllowFPv2,
822 /* OverwriteExisting= */ false);
826 setAttributeItem(ARMBuildAttrs::FP_arch,
827 ARMBuildAttrs::AllowFPv3A,
828 /* OverwriteExisting= */ false);
832 setAttributeItem(ARMBuildAttrs::FP_arch,
833 ARMBuildAttrs::AllowFPv3B,
834 /* OverwriteExisting= */ false);
838 setAttributeItem(ARMBuildAttrs::FP_arch,
839 ARMBuildAttrs::AllowFPv4A,
840 /* OverwriteExisting= */ false);
844 setAttributeItem(ARMBuildAttrs::FP_arch,
845 ARMBuildAttrs::AllowFPv4B,
846 /* OverwriteExisting= */ false);
850 setAttributeItem(ARMBuildAttrs::FP_arch,
851 ARMBuildAttrs::AllowFPARMv8A,
852 /* OverwriteExisting= */ false);
856 setAttributeItem(ARMBuildAttrs::FP_arch,
857 ARMBuildAttrs::AllowFPv3A,
858 /* OverwriteExisting= */ false);
859 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
860 ARMBuildAttrs::AllowNeon,
861 /* OverwriteExisting= */ false);
864 case ARM::NEON_VFPV4:
865 setAttributeItem(ARMBuildAttrs::FP_arch,
866 ARMBuildAttrs::AllowFPv4A,
867 /* OverwriteExisting= */ false);
868 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
869 ARMBuildAttrs::AllowNeon2,
870 /* OverwriteExisting= */ false);
873 case ARM::NEON_FP_ARMV8:
874 case ARM::CRYPTO_NEON_FP_ARMV8:
875 setAttributeItem(ARMBuildAttrs::FP_arch,
876 ARMBuildAttrs::AllowFPARMv8A,
877 /* OverwriteExisting= */ false);
878 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
879 ARMBuildAttrs::AllowNeonARMv8,
880 /* OverwriteExisting= */ false);
887 report_fatal_error("Unknown FPU: " + Twine(FPU));
891 size_t ARMTargetELFStreamer::calculateContentSize() const {
893 for (size_t i = 0; i < Contents.size(); ++i) {
894 AttributeItem item = Contents[i];
896 case AttributeItem::HiddenAttribute:
898 case AttributeItem::NumericAttribute:
899 Result += getULEB128Size(item.Tag);
900 Result += getULEB128Size(item.IntValue);
902 case AttributeItem::TextAttribute:
903 Result += getULEB128Size(item.Tag);
904 Result += item.StringValue.size() + 1; // string + '\0'
906 case AttributeItem::NumericAndTextAttributes:
907 Result += getULEB128Size(item.Tag);
908 Result += getULEB128Size(item.IntValue);
909 Result += item.StringValue.size() + 1; // string + '\0';
915 void ARMTargetELFStreamer::finishAttributeSection() {
917 // [ <section-length> "vendor-name"
918 // [ <file-tag> <size> <attribute>*
919 // | <section-tag> <size> <section-number>* 0 <attribute>*
920 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
924 if (FPU != ARM::INVALID_FPU)
925 emitFPUDefaultAttributes();
927 if (Arch != ARM::INVALID_ARCH)
928 emitArchDefaultAttributes();
930 if (Contents.empty())
933 std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
935 ARMELFStreamer &Streamer = getStreamer();
937 // Switch to .ARM.attributes section
938 if (AttributeSection) {
939 Streamer.SwitchSection(AttributeSection);
942 Streamer.getContext().getELFSection(".ARM.attributes",
943 ELF::SHT_ARM_ATTRIBUTES,
945 SectionKind::getMetadata());
946 Streamer.SwitchSection(AttributeSection);
949 Streamer.EmitIntValue(0x41, 1);
952 // Vendor size + Vendor name + '\0'
953 const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
956 const size_t TagHeaderSize = 1 + 4;
958 const size_t ContentsSize = calculateContentSize();
960 Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
961 Streamer.EmitBytes(CurrentVendor);
962 Streamer.EmitIntValue(0, 1); // '\0'
964 Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
965 Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
967 // Size should have been accounted for already, now
968 // emit each field as its type (ULEB or String)
969 for (size_t i = 0; i < Contents.size(); ++i) {
970 AttributeItem item = Contents[i];
971 Streamer.EmitULEB128IntValue(item.Tag);
973 default: llvm_unreachable("Invalid attribute type");
974 case AttributeItem::NumericAttribute:
975 Streamer.EmitULEB128IntValue(item.IntValue);
977 case AttributeItem::TextAttribute:
978 Streamer.EmitBytes(item.StringValue.upper());
979 Streamer.EmitIntValue(0, 1); // '\0'
981 case AttributeItem::NumericAndTextAttributes:
982 Streamer.EmitULEB128IntValue(item.IntValue);
983 Streamer.EmitBytes(item.StringValue.upper());
984 Streamer.EmitIntValue(0, 1); // '\0'
990 FPU = ARM::INVALID_FPU;
993 void ARMTargetELFStreamer::emitLabel(MCSymbol *Symbol) {
994 ARMELFStreamer &Streamer = getStreamer();
995 if (!Streamer.IsThumb)
998 const MCSymbolData &SD = Streamer.getOrCreateSymbolData(Symbol);
999 if (MCELF::GetType(SD) & (ELF::STT_FUNC << ELF_STT_Shift))
1000 Streamer.EmitThumbFunc(Symbol);
1004 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
1005 getStreamer().EmitFixup(S, FK_Data_4);
1008 void ARMTargetELFStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
1009 if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Value)) {
1010 // FIXME: Doing a lookup in here is a hack.
1012 getStreamer().getContext().LookupSymbol(SRE->getSymbol().getName());
1013 if (!Sym->isDefined()) {
1014 getStreamer().EmitSymbolAttribute(Sym, MCSA_Global);
1015 getStreamer().EmitAssignment(Symbol, Value);
1020 getStreamer().EmitThumbFunc(Symbol);
1021 getStreamer().EmitAssignment(Symbol, Value);
1024 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
1025 getStreamer().emitInst(Inst, Suffix);
1028 void ARMELFStreamer::FinishImpl() {
1029 MCTargetStreamer &TS = *getTargetStreamer();
1030 ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1031 ATS.finishAttributeSection();
1033 MCELFStreamer::FinishImpl();
1036 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
1040 const MCSymbol &Fn) {
1041 const MCSectionELF &FnSection =
1042 static_cast<const MCSectionELF &>(Fn.getSection());
1044 // Create the name for new section
1045 StringRef FnSecName(FnSection.getSectionName());
1046 SmallString<128> EHSecName(Prefix);
1047 if (FnSecName != ".text") {
1048 EHSecName += FnSecName;
1051 // Get .ARM.extab or .ARM.exidx section
1052 const MCSectionELF *EHSection = nullptr;
1053 if (const MCSymbol *Group = FnSection.getGroup()) {
1054 EHSection = getContext().getELFSection(
1055 EHSecName, Type, Flags | ELF::SHF_GROUP, Kind,
1056 FnSection.getEntrySize(), Group->getName());
1058 EHSection = getContext().getELFSection(EHSecName, Type, Flags, Kind);
1060 assert(EHSection && "Failed to get the required EH section");
1062 // Switch to .ARM.extab or .ARM.exidx section
1063 SwitchSection(EHSection);
1064 EmitCodeAlignment(4);
1067 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
1068 SwitchToEHSection(".ARM.extab",
1071 SectionKind::getDataRel(),
1075 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
1076 SwitchToEHSection(".ARM.exidx",
1078 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
1079 SectionKind::getDataRel(),
1082 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
1083 MCDataFragment *Frag = getOrCreateDataFragment();
1084 Frag->getFixups().push_back(MCFixup::Create(Frag->getContents().size(), Expr,
1088 void ARMELFStreamer::Reset() {
1091 Personality = nullptr;
1092 PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
1101 UnwindOpAsm.Reset();
1104 void ARMELFStreamer::emitFnStart() {
1105 assert(FnStart == 0);
1106 FnStart = getContext().CreateTempSymbol();
1110 void ARMELFStreamer::emitFnEnd() {
1111 assert(FnStart && ".fnstart must precedes .fnend");
1113 // Emit unwind opcodes if there is no .handlerdata directive
1114 if (!ExTab && !CantUnwind)
1115 FlushUnwindOpcodes(true);
1117 // Emit the exception index table entry
1118 SwitchToExIdxSection(*FnStart);
1120 if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
1121 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1123 const MCSymbolRefExpr *FnStartRef =
1124 MCSymbolRefExpr::Create(FnStart,
1125 MCSymbolRefExpr::VK_ARM_PREL31,
1128 EmitValue(FnStartRef, 4);
1131 EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
1133 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1134 const MCSymbolRefExpr *ExTabEntryRef =
1135 MCSymbolRefExpr::Create(ExTab,
1136 MCSymbolRefExpr::VK_ARM_PREL31,
1138 EmitValue(ExTabEntryRef, 4);
1140 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1141 // the second word of exception index table entry. The size of the unwind
1142 // opcodes should always be 4 bytes.
1143 assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1144 "Compact model must use __aeabi_cpp_unwind_pr0 as personality");
1145 assert(Opcodes.size() == 4u &&
1146 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be equal to 4");
1147 EmitBytes(StringRef(reinterpret_cast<const char*>(Opcodes.data()),
1151 // Switch to the section containing FnStart
1152 SwitchSection(&FnStart->getSection());
1154 // Clean exception handling frame information
1158 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1160 // Add the R_ARM_NONE fixup at the same position
1161 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1162 const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
1164 const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::Create(
1165 PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1167 AddValueSymbols(PersonalityRef);
1168 MCDataFragment *DF = getOrCreateDataFragment();
1169 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
1171 MCFixup::getKindForSize(4, false)));
1174 void ARMELFStreamer::FlushPendingOffset() {
1175 if (PendingOffset != 0) {
1176 UnwindOpAsm.EmitSPOffset(-PendingOffset);
1181 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1182 // Emit the unwind opcode to restore $sp.
1184 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1185 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1186 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1187 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1189 FlushPendingOffset();
1192 // Finalize the unwind opcode sequence
1193 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1195 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1196 // section. Thus, we don't have to create an entry in the .ARM.extab
1198 if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1201 // Switch to .ARM.extab section.
1202 SwitchToExTabSection(*FnStart);
1204 // Create .ARM.extab label for offset in .ARM.exidx
1206 ExTab = getContext().CreateTempSymbol();
1211 const MCSymbolRefExpr *PersonalityRef =
1212 MCSymbolRefExpr::Create(Personality,
1213 MCSymbolRefExpr::VK_ARM_PREL31,
1216 EmitValue(PersonalityRef, 4);
1219 // Emit unwind opcodes
1220 EmitBytes(StringRef(reinterpret_cast<const char *>(Opcodes.data()),
1223 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1224 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1225 // after the unwind opcodes. The handler data consists of several 32-bit
1226 // words, and should be terminated by zero.
1228 // In case that the .handlerdata directive is not specified by the
1229 // programmer, we should emit zero to terminate the handler data.
1230 if (NoHandlerData && !Personality)
1234 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1236 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1238 UnwindOpAsm.setPersonality(Per);
1241 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
1242 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
1243 PersonalityIndex = Index;
1246 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1248 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1249 "the operand of .setfp directive should be either $sp or $fp");
1254 if (NewSPReg == ARM::SP)
1255 FPOffset = SPOffset + Offset;
1260 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
1261 assert((Reg != ARM::SP && Reg != ARM::PC) &&
1262 "the operand of .movsp cannot be either sp or pc");
1263 assert(FPReg == ARM::SP && "current FP must be SP");
1265 FlushPendingOffset();
1268 FPOffset = SPOffset + Offset;
1270 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1271 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1274 void ARMELFStreamer::emitPad(int64_t Offset) {
1275 // Track the change of the $sp offset
1278 // To squash multiple .pad directives, we should delay the unwind opcode
1279 // until the .save, .vsave, .handlerdata, or .fnend directives.
1280 PendingOffset -= Offset;
1283 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1285 // Collect the registers in the register list
1288 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1289 for (size_t i = 0; i < RegList.size(); ++i) {
1290 unsigned Reg = MRI->getEncodingValue(RegList[i]);
1291 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1292 unsigned Bit = (1u << Reg);
1293 if ((Mask & Bit) == 0) {
1299 // Track the change the $sp offset: For the .save directive, the
1300 // corresponding push instruction will decrease the $sp by (4 * Count).
1301 // For the .vsave directive, the corresponding vpush instruction will
1302 // decrease $sp by (8 * Count).
1303 SPOffset -= Count * (IsVector ? 8 : 4);
1306 FlushPendingOffset();
1308 UnwindOpAsm.EmitVFPRegSave(Mask);
1310 UnwindOpAsm.EmitRegSave(Mask);
1313 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
1314 const SmallVectorImpl<uint8_t> &Opcodes) {
1315 FlushPendingOffset();
1316 SPOffset = SPOffset - Offset;
1317 UnwindOpAsm.EmitRaw(Opcodes);
1322 MCStreamer *createMCAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
1323 bool isVerboseAsm, bool useCFI,
1324 bool useDwarfDirectory,
1325 MCInstPrinter *InstPrint, MCCodeEmitter *CE,
1326 MCAsmBackend *TAB, bool ShowInst) {
1328 llvm::createAsmStreamer(Ctx, OS, isVerboseAsm, useCFI, useDwarfDirectory,
1329 InstPrint, CE, TAB, ShowInst);
1330 new ARMTargetAsmStreamer(*S, OS, *InstPrint, isVerboseAsm);
1334 MCELFStreamer* createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1335 raw_ostream &OS, MCCodeEmitter *Emitter,
1336 bool RelaxAll, bool NoExecStack,
1338 ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
1339 new ARMTargetELFStreamer(*S);
1340 // FIXME: This should eventually end up somewhere else where more
1341 // intelligent flag decisions can be made. For now we are just maintaining
1342 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1343 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1346 S->getAssembler().setRelaxAll(true);
1348 S->getAssembler().setNoExecStack(true);