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 "ARMRegisterInfo.h"
17 #include "ARMUnwindOpAsm.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmBackend.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCCodeEmitter.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCELFStreamer.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/MC/MCObjectFileInfo.h"
30 #include "llvm/MC/MCObjectStreamer.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCSectionELF.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbolELF.h"
36 #include "llvm/MC/MCValue.h"
37 #include "llvm/Support/ARMBuildAttributes.h"
38 #include "llvm/Support/ARMEHABI.h"
39 #include "llvm/Support/TargetParser.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ELF.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/LEB128.h"
44 #include "llvm/Support/raw_ostream.h"
49 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
50 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX &&
51 "Invalid personality index");
52 return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
59 class ARMTargetAsmStreamer : public ARMTargetStreamer {
60 formatted_raw_ostream &OS;
61 MCInstPrinter &InstPrinter;
64 void emitFnStart() override;
65 void emitFnEnd() override;
66 void emitCantUnwind() override;
67 void emitPersonality(const MCSymbol *Personality) override;
68 void emitPersonalityIndex(unsigned Index) override;
69 void emitHandlerData() override;
70 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
71 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
72 void emitPad(int64_t Offset) override;
73 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
74 bool isVector) override;
75 void emitUnwindRaw(int64_t Offset,
76 const SmallVectorImpl<uint8_t> &Opcodes) override;
78 void switchVendor(StringRef Vendor) override;
79 void emitAttribute(unsigned Attribute, unsigned Value) override;
80 void emitTextAttribute(unsigned Attribute, StringRef String) override;
81 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
82 StringRef StrinValue) override;
83 void emitArch(unsigned Arch) override;
84 void emitArchExtension(unsigned ArchExt) override;
85 void emitObjectArch(unsigned Arch) override;
86 void emitFPU(unsigned FPU) override;
87 void emitInst(uint32_t Inst, char Suffix = '\0') override;
88 void finishAttributeSection() override;
90 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
91 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
94 ARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS,
95 MCInstPrinter &InstPrinter, bool VerboseAsm);
98 ARMTargetAsmStreamer::ARMTargetAsmStreamer(MCStreamer &S,
99 formatted_raw_ostream &OS,
100 MCInstPrinter &InstPrinter,
102 : ARMTargetStreamer(S), OS(OS), InstPrinter(InstPrinter),
103 IsVerboseAsm(VerboseAsm) {}
104 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
105 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
106 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
107 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
108 OS << "\t.personality " << Personality->getName() << '\n';
110 void ARMTargetAsmStreamer::emitPersonalityIndex(unsigned Index) {
111 OS << "\t.personalityindex " << Index << '\n';
113 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
114 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
117 InstPrinter.printRegName(OS, FpReg);
119 InstPrinter.printRegName(OS, SpReg);
121 OS << ", #" << Offset;
124 void ARMTargetAsmStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
125 assert((Reg != ARM::SP && Reg != ARM::PC) &&
126 "the operand of .movsp cannot be either sp or pc");
129 InstPrinter.printRegName(OS, Reg);
131 OS << ", #" << Offset;
134 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
135 OS << "\t.pad\t#" << Offset << '\n';
137 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
139 assert(RegList.size() && "RegList should not be empty");
145 InstPrinter.printRegName(OS, RegList[0]);
147 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
149 InstPrinter.printRegName(OS, RegList[i]);
154 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
156 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
157 OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value);
159 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
161 OS << "\t@ " << Name;
165 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
168 case ARMBuildAttrs::CPU_name:
169 OS << "\t.cpu\t" << String.lower();
172 OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
174 StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
176 OS << "\t@ " << Name;
182 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
184 StringRef StringValue) {
186 default: llvm_unreachable("unsupported multi-value attribute in asm mode");
187 case ARMBuildAttrs::compatibility:
188 OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
189 if (!StringValue.empty())
190 OS << ", \"" << StringValue << "\"";
192 OS << "\t@ " << ARMBuildAttrs::AttrTypeAsString(Attribute);
197 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
198 OS << "\t.arch\t" << ARMTargetParser::getArchName(Arch) << "\n";
200 void ARMTargetAsmStreamer::emitArchExtension(unsigned ArchExt) {
201 OS << "\t.arch_extension\t" << ARMTargetParser::getArchExtName(ArchExt) << "\n";
203 void ARMTargetAsmStreamer::emitObjectArch(unsigned Arch) {
204 OS << "\t.object_arch\t" << ARMTargetParser::getArchName(Arch) << '\n';
206 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
207 OS << "\t.fpu\t" << ARMTargetParser::getFPUName(FPU) << "\n";
209 void ARMTargetAsmStreamer::finishAttributeSection() {
212 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
213 OS << "\t.tlsdescseq\t" << S->getSymbol().getName();
216 void ARMTargetAsmStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
217 OS << "\t.thumb_set\t" << *Symbol << ", " << *Value << '\n';
220 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
224 OS << "\t0x" << Twine::utohexstr(Inst) << "\n";
227 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
228 const SmallVectorImpl<uint8_t> &Opcodes) {
229 OS << "\t.unwind_raw " << Offset;
230 for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
233 OS << ", 0x" << Twine::utohexstr(*OCI);
237 class ARMTargetELFStreamer : public ARMTargetStreamer {
239 // This structure holds all attributes, accounting for
240 // their string/numeric value, so we can later emmit them
241 // in declaration order, keeping all in the same vector
242 struct AttributeItem {
247 NumericAndTextAttributes
251 StringRef StringValue;
253 static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
254 // The conformance tag must be emitted first when serialised
255 // into an object file. Specifically, the addenda to the ARM ABI
256 // states that (2.3.7.4):
258 // "To simplify recognition by consumers in the common case of
259 // claiming conformity for the whole file, this tag should be
260 // emitted first in a file-scope sub-subsection of the first
261 // public subsection of the attributes section."
263 // So it is special-cased in this comparison predicate when the
264 // attributes are sorted in finishAttributeSection().
265 return (RHS.Tag != ARMBuildAttrs::conformance) &&
266 ((LHS.Tag == ARMBuildAttrs::conformance) || (LHS.Tag < RHS.Tag));
270 StringRef CurrentVendor;
273 unsigned EmittedArch;
274 SmallVector<AttributeItem, 64> Contents;
276 MCSection *AttributeSection;
278 AttributeItem *getAttributeItem(unsigned Attribute) {
279 for (size_t i = 0; i < Contents.size(); ++i)
280 if (Contents[i].Tag == Attribute)
285 void setAttributeItem(unsigned Attribute, unsigned Value,
286 bool OverwriteExisting) {
287 // Look for existing attribute item
288 if (AttributeItem *Item = getAttributeItem(Attribute)) {
289 if (!OverwriteExisting)
291 Item->Type = AttributeItem::NumericAttribute;
292 Item->IntValue = Value;
296 // Create new attribute item
297 AttributeItem Item = {
298 AttributeItem::NumericAttribute,
303 Contents.push_back(Item);
306 void setAttributeItem(unsigned Attribute, StringRef Value,
307 bool OverwriteExisting) {
308 // Look for existing attribute item
309 if (AttributeItem *Item = getAttributeItem(Attribute)) {
310 if (!OverwriteExisting)
312 Item->Type = AttributeItem::TextAttribute;
313 Item->StringValue = Value;
317 // Create new attribute item
318 AttributeItem Item = {
319 AttributeItem::TextAttribute,
324 Contents.push_back(Item);
327 void setAttributeItems(unsigned Attribute, unsigned IntValue,
328 StringRef StringValue, bool OverwriteExisting) {
329 // Look for existing attribute item
330 if (AttributeItem *Item = getAttributeItem(Attribute)) {
331 if (!OverwriteExisting)
333 Item->Type = AttributeItem::NumericAndTextAttributes;
334 Item->IntValue = IntValue;
335 Item->StringValue = StringValue;
339 // Create new attribute item
340 AttributeItem Item = {
341 AttributeItem::NumericAndTextAttributes,
346 Contents.push_back(Item);
349 void emitArchDefaultAttributes();
350 void emitFPUDefaultAttributes();
352 ARMELFStreamer &getStreamer();
354 void emitFnStart() override;
355 void emitFnEnd() override;
356 void emitCantUnwind() override;
357 void emitPersonality(const MCSymbol *Personality) override;
358 void emitPersonalityIndex(unsigned Index) override;
359 void emitHandlerData() override;
360 void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
361 void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
362 void emitPad(int64_t Offset) override;
363 void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
364 bool isVector) override;
365 void emitUnwindRaw(int64_t Offset,
366 const SmallVectorImpl<uint8_t> &Opcodes) override;
368 void switchVendor(StringRef Vendor) override;
369 void emitAttribute(unsigned Attribute, unsigned Value) override;
370 void emitTextAttribute(unsigned Attribute, StringRef String) override;
371 void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
372 StringRef StringValue) override;
373 void emitArch(unsigned Arch) override;
374 void emitObjectArch(unsigned Arch) override;
375 void emitFPU(unsigned FPU) override;
376 void emitInst(uint32_t Inst, char Suffix = '\0') override;
377 void finishAttributeSection() override;
378 void emitLabel(MCSymbol *Symbol) override;
380 void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
381 void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
383 size_t calculateContentSize() const;
386 ARMTargetELFStreamer(MCStreamer &S)
387 : ARMTargetStreamer(S), CurrentVendor("aeabi"), FPU(ARM::FK_INVALID),
388 Arch(ARM::AK_INVALID), EmittedArch(ARM::AK_INVALID),
389 AttributeSection(nullptr) {}
392 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
393 /// the appropriate points in the object files. These symbols are defined in the
394 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
396 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
397 /// region of ARM code, Thumb code or data in a section. In practice, this
398 /// emission does not rely on explicit assembler directives but on inherent
399 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
400 /// r0, r0, r0" an instruction).
402 /// As a result this system is orthogonal to the DataRegion infrastructure used
403 /// by MachO. Beware!
404 class ARMELFStreamer : public MCELFStreamer {
406 friend class ARMTargetELFStreamer;
408 ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_pwrite_stream &OS,
409 MCCodeEmitter *Emitter, bool IsThumb)
410 : MCELFStreamer(Context, TAB, OS, Emitter), IsThumb(IsThumb),
411 MappingSymbolCounter(0), LastEMS(EMS_None) {
417 void FinishImpl() override;
419 // ARM exception handling directives
422 void emitCantUnwind();
423 void emitPersonality(const MCSymbol *Per);
424 void emitPersonalityIndex(unsigned index);
425 void emitHandlerData();
426 void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
427 void emitMovSP(unsigned Reg, int64_t Offset = 0);
428 void emitPad(int64_t Offset);
429 void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
430 void emitUnwindRaw(int64_t Offset, const SmallVectorImpl<uint8_t> &Opcodes);
432 void ChangeSection(MCSection *Section, const MCExpr *Subsection) override {
433 // We have to keep track of the mapping symbol state of any sections we
434 // use. Each one should start off as EMS_None, which is provided as the
435 // default constructor by DenseMap::lookup.
436 LastMappingSymbols[getPreviousSection().first] = LastEMS;
437 LastEMS = LastMappingSymbols.lookup(Section);
439 MCELFStreamer::ChangeSection(Section, Subsection);
442 /// This function is the one used to emit instruction data into the ELF
443 /// streamer. We override it to add the appropriate mapping symbol if
445 void EmitInstruction(const MCInst& Inst,
446 const MCSubtargetInfo &STI) override {
448 EmitThumbMappingSymbol();
450 EmitARMMappingSymbol();
452 MCELFStreamer::EmitInstruction(Inst, STI);
455 void emitInst(uint32_t Inst, char Suffix) {
458 const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
465 EmitARMMappingSymbol();
466 for (unsigned II = 0, IE = Size; II != IE; II++) {
467 const unsigned I = LittleEndian ? (Size - II - 1) : II;
468 Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
474 Size = (Suffix == 'n' ? 2 : 4);
477 EmitThumbMappingSymbol();
478 for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
479 const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
480 const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
481 Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
482 Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
487 llvm_unreachable("Invalid Suffix");
490 MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
493 /// This is one of the functions used to emit data into an ELF section, so the
494 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
496 void EmitBytes(StringRef Data) override {
497 EmitDataMappingSymbol();
498 MCELFStreamer::EmitBytes(Data);
501 /// This is one of the functions used to emit data into an ELF section, so the
502 /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
504 void EmitValueImpl(const MCExpr *Value, unsigned Size,
505 const SMLoc &Loc) override {
506 if (const MCSymbolRefExpr *SRE = dyn_cast_or_null<MCSymbolRefExpr>(Value))
507 if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_SBREL && !(Size == 4))
508 getContext().reportFatalError(Loc, "relocated expression must be 32-bit");
510 EmitDataMappingSymbol();
511 MCELFStreamer::EmitValueImpl(Value, Size);
514 void EmitAssemblerFlag(MCAssemblerFlag Flag) override {
515 MCELFStreamer::EmitAssemblerFlag(Flag);
518 case MCAF_SyntaxUnified:
519 return; // no-op here.
522 return; // Change to Thumb mode
525 return; // Change to ARM mode
528 case MCAF_SubsectionsViaSymbols:
534 enum ElfMappingSymbol {
541 void EmitDataMappingSymbol() {
542 if (LastEMS == EMS_Data) return;
543 EmitMappingSymbol("$d");
547 void EmitThumbMappingSymbol() {
548 if (LastEMS == EMS_Thumb) return;
549 EmitMappingSymbol("$t");
553 void EmitARMMappingSymbol() {
554 if (LastEMS == EMS_ARM) return;
555 EmitMappingSymbol("$a");
559 void EmitMappingSymbol(StringRef Name) {
560 MCSymbol *Start = getContext().createTempSymbol();
563 auto *Symbol = cast<MCSymbolELF>(getContext().getOrCreateSymbol(
564 Name + "." + Twine(MappingSymbolCounter++)));
566 getAssembler().registerSymbol(*Symbol);
567 Symbol->setType(ELF::STT_NOTYPE);
568 Symbol->setBinding(ELF::STB_LOCAL);
569 Symbol->setExternal(false);
570 AssignSection(Symbol, getCurrentSection().first);
572 const MCExpr *Value = MCSymbolRefExpr::create(Start, getContext());
573 Symbol->setVariableValue(Value);
576 void EmitThumbFunc(MCSymbol *Func) override {
577 getAssembler().setIsThumbFunc(Func);
578 EmitSymbolAttribute(Func, MCSA_ELF_TypeFunction);
581 // Helper functions for ARM exception handling directives
584 void EmitPersonalityFixup(StringRef Name);
585 void FlushPendingOffset();
586 void FlushUnwindOpcodes(bool NoHandlerData);
588 void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
589 SectionKind Kind, const MCSymbol &Fn);
590 void SwitchToExTabSection(const MCSymbol &FnStart);
591 void SwitchToExIdxSection(const MCSymbol &FnStart);
593 void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
596 int64_t MappingSymbolCounter;
598 DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
599 ElfMappingSymbol LastEMS;
601 // ARM Exception Handling Frame Information
604 const MCSymbol *Personality;
605 unsigned PersonalityIndex;
606 unsigned FPReg; // Frame pointer register
607 int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
608 int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
609 int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
612 SmallVector<uint8_t, 64> Opcodes;
613 UnwindOpcodeAssembler UnwindOpAsm;
615 } // end anonymous namespace
617 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
618 return static_cast<ARMELFStreamer &>(Streamer);
621 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
622 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
623 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
624 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
625 getStreamer().emitPersonality(Personality);
627 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
628 getStreamer().emitPersonalityIndex(Index);
630 void ARMTargetELFStreamer::emitHandlerData() {
631 getStreamer().emitHandlerData();
633 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
635 getStreamer().emitSetFP(FpReg, SpReg, Offset);
637 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
638 getStreamer().emitMovSP(Reg, Offset);
640 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
641 getStreamer().emitPad(Offset);
643 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
645 getStreamer().emitRegSave(RegList, isVector);
647 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
648 const SmallVectorImpl<uint8_t> &Opcodes) {
649 getStreamer().emitUnwindRaw(Offset, Opcodes);
651 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
652 assert(!Vendor.empty() && "Vendor cannot be empty.");
654 if (CurrentVendor == Vendor)
657 if (!CurrentVendor.empty())
658 finishAttributeSection();
660 assert(Contents.empty() &&
661 ".ARM.attributes should be flushed before changing vendor");
662 CurrentVendor = Vendor;
665 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
666 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
668 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
670 setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
672 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
674 StringRef StringValue) {
675 setAttributeItems(Attribute, IntValue, StringValue,
676 /* OverwriteExisting= */ true);
678 void ARMTargetELFStreamer::emitArch(unsigned Value) {
681 void ARMTargetELFStreamer::emitObjectArch(unsigned Value) {
684 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
685 using namespace ARMBuildAttrs;
687 setAttributeItem(CPU_name,
688 ARMTargetParser::getCPUAttr(Arch),
691 if (EmittedArch == ARM::AK_INVALID)
692 setAttributeItem(CPU_arch,
693 ARMTargetParser::getArchAttr(Arch),
696 setAttributeItem(CPU_arch,
697 ARMTargetParser::getArchAttr(EmittedArch),
707 setAttributeItem(ARM_ISA_use, Allowed, false);
712 case ARM::AK_ARMV5TE:
715 setAttributeItem(ARM_ISA_use, Allowed, false);
716 setAttributeItem(THUMB_ISA_use, Allowed, false);
719 case ARM::AK_ARMV6T2:
720 setAttributeItem(ARM_ISA_use, Allowed, false);
721 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
726 case ARM::AK_ARMV6ZK:
727 setAttributeItem(ARM_ISA_use, Allowed, false);
728 setAttributeItem(THUMB_ISA_use, Allowed, false);
729 setAttributeItem(Virtualization_use, AllowTZ, false);
733 setAttributeItem(THUMB_ISA_use, Allowed, false);
737 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
741 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
742 setAttributeItem(ARM_ISA_use, Allowed, false);
743 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
747 setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
748 setAttributeItem(ARM_ISA_use, Allowed, false);
749 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
753 setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
754 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
758 case ARM::AK_ARMV8_1A:
759 setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
760 setAttributeItem(ARM_ISA_use, Allowed, false);
761 setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
762 setAttributeItem(MPextension_use, Allowed, false);
763 setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
767 setAttributeItem(ARM_ISA_use, Allowed, false);
768 setAttributeItem(THUMB_ISA_use, Allowed, false);
769 setAttributeItem(WMMX_arch, AllowWMMXv1, false);
772 case ARM::AK_IWMMXT2:
773 setAttributeItem(ARM_ISA_use, Allowed, false);
774 setAttributeItem(THUMB_ISA_use, Allowed, false);
775 setAttributeItem(WMMX_arch, AllowWMMXv2, false);
779 report_fatal_error("Unknown Arch: " + Twine(Arch));
783 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
786 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
790 setAttributeItem(ARMBuildAttrs::FP_arch,
791 ARMBuildAttrs::AllowFPv2,
792 /* OverwriteExisting= */ false);
796 setAttributeItem(ARMBuildAttrs::FP_arch,
797 ARMBuildAttrs::AllowFPv3A,
798 /* OverwriteExisting= */ false);
801 case ARM::FK_VFPV3_D16:
802 setAttributeItem(ARMBuildAttrs::FP_arch,
803 ARMBuildAttrs::AllowFPv3B,
804 /* OverwriteExisting= */ false);
808 setAttributeItem(ARMBuildAttrs::FP_arch,
809 ARMBuildAttrs::AllowFPv4A,
810 /* OverwriteExisting= */ false);
813 case ARM::FK_VFPV4_D16:
814 setAttributeItem(ARMBuildAttrs::FP_arch,
815 ARMBuildAttrs::AllowFPv4B,
816 /* OverwriteExisting= */ false);
819 case ARM::FK_FP_ARMV8:
820 setAttributeItem(ARMBuildAttrs::FP_arch,
821 ARMBuildAttrs::AllowFPARMv8A,
822 /* OverwriteExisting= */ false);
825 // FPV5_D16 is identical to FP_ARMV8 except for the number of D registers, so
826 // uses the FP_ARMV8_D16 build attribute.
827 case ARM::FK_FPV5_D16:
828 setAttributeItem(ARMBuildAttrs::FP_arch,
829 ARMBuildAttrs::AllowFPARMv8B,
830 /* OverwriteExisting= */ false);
834 setAttributeItem(ARMBuildAttrs::FP_arch,
835 ARMBuildAttrs::AllowFPv3A,
836 /* OverwriteExisting= */ false);
837 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
838 ARMBuildAttrs::AllowNeon,
839 /* OverwriteExisting= */ false);
842 case ARM::FK_NEON_VFPV4:
843 setAttributeItem(ARMBuildAttrs::FP_arch,
844 ARMBuildAttrs::AllowFPv4A,
845 /* OverwriteExisting= */ false);
846 setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
847 ARMBuildAttrs::AllowNeon2,
848 /* OverwriteExisting= */ false);
851 case ARM::FK_NEON_FP_ARMV8:
852 case ARM::FK_CRYPTO_NEON_FP_ARMV8:
853 setAttributeItem(ARMBuildAttrs::FP_arch,
854 ARMBuildAttrs::AllowFPARMv8A,
855 /* OverwriteExisting= */ false);
856 // 'Advanced_SIMD_arch' must be emitted not here, but within
857 // ARMAsmPrinter::emitAttributes(), depending on hasV8Ops() and hasV8_1a()
860 case ARM::FK_SOFTVFP:
864 report_fatal_error("Unknown FPU: " + Twine(FPU));
868 size_t ARMTargetELFStreamer::calculateContentSize() const {
870 for (size_t i = 0; i < Contents.size(); ++i) {
871 AttributeItem item = Contents[i];
873 case AttributeItem::HiddenAttribute:
875 case AttributeItem::NumericAttribute:
876 Result += getULEB128Size(item.Tag);
877 Result += getULEB128Size(item.IntValue);
879 case AttributeItem::TextAttribute:
880 Result += getULEB128Size(item.Tag);
881 Result += item.StringValue.size() + 1; // string + '\0'
883 case AttributeItem::NumericAndTextAttributes:
884 Result += getULEB128Size(item.Tag);
885 Result += getULEB128Size(item.IntValue);
886 Result += item.StringValue.size() + 1; // string + '\0';
892 void ARMTargetELFStreamer::finishAttributeSection() {
894 // [ <section-length> "vendor-name"
895 // [ <file-tag> <size> <attribute>*
896 // | <section-tag> <size> <section-number>* 0 <attribute>*
897 // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
901 if (FPU != ARM::FK_INVALID)
902 emitFPUDefaultAttributes();
904 if (Arch != ARM::AK_INVALID)
905 emitArchDefaultAttributes();
907 if (Contents.empty())
910 std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
912 ARMELFStreamer &Streamer = getStreamer();
914 // Switch to .ARM.attributes section
915 if (AttributeSection) {
916 Streamer.SwitchSection(AttributeSection);
918 AttributeSection = Streamer.getContext().getELFSection(
919 ".ARM.attributes", ELF::SHT_ARM_ATTRIBUTES, 0);
920 Streamer.SwitchSection(AttributeSection);
923 Streamer.EmitIntValue(0x41, 1);
926 // Vendor size + Vendor name + '\0'
927 const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
930 const size_t TagHeaderSize = 1 + 4;
932 const size_t ContentsSize = calculateContentSize();
934 Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
935 Streamer.EmitBytes(CurrentVendor);
936 Streamer.EmitIntValue(0, 1); // '\0'
938 Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
939 Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
941 // Size should have been accounted for already, now
942 // emit each field as its type (ULEB or String)
943 for (size_t i = 0; i < Contents.size(); ++i) {
944 AttributeItem item = Contents[i];
945 Streamer.EmitULEB128IntValue(item.Tag);
947 default: llvm_unreachable("Invalid attribute type");
948 case AttributeItem::NumericAttribute:
949 Streamer.EmitULEB128IntValue(item.IntValue);
951 case AttributeItem::TextAttribute:
952 Streamer.EmitBytes(item.StringValue);
953 Streamer.EmitIntValue(0, 1); // '\0'
955 case AttributeItem::NumericAndTextAttributes:
956 Streamer.EmitULEB128IntValue(item.IntValue);
957 Streamer.EmitBytes(item.StringValue);
958 Streamer.EmitIntValue(0, 1); // '\0'
964 FPU = ARM::FK_INVALID;
967 void ARMTargetELFStreamer::emitLabel(MCSymbol *Symbol) {
968 ARMELFStreamer &Streamer = getStreamer();
969 if (!Streamer.IsThumb)
972 Streamer.getAssembler().registerSymbol(*Symbol);
973 unsigned Type = cast<MCSymbolELF>(Symbol)->getType();
974 if (Type == ELF::STT_FUNC || Type == ELF::STT_GNU_IFUNC)
975 Streamer.EmitThumbFunc(Symbol);
979 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
980 getStreamer().EmitFixup(S, FK_Data_4);
983 void ARMTargetELFStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
984 if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Value)) {
985 const MCSymbol &Sym = SRE->getSymbol();
986 if (!Sym.isDefined()) {
987 getStreamer().EmitAssignment(Symbol, Value);
992 getStreamer().EmitThumbFunc(Symbol);
993 getStreamer().EmitAssignment(Symbol, Value);
996 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
997 getStreamer().emitInst(Inst, Suffix);
1000 void ARMELFStreamer::FinishImpl() {
1001 MCTargetStreamer &TS = *getTargetStreamer();
1002 ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1003 ATS.finishAttributeSection();
1005 MCELFStreamer::FinishImpl();
1008 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
1012 const MCSymbol &Fn) {
1013 const MCSectionELF &FnSection =
1014 static_cast<const MCSectionELF &>(Fn.getSection());
1016 // Create the name for new section
1017 StringRef FnSecName(FnSection.getSectionName());
1018 SmallString<128> EHSecName(Prefix);
1019 if (FnSecName != ".text") {
1020 EHSecName += FnSecName;
1023 // Get .ARM.extab or .ARM.exidx section
1024 const MCSymbolELF *Group = FnSection.getGroup();
1026 Flags |= ELF::SHF_GROUP;
1027 MCSectionELF *EHSection =
1028 getContext().getELFSection(EHSecName, Type, Flags, 0, Group,
1029 FnSection.getUniqueID(), nullptr, &FnSection);
1031 assert(EHSection && "Failed to get the required EH section");
1033 // Switch to .ARM.extab or .ARM.exidx section
1034 SwitchSection(EHSection);
1035 EmitCodeAlignment(4);
1038 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
1039 SwitchToEHSection(".ARM.extab",
1042 SectionKind::getDataRel(),
1046 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
1047 SwitchToEHSection(".ARM.exidx",
1049 ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
1050 SectionKind::getDataRel(),
1053 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
1054 MCDataFragment *Frag = getOrCreateDataFragment();
1055 Frag->getFixups().push_back(MCFixup::create(Frag->getContents().size(), Expr,
1059 void ARMELFStreamer::Reset() {
1062 Personality = nullptr;
1063 PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
1072 UnwindOpAsm.Reset();
1075 void ARMELFStreamer::emitFnStart() {
1076 assert(FnStart == nullptr);
1077 FnStart = getContext().createTempSymbol();
1081 void ARMELFStreamer::emitFnEnd() {
1082 assert(FnStart && ".fnstart must precedes .fnend");
1084 // Emit unwind opcodes if there is no .handlerdata directive
1085 if (!ExTab && !CantUnwind)
1086 FlushUnwindOpcodes(true);
1088 // Emit the exception index table entry
1089 SwitchToExIdxSection(*FnStart);
1091 if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
1092 EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1094 const MCSymbolRefExpr *FnStartRef =
1095 MCSymbolRefExpr::create(FnStart,
1096 MCSymbolRefExpr::VK_ARM_PREL31,
1099 EmitValue(FnStartRef, 4);
1102 EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
1104 // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1105 const MCSymbolRefExpr *ExTabEntryRef =
1106 MCSymbolRefExpr::create(ExTab,
1107 MCSymbolRefExpr::VK_ARM_PREL31,
1109 EmitValue(ExTabEntryRef, 4);
1111 // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1112 // the second word of exception index table entry. The size of the unwind
1113 // opcodes should always be 4 bytes.
1114 assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1115 "Compact model must use __aeabi_unwind_cpp_pr0 as personality");
1116 assert(Opcodes.size() == 4u &&
1117 "Unwind opcode size for __aeabi_unwind_cpp_pr0 must be equal to 4");
1118 uint64_t Intval = Opcodes[0] |
1122 EmitIntValue(Intval, Opcodes.size());
1125 // Switch to the section containing FnStart
1126 SwitchSection(&FnStart->getSection());
1128 // Clean exception handling frame information
1132 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1134 // Add the R_ARM_NONE fixup at the same position
1135 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1136 const MCSymbol *PersonalitySym = getContext().getOrCreateSymbol(Name);
1138 const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::create(
1139 PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1141 visitUsedExpr(*PersonalityRef);
1142 MCDataFragment *DF = getOrCreateDataFragment();
1143 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
1145 MCFixup::getKindForSize(4, false)));
1148 void ARMELFStreamer::FlushPendingOffset() {
1149 if (PendingOffset != 0) {
1150 UnwindOpAsm.EmitSPOffset(-PendingOffset);
1155 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1156 // Emit the unwind opcode to restore $sp.
1158 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1159 int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1160 UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1161 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1163 FlushPendingOffset();
1166 // Finalize the unwind opcode sequence
1167 UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1169 // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1170 // section. Thus, we don't have to create an entry in the .ARM.extab
1172 if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1175 // Switch to .ARM.extab section.
1176 SwitchToExTabSection(*FnStart);
1178 // Create .ARM.extab label for offset in .ARM.exidx
1180 ExTab = getContext().createTempSymbol();
1185 const MCSymbolRefExpr *PersonalityRef =
1186 MCSymbolRefExpr::create(Personality,
1187 MCSymbolRefExpr::VK_ARM_PREL31,
1190 EmitValue(PersonalityRef, 4);
1193 // Emit unwind opcodes
1194 assert((Opcodes.size() % 4) == 0 &&
1195 "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be multiple of 4");
1196 for (unsigned I = 0; I != Opcodes.size(); I += 4) {
1197 uint64_t Intval = Opcodes[I] |
1198 Opcodes[I + 1] << 8 |
1199 Opcodes[I + 2] << 16 |
1200 Opcodes[I + 3] << 24;
1201 EmitIntValue(Intval, 4);
1204 // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1205 // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1206 // after the unwind opcodes. The handler data consists of several 32-bit
1207 // words, and should be terminated by zero.
1209 // In case that the .handlerdata directive is not specified by the
1210 // programmer, we should emit zero to terminate the handler data.
1211 if (NoHandlerData && !Personality)
1215 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1217 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1219 UnwindOpAsm.setPersonality(Per);
1222 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
1223 assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
1224 PersonalityIndex = Index;
1227 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1229 assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1230 "the operand of .setfp directive should be either $sp or $fp");
1235 if (NewSPReg == ARM::SP)
1236 FPOffset = SPOffset + Offset;
1241 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
1242 assert((Reg != ARM::SP && Reg != ARM::PC) &&
1243 "the operand of .movsp cannot be either sp or pc");
1244 assert(FPReg == ARM::SP && "current FP must be SP");
1246 FlushPendingOffset();
1249 FPOffset = SPOffset + Offset;
1251 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1252 UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1255 void ARMELFStreamer::emitPad(int64_t Offset) {
1256 // Track the change of the $sp offset
1259 // To squash multiple .pad directives, we should delay the unwind opcode
1260 // until the .save, .vsave, .handlerdata, or .fnend directives.
1261 PendingOffset -= Offset;
1264 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1266 // Collect the registers in the register list
1269 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1270 for (size_t i = 0; i < RegList.size(); ++i) {
1271 unsigned Reg = MRI->getEncodingValue(RegList[i]);
1272 assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1273 unsigned Bit = (1u << Reg);
1274 if ((Mask & Bit) == 0) {
1280 // Track the change the $sp offset: For the .save directive, the
1281 // corresponding push instruction will decrease the $sp by (4 * Count).
1282 // For the .vsave directive, the corresponding vpush instruction will
1283 // decrease $sp by (8 * Count).
1284 SPOffset -= Count * (IsVector ? 8 : 4);
1287 FlushPendingOffset();
1289 UnwindOpAsm.EmitVFPRegSave(Mask);
1291 UnwindOpAsm.EmitRegSave(Mask);
1294 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
1295 const SmallVectorImpl<uint8_t> &Opcodes) {
1296 FlushPendingOffset();
1297 SPOffset = SPOffset - Offset;
1298 UnwindOpAsm.EmitRaw(Opcodes);
1303 MCTargetStreamer *createARMTargetAsmStreamer(MCStreamer &S,
1304 formatted_raw_ostream &OS,
1305 MCInstPrinter *InstPrint,
1306 bool isVerboseAsm) {
1307 return new ARMTargetAsmStreamer(S, OS, *InstPrint, isVerboseAsm);
1310 MCTargetStreamer *createARMNullTargetStreamer(MCStreamer &S) {
1311 return new ARMTargetStreamer(S);
1314 MCTargetStreamer *createARMObjectTargetStreamer(MCStreamer &S,
1315 const MCSubtargetInfo &STI) {
1316 Triple TT(STI.getTargetTriple());
1317 if (TT.getObjectFormat() == Triple::ELF)
1318 return new ARMTargetELFStreamer(S);
1319 return new ARMTargetStreamer(S);
1322 MCELFStreamer *createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1323 raw_pwrite_stream &OS,
1324 MCCodeEmitter *Emitter, bool RelaxAll,
1326 ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
1327 // FIXME: This should eventually end up somewhere else where more
1328 // intelligent flag decisions can be made. For now we are just maintaining
1329 // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1330 S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1333 S->getAssembler().setRelaxAll(true);