LLVM  8.0.1
ARMELFStreamer.cpp
Go to the documentation of this file.
1 //===- lib/MC/ARMELFStreamer.cpp - ELF Object Output for ARM --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "ARMRegisterInfo.h"
17 #include "ARMUnwindOpAsm.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/BinaryFormat/ELF.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/MCELFStreamer.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCFixup.h"
33 #include "llvm/MC/MCFragment.h"
34 #include "llvm/MC/MCInst.h"
35 #include "llvm/MC/MCInstPrinter.h"
36 #include "llvm/MC/MCObjectWriter.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"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/MC/MCSymbolELF.h"
44 #include "llvm/MC/SectionKind.h"
46 #include "llvm/Support/ARMEHABI.h"
47 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/LEB128.h"
53 #include <algorithm>
54 #include <cassert>
55 #include <climits>
56 #include <cstddef>
57 #include <cstdint>
58 #include <string>
59 
60 using namespace llvm;
61 
62 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
64  "Invalid personality index");
65  return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
66 }
67 
68 namespace {
69 
70 class ARMELFStreamer;
71 
72 class ARMTargetAsmStreamer : public ARMTargetStreamer {
74  MCInstPrinter &InstPrinter;
75  bool IsVerboseAsm;
76 
77  void emitFnStart() override;
78  void emitFnEnd() override;
79  void emitCantUnwind() override;
80  void emitPersonality(const MCSymbol *Personality) override;
81  void emitPersonalityIndex(unsigned Index) override;
82  void emitHandlerData() override;
83  void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
84  void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
85  void emitPad(int64_t Offset) override;
86  void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
87  bool isVector) override;
88  void emitUnwindRaw(int64_t Offset,
89  const SmallVectorImpl<uint8_t> &Opcodes) override;
90 
91  void switchVendor(StringRef Vendor) override;
92  void emitAttribute(unsigned Attribute, unsigned Value) override;
93  void emitTextAttribute(unsigned Attribute, StringRef String) override;
94  void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
95  StringRef StringValue) override;
96  void emitArch(ARM::ArchKind Arch) override;
97  void emitArchExtension(unsigned ArchExt) override;
98  void emitObjectArch(ARM::ArchKind Arch) override;
99  void emitFPU(unsigned FPU) override;
100  void emitInst(uint32_t Inst, char Suffix = '\0') override;
101  void finishAttributeSection() override;
102 
103  void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
104  void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
105 
106 public:
107  ARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS,
108  MCInstPrinter &InstPrinter, bool VerboseAsm);
109 };
110 
111 ARMTargetAsmStreamer::ARMTargetAsmStreamer(MCStreamer &S,
113  MCInstPrinter &InstPrinter,
114  bool VerboseAsm)
115  : ARMTargetStreamer(S), OS(OS), InstPrinter(InstPrinter),
116  IsVerboseAsm(VerboseAsm) {}
117 
118 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
119 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
120 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
121 
122 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
123  OS << "\t.personality " << Personality->getName() << '\n';
124 }
125 
126 void ARMTargetAsmStreamer::emitPersonalityIndex(unsigned Index) {
127  OS << "\t.personalityindex " << Index << '\n';
128 }
129 
130 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
131 
132 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
133  int64_t Offset) {
134  OS << "\t.setfp\t";
135  InstPrinter.printRegName(OS, FpReg);
136  OS << ", ";
137  InstPrinter.printRegName(OS, SpReg);
138  if (Offset)
139  OS << ", #" << Offset;
140  OS << '\n';
141 }
142 
143 void ARMTargetAsmStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
144  assert((Reg != ARM::SP && Reg != ARM::PC) &&
145  "the operand of .movsp cannot be either sp or pc");
146 
147  OS << "\t.movsp\t";
148  InstPrinter.printRegName(OS, Reg);
149  if (Offset)
150  OS << ", #" << Offset;
151  OS << '\n';
152 }
153 
154 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
155  OS << "\t.pad\t#" << Offset << '\n';
156 }
157 
158 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
159  bool isVector) {
160  assert(RegList.size() && "RegList should not be empty");
161  if (isVector)
162  OS << "\t.vsave\t{";
163  else
164  OS << "\t.save\t{";
165 
166  InstPrinter.printRegName(OS, RegList[0]);
167 
168  for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
169  OS << ", ";
170  InstPrinter.printRegName(OS, RegList[i]);
171  }
172 
173  OS << "}\n";
174 }
175 
176 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {}
177 
178 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
179  OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value);
180  if (IsVerboseAsm) {
182  if (!Name.empty())
183  OS << "\t@ " << Name;
184  }
185  OS << "\n";
186 }
187 
188 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
189  StringRef String) {
190  switch (Attribute) {
192  OS << "\t.cpu\t" << String.lower();
193  break;
194  default:
195  OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
196  if (IsVerboseAsm) {
198  if (!Name.empty())
199  OS << "\t@ " << Name;
200  }
201  break;
202  }
203  OS << "\n";
204 }
205 
206 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
207  unsigned IntValue,
208  StringRef StringValue) {
209  switch (Attribute) {
210  default: llvm_unreachable("unsupported multi-value attribute in asm mode");
212  OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
213  if (!StringValue.empty())
214  OS << ", \"" << StringValue << "\"";
215  if (IsVerboseAsm)
216  OS << "\t@ " << ARMBuildAttrs::AttrTypeAsString(Attribute);
217  break;
218  }
219  OS << "\n";
220 }
221 
222 void ARMTargetAsmStreamer::emitArch(ARM::ArchKind Arch) {
223  OS << "\t.arch\t" << ARM::getArchName(Arch) << "\n";
224 }
225 
226 void ARMTargetAsmStreamer::emitArchExtension(unsigned ArchExt) {
227  OS << "\t.arch_extension\t" << ARM::getArchExtName(ArchExt) << "\n";
228 }
229 
230 void ARMTargetAsmStreamer::emitObjectArch(ARM::ArchKind Arch) {
231  OS << "\t.object_arch\t" << ARM::getArchName(Arch) << '\n';
232 }
233 
234 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
235  OS << "\t.fpu\t" << ARM::getFPUName(FPU) << "\n";
236 }
237 
238 void ARMTargetAsmStreamer::finishAttributeSection() {}
239 
240 void
241 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
242  OS << "\t.tlsdescseq\t" << S->getSymbol().getName();
243 }
244 
245 void ARMTargetAsmStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
246  const MCAsmInfo *MAI = Streamer.getContext().getAsmInfo();
247 
248  OS << "\t.thumb_set\t";
249  Symbol->print(OS, MAI);
250  OS << ", ";
251  Value->print(OS, MAI);
252  OS << '\n';
253 }
254 
255 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
256  OS << "\t.inst";
257  if (Suffix)
258  OS << "." << Suffix;
259  OS << "\t0x" << Twine::utohexstr(Inst) << "\n";
260 }
261 
262 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
263  const SmallVectorImpl<uint8_t> &Opcodes) {
264  OS << "\t.unwind_raw " << Offset;
265  for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
266  OCE = Opcodes.end();
267  OCI != OCE; ++OCI)
268  OS << ", 0x" << Twine::utohexstr(*OCI);
269  OS << '\n';
270 }
271 
272 class ARMTargetELFStreamer : public ARMTargetStreamer {
273 private:
274  // This structure holds all attributes, accounting for
275  // their string/numeric value, so we can later emit them
276  // in declaration order, keeping all in the same vector
277  struct AttributeItem {
278  enum {
279  HiddenAttribute = 0,
280  NumericAttribute,
281  TextAttribute,
282  NumericAndTextAttributes
283  } Type;
284  unsigned Tag;
285  unsigned IntValue;
286  std::string StringValue;
287 
288  static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
289  // The conformance tag must be emitted first when serialised
290  // into an object file. Specifically, the addenda to the ARM ABI
291  // states that (2.3.7.4):
292  //
293  // "To simplify recognition by consumers in the common case of
294  // claiming conformity for the whole file, this tag should be
295  // emitted first in a file-scope sub-subsection of the first
296  // public subsection of the attributes section."
297  //
298  // So it is special-cased in this comparison predicate when the
299  // attributes are sorted in finishAttributeSection().
300  return (RHS.Tag != ARMBuildAttrs::conformance) &&
301  ((LHS.Tag == ARMBuildAttrs::conformance) || (LHS.Tag < RHS.Tag));
302  }
303  };
304 
305  StringRef CurrentVendor;
306  unsigned FPU = ARM::FK_INVALID;
310 
311  MCSection *AttributeSection = nullptr;
312 
313  AttributeItem *getAttributeItem(unsigned Attribute) {
314  for (size_t i = 0; i < Contents.size(); ++i)
315  if (Contents[i].Tag == Attribute)
316  return &Contents[i];
317  return nullptr;
318  }
319 
320  void setAttributeItem(unsigned Attribute, unsigned Value,
321  bool OverwriteExisting) {
322  // Look for existing attribute item
323  if (AttributeItem *Item = getAttributeItem(Attribute)) {
324  if (!OverwriteExisting)
325  return;
326  Item->Type = AttributeItem::NumericAttribute;
327  Item->IntValue = Value;
328  return;
329  }
330 
331  // Create new attribute item
332  AttributeItem Item = {
333  AttributeItem::NumericAttribute,
334  Attribute,
335  Value,
336  StringRef("")
337  };
338  Contents.push_back(Item);
339  }
340 
341  void setAttributeItem(unsigned Attribute, StringRef Value,
342  bool OverwriteExisting) {
343  // Look for existing attribute item
344  if (AttributeItem *Item = getAttributeItem(Attribute)) {
345  if (!OverwriteExisting)
346  return;
347  Item->Type = AttributeItem::TextAttribute;
348  Item->StringValue = Value;
349  return;
350  }
351 
352  // Create new attribute item
353  AttributeItem Item = {
354  AttributeItem::TextAttribute,
355  Attribute,
356  0,
357  Value
358  };
359  Contents.push_back(Item);
360  }
361 
362  void setAttributeItems(unsigned Attribute, unsigned IntValue,
363  StringRef StringValue, bool OverwriteExisting) {
364  // Look for existing attribute item
365  if (AttributeItem *Item = getAttributeItem(Attribute)) {
366  if (!OverwriteExisting)
367  return;
368  Item->Type = AttributeItem::NumericAndTextAttributes;
369  Item->IntValue = IntValue;
370  Item->StringValue = StringValue;
371  return;
372  }
373 
374  // Create new attribute item
375  AttributeItem Item = {
376  AttributeItem::NumericAndTextAttributes,
377  Attribute,
378  IntValue,
379  StringValue
380  };
381  Contents.push_back(Item);
382  }
383 
384  void emitArchDefaultAttributes();
385  void emitFPUDefaultAttributes();
386 
387  ARMELFStreamer &getStreamer();
388 
389  void emitFnStart() override;
390  void emitFnEnd() override;
391  void emitCantUnwind() override;
392  void emitPersonality(const MCSymbol *Personality) override;
393  void emitPersonalityIndex(unsigned Index) override;
394  void emitHandlerData() override;
395  void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
396  void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
397  void emitPad(int64_t Offset) override;
398  void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
399  bool isVector) override;
400  void emitUnwindRaw(int64_t Offset,
401  const SmallVectorImpl<uint8_t> &Opcodes) override;
402 
403  void switchVendor(StringRef Vendor) override;
404  void emitAttribute(unsigned Attribute, unsigned Value) override;
405  void emitTextAttribute(unsigned Attribute, StringRef String) override;
406  void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
407  StringRef StringValue) override;
408  void emitArch(ARM::ArchKind Arch) override;
409  void emitObjectArch(ARM::ArchKind Arch) override;
410  void emitFPU(unsigned FPU) override;
411  void emitInst(uint32_t Inst, char Suffix = '\0') override;
412  void finishAttributeSection() override;
413  void emitLabel(MCSymbol *Symbol) override;
414 
415  void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
416  void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
417 
418  size_t calculateContentSize() const;
419 
420  // Reset state between object emissions
421  void reset() override;
422 
423 public:
424  ARMTargetELFStreamer(MCStreamer &S)
425  : ARMTargetStreamer(S), CurrentVendor("aeabi") {}
426 };
427 
428 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
429 /// the appropriate points in the object files. These symbols are defined in the
430 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
431 ///
432 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
433 /// region of ARM code, Thumb code or data in a section. In practice, this
434 /// emission does not rely on explicit assembler directives but on inherent
435 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
436 /// r0, r0, r0" an instruction).
437 ///
438 /// As a result this system is orthogonal to the DataRegion infrastructure used
439 /// by MachO. Beware!
440 class ARMELFStreamer : public MCELFStreamer {
441 public:
442  friend class ARMTargetELFStreamer;
443 
444  ARMELFStreamer(MCContext &Context, std::unique_ptr<MCAsmBackend> TAB,
445  std::unique_ptr<MCObjectWriter> OW, std::unique_ptr<MCCodeEmitter> Emitter,
446  bool IsThumb)
447  : MCELFStreamer(Context, std::move(TAB), std::move(OW), std::move(Emitter)),
448  IsThumb(IsThumb) {
449  EHReset();
450  }
451 
452  ~ARMELFStreamer() override = default;
453 
454  void FinishImpl() override;
455 
456  // ARM exception handling directives
457  void emitFnStart();
458  void emitFnEnd();
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);
468  void emitFill(const MCExpr &NumBytes, uint64_t FillValue,
469  SMLoc Loc) override {
470  EmitDataMappingSymbol();
471  MCObjectStreamer::emitFill(NumBytes, FillValue, Loc);
472  }
473 
474  void ChangeSection(MCSection *Section, const MCExpr *Subsection) override {
475  LastMappingSymbols[getCurrentSection().first] = std::move(LastEMSInfo);
476  MCELFStreamer::ChangeSection(Section, Subsection);
477  auto LastMappingSymbol = LastMappingSymbols.find(Section);
478  if (LastMappingSymbol != LastMappingSymbols.end()) {
479  LastEMSInfo = std::move(LastMappingSymbol->second);
480  return;
481  }
482  LastEMSInfo.reset(new ElfMappingSymbolInfo(SMLoc(), nullptr, 0));
483  }
484 
485  /// This function is the one used to emit instruction data into the ELF
486  /// streamer. We override it to add the appropriate mapping symbol if
487  /// necessary.
488  void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
489  bool) override {
490  if (IsThumb)
491  EmitThumbMappingSymbol();
492  else
493  EmitARMMappingSymbol();
494 
496  }
497 
498  void emitInst(uint32_t Inst, char Suffix) {
499  unsigned Size;
500  char Buffer[4];
501  const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
502 
503  switch (Suffix) {
504  case '\0':
505  Size = 4;
506 
507  assert(!IsThumb);
508  EmitARMMappingSymbol();
509  for (unsigned II = 0, IE = Size; II != IE; II++) {
510  const unsigned I = LittleEndian ? (Size - II - 1) : II;
511  Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
512  }
513 
514  break;
515  case 'n':
516  case 'w':
517  Size = (Suffix == 'n' ? 2 : 4);
518 
519  assert(IsThumb);
520  EmitThumbMappingSymbol();
521  // Thumb wide instructions are emitted as a pair of 16-bit words of the
522  // appropriate endianness.
523  for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
524  const unsigned I0 = LittleEndian ? II + 0 : II + 1;
525  const unsigned I1 = LittleEndian ? II + 1 : II + 0;
526  Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
527  Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
528  }
529 
530  break;
531  default:
532  llvm_unreachable("Invalid Suffix");
533  }
534 
535  MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
536  }
537 
538  /// This is one of the functions used to emit data into an ELF section, so the
539  /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
540  /// necessary.
541  void EmitBytes(StringRef Data) override {
542  EmitDataMappingSymbol();
544  }
545 
546  void FlushPendingMappingSymbol() {
547  if (!LastEMSInfo->hasInfo())
548  return;
549  ElfMappingSymbolInfo *EMS = LastEMSInfo.get();
550  EmitMappingSymbol("$d", EMS->Loc, EMS->F, EMS->Offset);
551  EMS->resetInfo();
552  }
553 
554  /// This is one of the functions used to emit data into an ELF section, so the
555  /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
556  /// necessary.
557  void EmitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc) override {
558  if (const MCSymbolRefExpr *SRE = dyn_cast_or_null<MCSymbolRefExpr>(Value)) {
559  if (SRE->getKind() == MCSymbolRefExpr::VK_ARM_SBREL && !(Size == 4)) {
560  getContext().reportError(Loc, "relocated expression must be 32-bit");
561  return;
562  }
563  getOrCreateDataFragment();
564  }
565 
566  EmitDataMappingSymbol();
567  MCELFStreamer::EmitValueImpl(Value, Size, Loc);
568  }
569 
570  void EmitAssemblerFlag(MCAssemblerFlag Flag) override {
572 
573  switch (Flag) {
574  case MCAF_SyntaxUnified:
575  return; // no-op here.
576  case MCAF_Code16:
577  IsThumb = true;
578  return; // Change to Thumb mode
579  case MCAF_Code32:
580  IsThumb = false;
581  return; // Change to ARM mode
582  case MCAF_Code64:
583  return;
585  return;
586  }
587  }
588 
589 private:
590  enum ElfMappingSymbol {
591  EMS_None,
592  EMS_ARM,
593  EMS_Thumb,
594  EMS_Data
595  };
596 
597  struct ElfMappingSymbolInfo {
598  explicit ElfMappingSymbolInfo(SMLoc Loc, MCFragment *F, uint64_t O)
599  : Loc(Loc), F(F), Offset(O), State(EMS_None) {}
600  void resetInfo() {
601  F = nullptr;
602  Offset = 0;
603  }
604  bool hasInfo() { return F != nullptr; }
605  SMLoc Loc;
606  MCFragment *F;
607  uint64_t Offset;
608  ElfMappingSymbol State;
609  };
610 
611  void EmitDataMappingSymbol() {
612  if (LastEMSInfo->State == EMS_Data)
613  return;
614  else if (LastEMSInfo->State == EMS_None) {
615  // This is a tentative symbol, it won't really be emitted until it's
616  // actually needed.
617  ElfMappingSymbolInfo *EMS = LastEMSInfo.get();
618  auto *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
619  if (!DF)
620  return;
621  EMS->Loc = SMLoc();
622  EMS->F = getCurrentFragment();
623  EMS->Offset = DF->getContents().size();
624  LastEMSInfo->State = EMS_Data;
625  return;
626  }
627  EmitMappingSymbol("$d");
628  LastEMSInfo->State = EMS_Data;
629  }
630 
631  void EmitThumbMappingSymbol() {
632  if (LastEMSInfo->State == EMS_Thumb)
633  return;
634  FlushPendingMappingSymbol();
635  EmitMappingSymbol("$t");
636  LastEMSInfo->State = EMS_Thumb;
637  }
638 
639  void EmitARMMappingSymbol() {
640  if (LastEMSInfo->State == EMS_ARM)
641  return;
642  FlushPendingMappingSymbol();
643  EmitMappingSymbol("$a");
644  LastEMSInfo->State = EMS_ARM;
645  }
646 
647  void EmitMappingSymbol(StringRef Name) {
648  auto *Symbol = cast<MCSymbolELF>(getContext().getOrCreateSymbol(
649  Name + "." + Twine(MappingSymbolCounter++)));
650  EmitLabel(Symbol);
651 
652  Symbol->setType(ELF::STT_NOTYPE);
653  Symbol->setBinding(ELF::STB_LOCAL);
654  Symbol->setExternal(false);
655  }
656 
657  void EmitMappingSymbol(StringRef Name, SMLoc Loc, MCFragment *F,
658  uint64_t Offset) {
659  auto *Symbol = cast<MCSymbolELF>(getContext().getOrCreateSymbol(
660  Name + "." + Twine(MappingSymbolCounter++)));
661  EmitLabel(Symbol, Loc, F);
662  Symbol->setType(ELF::STT_NOTYPE);
663  Symbol->setBinding(ELF::STB_LOCAL);
664  Symbol->setExternal(false);
665  Symbol->setOffset(Offset);
666  }
667 
668  void EmitThumbFunc(MCSymbol *Func) override {
669  getAssembler().setIsThumbFunc(Func);
670  EmitSymbolAttribute(Func, MCSA_ELF_TypeFunction);
671  }
672 
673  // Helper functions for ARM exception handling directives
674  void EHReset();
675 
676  // Reset state between object emissions
677  void reset() override;
678 
679  void EmitPersonalityFixup(StringRef Name);
680  void FlushPendingOffset();
681  void FlushUnwindOpcodes(bool NoHandlerData);
682 
683  void SwitchToEHSection(StringRef Prefix, unsigned Type, unsigned Flags,
684  SectionKind Kind, const MCSymbol &Fn);
685  void SwitchToExTabSection(const MCSymbol &FnStart);
686  void SwitchToExIdxSection(const MCSymbol &FnStart);
687 
688  void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
689 
690  bool IsThumb;
691  int64_t MappingSymbolCounter = 0;
692 
694  LastMappingSymbols;
695 
696  std::unique_ptr<ElfMappingSymbolInfo> LastEMSInfo;
697 
698  // ARM Exception Handling Frame Information
699  MCSymbol *ExTab;
700  MCSymbol *FnStart;
701  const MCSymbol *Personality;
702  unsigned PersonalityIndex;
703  unsigned FPReg; // Frame pointer register
704  int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
705  int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
706  int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
707  bool UsedFP;
708  bool CantUnwind;
709  SmallVector<uint8_t, 64> Opcodes;
710  UnwindOpcodeAssembler UnwindOpAsm;
711 };
712 
713 } // end anonymous namespace
714 
715 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
716  return static_cast<ARMELFStreamer &>(Streamer);
717 }
718 
719 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
720 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
721 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
722 
723 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
724  getStreamer().emitPersonality(Personality);
725 }
726 
727 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
728  getStreamer().emitPersonalityIndex(Index);
729 }
730 
731 void ARMTargetELFStreamer::emitHandlerData() {
732  getStreamer().emitHandlerData();
733 }
734 
735 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
736  int64_t Offset) {
737  getStreamer().emitSetFP(FpReg, SpReg, Offset);
738 }
739 
740 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
741  getStreamer().emitMovSP(Reg, Offset);
742 }
743 
744 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
745  getStreamer().emitPad(Offset);
746 }
747 
748 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
749  bool isVector) {
750  getStreamer().emitRegSave(RegList, isVector);
751 }
752 
753 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
754  const SmallVectorImpl<uint8_t> &Opcodes) {
755  getStreamer().emitUnwindRaw(Offset, Opcodes);
756 }
757 
758 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
759  assert(!Vendor.empty() && "Vendor cannot be empty.");
760 
761  if (CurrentVendor == Vendor)
762  return;
763 
764  if (!CurrentVendor.empty())
765  finishAttributeSection();
766 
767  assert(Contents.empty() &&
768  ".ARM.attributes should be flushed before changing vendor");
769  CurrentVendor = Vendor;
770 
771 }
772 
773 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
774  setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
775 }
776 
777 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
778  StringRef Value) {
779  setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
780 }
781 
782 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
783  unsigned IntValue,
784  StringRef StringValue) {
785  setAttributeItems(Attribute, IntValue, StringValue,
786  /* OverwriteExisting= */ true);
787 }
788 
789 void ARMTargetELFStreamer::emitArch(ARM::ArchKind Value) {
790  Arch = Value;
791 }
792 
793 void ARMTargetELFStreamer::emitObjectArch(ARM::ArchKind Value) {
794  EmittedArch = Value;
795 }
796 
797 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
798  using namespace ARMBuildAttrs;
799 
800  setAttributeItem(CPU_name,
801  ARM::getCPUAttr(Arch),
802  false);
803 
804  if (EmittedArch == ARM::ArchKind::INVALID)
805  setAttributeItem(CPU_arch,
806  ARM::getArchAttr(Arch),
807  false);
808  else
809  setAttributeItem(CPU_arch,
810  ARM::getArchAttr(EmittedArch),
811  false);
812 
813  switch (Arch) {
814  case ARM::ArchKind::ARMV2:
815  case ARM::ArchKind::ARMV2A:
816  case ARM::ArchKind::ARMV3:
817  case ARM::ArchKind::ARMV3M:
818  case ARM::ArchKind::ARMV4:
819  setAttributeItem(ARM_ISA_use, Allowed, false);
820  break;
821 
822  case ARM::ArchKind::ARMV4T:
823  case ARM::ArchKind::ARMV5T:
824  case ARM::ArchKind::ARMV5TE:
825  case ARM::ArchKind::ARMV6:
826  setAttributeItem(ARM_ISA_use, Allowed, false);
827  setAttributeItem(THUMB_ISA_use, Allowed, false);
828  break;
829 
830  case ARM::ArchKind::ARMV6T2:
831  setAttributeItem(ARM_ISA_use, Allowed, false);
832  setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
833  break;
834 
835  case ARM::ArchKind::ARMV6K:
836  case ARM::ArchKind::ARMV6KZ:
837  setAttributeItem(ARM_ISA_use, Allowed, false);
838  setAttributeItem(THUMB_ISA_use, Allowed, false);
839  setAttributeItem(Virtualization_use, AllowTZ, false);
840  break;
841 
842  case ARM::ArchKind::ARMV6M:
843  setAttributeItem(THUMB_ISA_use, Allowed, false);
844  break;
845 
846  case ARM::ArchKind::ARMV7A:
847  setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
848  setAttributeItem(ARM_ISA_use, Allowed, false);
849  setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
850  break;
851 
852  case ARM::ArchKind::ARMV7R:
853  setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
854  setAttributeItem(ARM_ISA_use, Allowed, false);
855  setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
856  break;
857 
858  case ARM::ArchKind::ARMV7EM:
859  case ARM::ArchKind::ARMV7M:
860  setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
861  setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
862  break;
863 
864  case ARM::ArchKind::ARMV8A:
865  case ARM::ArchKind::ARMV8_1A:
866  case ARM::ArchKind::ARMV8_2A:
867  case ARM::ArchKind::ARMV8_3A:
868  case ARM::ArchKind::ARMV8_4A:
869  case ARM::ArchKind::ARMV8_5A:
870  setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
871  setAttributeItem(ARM_ISA_use, Allowed, false);
872  setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
873  setAttributeItem(MPextension_use, Allowed, false);
874  setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
875  break;
876 
877  case ARM::ArchKind::ARMV8MBaseline:
878  case ARM::ArchKind::ARMV8MMainline:
879  setAttributeItem(THUMB_ISA_use, AllowThumbDerived, false);
880  setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
881  break;
882 
883  case ARM::ArchKind::IWMMXT:
884  setAttributeItem(ARM_ISA_use, Allowed, false);
885  setAttributeItem(THUMB_ISA_use, Allowed, false);
886  setAttributeItem(WMMX_arch, AllowWMMXv1, false);
887  break;
888 
889  case ARM::ArchKind::IWMMXT2:
890  setAttributeItem(ARM_ISA_use, Allowed, false);
891  setAttributeItem(THUMB_ISA_use, Allowed, false);
892  setAttributeItem(WMMX_arch, AllowWMMXv2, false);
893  break;
894 
895  default:
896  report_fatal_error("Unknown Arch: " + Twine(ARM::getArchName(Arch)));
897  break;
898  }
899 }
900 
901 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
902  FPU = Value;
903 }
904 
905 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
906  switch (FPU) {
907  case ARM::FK_VFP:
908  case ARM::FK_VFPV2:
909  setAttributeItem(ARMBuildAttrs::FP_arch,
911  /* OverwriteExisting= */ false);
912  break;
913 
914  case ARM::FK_VFPV3:
915  setAttributeItem(ARMBuildAttrs::FP_arch,
917  /* OverwriteExisting= */ false);
918  break;
919 
920  case ARM::FK_VFPV3_FP16:
921  setAttributeItem(ARMBuildAttrs::FP_arch,
923  /* OverwriteExisting= */ false);
924  setAttributeItem(ARMBuildAttrs::FP_HP_extension,
926  /* OverwriteExisting= */ false);
927  break;
928 
929  case ARM::FK_VFPV3_D16:
930  setAttributeItem(ARMBuildAttrs::FP_arch,
932  /* OverwriteExisting= */ false);
933  break;
934 
935  case ARM::FK_VFPV3_D16_FP16:
936  setAttributeItem(ARMBuildAttrs::FP_arch,
938  /* OverwriteExisting= */ false);
939  setAttributeItem(ARMBuildAttrs::FP_HP_extension,
941  /* OverwriteExisting= */ false);
942  break;
943 
944  case ARM::FK_VFPV3XD:
945  setAttributeItem(ARMBuildAttrs::FP_arch,
947  /* OverwriteExisting= */ false);
948  break;
949  case ARM::FK_VFPV3XD_FP16:
950  setAttributeItem(ARMBuildAttrs::FP_arch,
952  /* OverwriteExisting= */ false);
953  setAttributeItem(ARMBuildAttrs::FP_HP_extension,
955  /* OverwriteExisting= */ false);
956  break;
957 
958  case ARM::FK_VFPV4:
959  setAttributeItem(ARMBuildAttrs::FP_arch,
961  /* OverwriteExisting= */ false);
962  break;
963 
964  // ABI_HardFP_use is handled in ARMAsmPrinter, so _SP_D16 is treated the same
965  // as _D16 here.
966  case ARM::FK_FPV4_SP_D16:
967  case ARM::FK_VFPV4_D16:
968  setAttributeItem(ARMBuildAttrs::FP_arch,
970  /* OverwriteExisting= */ false);
971  break;
972 
973  case ARM::FK_FP_ARMV8:
974  setAttributeItem(ARMBuildAttrs::FP_arch,
976  /* OverwriteExisting= */ false);
977  break;
978 
979  // FPV5_D16 is identical to FP_ARMV8 except for the number of D registers, so
980  // uses the FP_ARMV8_D16 build attribute.
981  case ARM::FK_FPV5_SP_D16:
982  case ARM::FK_FPV5_D16:
983  setAttributeItem(ARMBuildAttrs::FP_arch,
985  /* OverwriteExisting= */ false);
986  break;
987 
988  case ARM::FK_NEON:
989  setAttributeItem(ARMBuildAttrs::FP_arch,
991  /* OverwriteExisting= */ false);
992  setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
994  /* OverwriteExisting= */ false);
995  break;
996 
997  case ARM::FK_NEON_FP16:
998  setAttributeItem(ARMBuildAttrs::FP_arch,
1000  /* OverwriteExisting= */ false);
1001  setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
1003  /* OverwriteExisting= */ false);
1004  setAttributeItem(ARMBuildAttrs::FP_HP_extension,
1006  /* OverwriteExisting= */ false);
1007  break;
1008 
1009  case ARM::FK_NEON_VFPV4:
1010  setAttributeItem(ARMBuildAttrs::FP_arch,
1012  /* OverwriteExisting= */ false);
1013  setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
1015  /* OverwriteExisting= */ false);
1016  break;
1017 
1018  case ARM::FK_NEON_FP_ARMV8:
1019  case ARM::FK_CRYPTO_NEON_FP_ARMV8:
1020  setAttributeItem(ARMBuildAttrs::FP_arch,
1022  /* OverwriteExisting= */ false);
1023  // 'Advanced_SIMD_arch' must be emitted not here, but within
1024  // ARMAsmPrinter::emitAttributes(), depending on hasV8Ops() and hasV8_1a()
1025  break;
1026 
1027  case ARM::FK_SOFTVFP:
1028  case ARM::FK_NONE:
1029  break;
1030 
1031  default:
1032  report_fatal_error("Unknown FPU: " + Twine(FPU));
1033  break;
1034  }
1035 }
1036 
1037 size_t ARMTargetELFStreamer::calculateContentSize() const {
1038  size_t Result = 0;
1039  for (size_t i = 0; i < Contents.size(); ++i) {
1040  AttributeItem item = Contents[i];
1041  switch (item.Type) {
1042  case AttributeItem::HiddenAttribute:
1043  break;
1044  case AttributeItem::NumericAttribute:
1045  Result += getULEB128Size(item.Tag);
1046  Result += getULEB128Size(item.IntValue);
1047  break;
1048  case AttributeItem::TextAttribute:
1049  Result += getULEB128Size(item.Tag);
1050  Result += item.StringValue.size() + 1; // string + '\0'
1051  break;
1052  case AttributeItem::NumericAndTextAttributes:
1053  Result += getULEB128Size(item.Tag);
1054  Result += getULEB128Size(item.IntValue);
1055  Result += item.StringValue.size() + 1; // string + '\0';
1056  break;
1057  }
1058  }
1059  return Result;
1060 }
1061 
1062 void ARMTargetELFStreamer::finishAttributeSection() {
1063  // <format-version>
1064  // [ <section-length> "vendor-name"
1065  // [ <file-tag> <size> <attribute>*
1066  // | <section-tag> <size> <section-number>* 0 <attribute>*
1067  // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
1068  // ]+
1069  // ]*
1070 
1071  if (FPU != ARM::FK_INVALID)
1072  emitFPUDefaultAttributes();
1073 
1074  if (Arch != ARM::ArchKind::INVALID)
1075  emitArchDefaultAttributes();
1076 
1077  if (Contents.empty())
1078  return;
1079 
1080  llvm::sort(Contents, AttributeItem::LessTag);
1081 
1082  ARMELFStreamer &Streamer = getStreamer();
1083 
1084  // Switch to .ARM.attributes section
1085  if (AttributeSection) {
1086  Streamer.SwitchSection(AttributeSection);
1087  } else {
1088  AttributeSection = Streamer.getContext().getELFSection(
1089  ".ARM.attributes", ELF::SHT_ARM_ATTRIBUTES, 0);
1090  Streamer.SwitchSection(AttributeSection);
1091 
1092  // Format version
1093  Streamer.EmitIntValue(0x41, 1);
1094  }
1095 
1096  // Vendor size + Vendor name + '\0'
1097  const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
1098 
1099  // Tag + Tag Size
1100  const size_t TagHeaderSize = 1 + 4;
1101 
1102  const size_t ContentsSize = calculateContentSize();
1103 
1104  Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
1105  Streamer.EmitBytes(CurrentVendor);
1106  Streamer.EmitIntValue(0, 1); // '\0'
1107 
1108  Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
1109  Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
1110 
1111  // Size should have been accounted for already, now
1112  // emit each field as its type (ULEB or String)
1113  for (size_t i = 0; i < Contents.size(); ++i) {
1114  AttributeItem item = Contents[i];
1115  Streamer.EmitULEB128IntValue(item.Tag);
1116  switch (item.Type) {
1117  default: llvm_unreachable("Invalid attribute type");
1118  case AttributeItem::NumericAttribute:
1119  Streamer.EmitULEB128IntValue(item.IntValue);
1120  break;
1121  case AttributeItem::TextAttribute:
1122  Streamer.EmitBytes(item.StringValue);
1123  Streamer.EmitIntValue(0, 1); // '\0'
1124  break;
1125  case AttributeItem::NumericAndTextAttributes:
1126  Streamer.EmitULEB128IntValue(item.IntValue);
1127  Streamer.EmitBytes(item.StringValue);
1128  Streamer.EmitIntValue(0, 1); // '\0'
1129  break;
1130  }
1131  }
1132 
1133  Contents.clear();
1134  FPU = ARM::FK_INVALID;
1135 }
1136 
1137 void ARMTargetELFStreamer::emitLabel(MCSymbol *Symbol) {
1138  ARMELFStreamer &Streamer = getStreamer();
1139  if (!Streamer.IsThumb)
1140  return;
1141 
1142  Streamer.getAssembler().registerSymbol(*Symbol);
1143  unsigned Type = cast<MCSymbolELF>(Symbol)->getType();
1144  if (Type == ELF::STT_FUNC || Type == ELF::STT_GNU_IFUNC)
1145  Streamer.EmitThumbFunc(Symbol);
1146 }
1147 
1148 void
1149 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
1150  getStreamer().EmitFixup(S, FK_Data_4);
1151 }
1152 
1153 void ARMTargetELFStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
1154  if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Value)) {
1155  const MCSymbol &Sym = SRE->getSymbol();
1156  if (!Sym.isDefined()) {
1157  getStreamer().EmitAssignment(Symbol, Value);
1158  return;
1159  }
1160  }
1161 
1162  getStreamer().EmitThumbFunc(Symbol);
1163  getStreamer().EmitAssignment(Symbol, Value);
1164 }
1165 
1166 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
1167  getStreamer().emitInst(Inst, Suffix);
1168 }
1169 
1170 void ARMTargetELFStreamer::reset() { AttributeSection = nullptr; }
1171 
1172 void ARMELFStreamer::FinishImpl() {
1173  MCTargetStreamer &TS = *getTargetStreamer();
1174  ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1175  ATS.finishAttributeSection();
1176 
1178 }
1179 
1180 void ARMELFStreamer::reset() {
1181  MCTargetStreamer &TS = *getTargetStreamer();
1182  ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1183  ATS.reset();
1184  MappingSymbolCounter = 0;
1186  LastMappingSymbols.clear();
1187  LastEMSInfo.reset();
1188  // MCELFStreamer clear's the assembler's e_flags. However, for
1189  // arm we manually set the ABI version on streamer creation, so
1190  // do the same here
1191  getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1192 }
1193 
1194 inline void ARMELFStreamer::SwitchToEHSection(StringRef Prefix,
1195  unsigned Type,
1196  unsigned Flags,
1197  SectionKind Kind,
1198  const MCSymbol &Fn) {
1199  const MCSectionELF &FnSection =
1200  static_cast<const MCSectionELF &>(Fn.getSection());
1201 
1202  // Create the name for new section
1203  StringRef FnSecName(FnSection.getSectionName());
1204  SmallString<128> EHSecName(Prefix);
1205  if (FnSecName != ".text") {
1206  EHSecName += FnSecName;
1207  }
1208 
1209  // Get .ARM.extab or .ARM.exidx section
1210  const MCSymbolELF *Group = FnSection.getGroup();
1211  if (Group)
1212  Flags |= ELF::SHF_GROUP;
1213  MCSectionELF *EHSection = getContext().getELFSection(
1214  EHSecName, Type, Flags, 0, Group, FnSection.getUniqueID(),
1215  static_cast<const MCSymbolELF *>(&Fn));
1216 
1217  assert(EHSection && "Failed to get the required EH section");
1218 
1219  // Switch to .ARM.extab or .ARM.exidx section
1220  SwitchSection(EHSection);
1221  EmitCodeAlignment(4);
1222 }
1223 
1224 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
1225  SwitchToEHSection(".ARM.extab", ELF::SHT_PROGBITS, ELF::SHF_ALLOC,
1226  SectionKind::getData(), FnStart);
1227 }
1228 
1229 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
1230  SwitchToEHSection(".ARM.exidx", ELF::SHT_ARM_EXIDX,
1232  SectionKind::getData(), FnStart);
1233 }
1234 
1235 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
1236  MCDataFragment *Frag = getOrCreateDataFragment();
1237  Frag->getFixups().push_back(MCFixup::create(Frag->getContents().size(), Expr,
1238  Kind));
1239 }
1240 
1241 void ARMELFStreamer::EHReset() {
1242  ExTab = nullptr;
1243  FnStart = nullptr;
1244  Personality = nullptr;
1245  PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
1246  FPReg = ARM::SP;
1247  FPOffset = 0;
1248  SPOffset = 0;
1249  PendingOffset = 0;
1250  UsedFP = false;
1251  CantUnwind = false;
1252 
1253  Opcodes.clear();
1254  UnwindOpAsm.Reset();
1255 }
1256 
1257 void ARMELFStreamer::emitFnStart() {
1258  assert(FnStart == nullptr);
1259  FnStart = getContext().createTempSymbol();
1260  EmitLabel(FnStart);
1261 }
1262 
1263 void ARMELFStreamer::emitFnEnd() {
1264  assert(FnStart && ".fnstart must precedes .fnend");
1265 
1266  // Emit unwind opcodes if there is no .handlerdata directive
1267  if (!ExTab && !CantUnwind)
1268  FlushUnwindOpcodes(true);
1269 
1270  // Emit the exception index table entry
1271  SwitchToExIdxSection(*FnStart);
1272 
1273  if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
1274  EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1275 
1276  const MCSymbolRefExpr *FnStartRef =
1277  MCSymbolRefExpr::create(FnStart,
1279  getContext());
1280 
1281  EmitValue(FnStartRef, 4);
1282 
1283  if (CantUnwind) {
1284  EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
1285  } else if (ExTab) {
1286  // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1287  const MCSymbolRefExpr *ExTabEntryRef =
1290  getContext());
1291  EmitValue(ExTabEntryRef, 4);
1292  } else {
1293  // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1294  // the second word of exception index table entry. The size of the unwind
1295  // opcodes should always be 4 bytes.
1296  assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1297  "Compact model must use __aeabi_unwind_cpp_pr0 as personality");
1298  assert(Opcodes.size() == 4u &&
1299  "Unwind opcode size for __aeabi_unwind_cpp_pr0 must be equal to 4");
1300  uint64_t Intval = Opcodes[0] |
1301  Opcodes[1] << 8 |
1302  Opcodes[2] << 16 |
1303  Opcodes[3] << 24;
1304  EmitIntValue(Intval, Opcodes.size());
1305  }
1306 
1307  // Switch to the section containing FnStart
1308  SwitchSection(&FnStart->getSection());
1309 
1310  // Clean exception handling frame information
1311  EHReset();
1312 }
1313 
1314 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1315 
1316 // Add the R_ARM_NONE fixup at the same position
1317 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1318  const MCSymbol *PersonalitySym = getContext().getOrCreateSymbol(Name);
1319 
1320  const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::create(
1321  PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1322 
1323  visitUsedExpr(*PersonalityRef);
1324  MCDataFragment *DF = getOrCreateDataFragment();
1325  DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
1326  PersonalityRef,
1327  MCFixup::getKindForSize(4, false)));
1328 }
1329 
1330 void ARMELFStreamer::FlushPendingOffset() {
1331  if (PendingOffset != 0) {
1332  UnwindOpAsm.EmitSPOffset(-PendingOffset);
1333  PendingOffset = 0;
1334  }
1335 }
1336 
1337 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1338  // Emit the unwind opcode to restore $sp.
1339  if (UsedFP) {
1340  const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1341  int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1342  UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1343  UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1344  } else {
1345  FlushPendingOffset();
1346  }
1347 
1348  // Finalize the unwind opcode sequence
1349  UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1350 
1351  // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1352  // section. Thus, we don't have to create an entry in the .ARM.extab
1353  // section.
1354  if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1355  return;
1356 
1357  // Switch to .ARM.extab section.
1358  SwitchToExTabSection(*FnStart);
1359 
1360  // Create .ARM.extab label for offset in .ARM.exidx
1361  assert(!ExTab);
1362  ExTab = getContext().createTempSymbol();
1363  EmitLabel(ExTab);
1364 
1365  // Emit personality
1366  if (Personality) {
1367  const MCSymbolRefExpr *PersonalityRef =
1368  MCSymbolRefExpr::create(Personality,
1370  getContext());
1371 
1372  EmitValue(PersonalityRef, 4);
1373  }
1374 
1375  // Emit unwind opcodes
1376  assert((Opcodes.size() % 4) == 0 &&
1377  "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be multiple of 4");
1378  for (unsigned I = 0; I != Opcodes.size(); I += 4) {
1379  uint64_t Intval = Opcodes[I] |
1380  Opcodes[I + 1] << 8 |
1381  Opcodes[I + 2] << 16 |
1382  Opcodes[I + 3] << 24;
1383  EmitIntValue(Intval, 4);
1384  }
1385 
1386  // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1387  // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1388  // after the unwind opcodes. The handler data consists of several 32-bit
1389  // words, and should be terminated by zero.
1390  //
1391  // In case that the .handlerdata directive is not specified by the
1392  // programmer, we should emit zero to terminate the handler data.
1393  if (NoHandlerData && !Personality)
1394  EmitIntValue(0, 4);
1395 }
1396 
1397 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1398 
1399 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1400  Personality = Per;
1401  UnwindOpAsm.setPersonality(Per);
1402 }
1403 
1404 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
1405  assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
1406  PersonalityIndex = Index;
1407 }
1408 
1409 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1410  int64_t Offset) {
1411  assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1412  "the operand of .setfp directive should be either $sp or $fp");
1413 
1414  UsedFP = true;
1415  FPReg = NewFPReg;
1416 
1417  if (NewSPReg == ARM::SP)
1418  FPOffset = SPOffset + Offset;
1419  else
1420  FPOffset += Offset;
1421 }
1422 
1423 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
1424  assert((Reg != ARM::SP && Reg != ARM::PC) &&
1425  "the operand of .movsp cannot be either sp or pc");
1426  assert(FPReg == ARM::SP && "current FP must be SP");
1427 
1428  FlushPendingOffset();
1429 
1430  FPReg = Reg;
1431  FPOffset = SPOffset + Offset;
1432 
1433  const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1434  UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1435 }
1436 
1437 void ARMELFStreamer::emitPad(int64_t Offset) {
1438  // Track the change of the $sp offset
1439  SPOffset -= Offset;
1440 
1441  // To squash multiple .pad directives, we should delay the unwind opcode
1442  // until the .save, .vsave, .handlerdata, or .fnend directives.
1443  PendingOffset -= Offset;
1444 }
1445 
1446 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1447  bool IsVector) {
1448  // Collect the registers in the register list
1449  unsigned Count = 0;
1450  uint32_t Mask = 0;
1451  const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1452  for (size_t i = 0; i < RegList.size(); ++i) {
1453  unsigned Reg = MRI->getEncodingValue(RegList[i]);
1454  assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1455  unsigned Bit = (1u << Reg);
1456  if ((Mask & Bit) == 0) {
1457  Mask |= Bit;
1458  ++Count;
1459  }
1460  }
1461 
1462  // Track the change the $sp offset: For the .save directive, the
1463  // corresponding push instruction will decrease the $sp by (4 * Count).
1464  // For the .vsave directive, the corresponding vpush instruction will
1465  // decrease $sp by (8 * Count).
1466  SPOffset -= Count * (IsVector ? 8 : 4);
1467 
1468  // Emit the opcode
1469  FlushPendingOffset();
1470  if (IsVector)
1471  UnwindOpAsm.EmitVFPRegSave(Mask);
1472  else
1473  UnwindOpAsm.EmitRegSave(Mask);
1474 }
1475 
1476 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
1477  const SmallVectorImpl<uint8_t> &Opcodes) {
1478  FlushPendingOffset();
1479  SPOffset = SPOffset - Offset;
1480  UnwindOpAsm.EmitRaw(Opcodes);
1481 }
1482 
1483 namespace llvm {
1484 
1487  MCInstPrinter *InstPrint,
1488  bool isVerboseAsm) {
1489  return new ARMTargetAsmStreamer(S, OS, *InstPrint, isVerboseAsm);
1490 }
1491 
1493  return new ARMTargetStreamer(S);
1494 }
1495 
1497  const MCSubtargetInfo &STI) {
1498  const Triple &TT = STI.getTargetTriple();
1499  if (TT.isOSBinFormatELF())
1500  return new ARMTargetELFStreamer(S);
1501  return new ARMTargetStreamer(S);
1502 }
1503 
1505  std::unique_ptr<MCAsmBackend> TAB,
1506  std::unique_ptr<MCObjectWriter> OW,
1507  std::unique_ptr<MCCodeEmitter> Emitter,
1508  bool RelaxAll, bool IsThumb) {
1509  ARMELFStreamer *S = new ARMELFStreamer(Context, std::move(TAB), std::move(OW),
1510  std::move(Emitter), IsThumb);
1511  // FIXME: This should eventually end up somewhere else where more
1512  // intelligent flag decisions can be made. For now we are just maintaining
1513  // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1514  S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1515 
1516  if (RelaxAll)
1517  S->getAssembler().setRelaxAll(true);
1518  return S;
1519 }
1520 
1521 } // end namespace llvm
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:39
static SectionKind getData()
Definition: SectionKind.h:202
void EmitBytes(StringRef Data) override
Emit the bytes in Data into the output.
LLVMContext & Context
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:323
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:24
void reset() override
state management
Definition: MCELFStreamer.h:33
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:604
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
Target specific streamer interface.
Definition: MCStreamer.h:84
unsigned Reg
virtual void printRegName(raw_ostream &OS, unsigned RegNo) const
Print the assembler register name.
static MCFixupKind getKindForSize(unsigned Size, bool isPCRel)
Return the generic fixup kind for a value with the given size.
Definition: MCFixup.h:132
virtual void finishAttributeSection()
F(f)
StringRef getCPUAttr(ArchKind AK)
virtual void reset()
Reset any state between object emissions, i.e.
const Triple & getTargetTriple() const
amdgpu Simplify well known AMD library false Value Value const Twine & Name
void setExternal(bool Value) const
Definition: MCSymbol.h:394
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
StringRef getArchName(ArchKind AK)
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:36
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:166
A four-byte fixup.
Definition: MCFixup.h:26
Context object for machine code objects.
Definition: MCContext.h:63
void emitFill(const MCExpr &NumBytes, uint64_t FillValue, SMLoc Loc=SMLoc()) override
Emit Size bytes worth of the value specified by FillValue.
.code16 (X86) / .code 16 (ARM)
Definition: MCDirectives.h:51
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
void EmitValueImpl(const MCExpr *Value, unsigned Size, SMLoc Loc=SMLoc()) override
Emit the expression Value into the output as a native integer of the given Size bytes.
SmallVectorImpl< char > & getContents()
Definition: MCFragment.h:198
MCTargetStreamer * createARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS, MCInstPrinter *InstPrint, bool isVerboseAsm)
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:161
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:118
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
StringRef AttrTypeAsString(unsigned Attr, bool HasTagPrefix=true)
unsigned getUniqueID() const
Definition: MCSectionELF.h:87
void ChangeSection(MCSection *Section, const MCExpr *Subsection) override
Update streamer for a new active section.
MCTargetStreamer * createARMObjectTargetStreamer(MCStreamer &S, const MCSubtargetInfo &STI)
Streaming machine code generation interface.
Definition: MCStreamer.h:189
void print(raw_ostream &OS, const MCAsmInfo *MAI, bool InParens=false) const
Definition: MCExpr.cpp:42
unsigned const MachineRegisterInfo * MRI
const MCSymbolELF * getGroup() const
Definition: MCSectionELF.h:78
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition: MCFixup.h:23
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCFragment.h:224
.subsections_via_symbols (MachO)
Definition: MCDirectives.h:50
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:23
void setOffset(uint64_t Value)
Definition: MCSymbol.h:327
MCELFStreamer * createARMELFStreamer(MCContext &Context, std::unique_ptr< MCAsmBackend > TAB, std::unique_ptr< MCObjectWriter > OW, std::unique_ptr< MCCodeEmitter > Emitter, bool RelaxAll, bool IsThumb)
static MCFixup create(uint32_t Offset, const MCExpr *Value, MCFixupKind Kind, SMLoc Loc=SMLoc())
Definition: MCFixup.h:90
size_t size() const
Definition: SmallVector.h:53
static wasm::ValType getType(const TargetRegisterClass *RC)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
unsigned getULEB128Size(uint64_t Value)
Utility function to get the size of the ULEB128-encoded value.
Definition: LEB128.cpp:20
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1116
const MCSymbol & getSymbol() const
Definition: MCExpr.h:336
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
bool isVector(MCInstrInfo const &MCII, MCInst const &MCI)
static Twine utohexstr(const uint64_t &Val)
Definition: Twine.h:385
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:248
.syntax (ARM/ELF)
Definition: MCDirectives.h:49
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:267
StringRef getArchExtName(unsigned ArchExtKind)
.code32 (X86) / .code 32 (ARM)
Definition: MCDirectives.h:52
.code64 (X86)
Definition: MCDirectives.h:53
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:40
uint16_t getEncodingValue(unsigned RegNo) const
Returns the encoding for RegNo.
MCAssemblerFlag
Definition: MCDirectives.h:48
.type _foo, STT_FUNC # aka
Definition: MCDirectives.h:23
#define I(x, y, z)
Definition: MD5.cpp:58
Generic base class for all target subtargets.
StringRef getFPUName(unsigned FPUKind)
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:28
Special entry for the function never unwind.
Definition: ARMEHABI.h:36
uint32_t Size
Definition: Profile.cpp:47
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:203
const unsigned Kind
Fragment for data and encoded instructions.
Definition: MCFragment.h:242
LLVM_NODISCARD std::string lower() const
Definition: StringRef.cpp:108
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MCTargetStreamer * createARMNullTargetStreamer(MCStreamer &S)
LLVM Value Representation.
Definition: Value.h:73
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:81
void EmitAssemblerFlag(MCAssemblerFlag Flag) override
Note in the output the specified Flag.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
static std::string GetAEABIUnwindPersonalityName(unsigned Index)
Represents a location in source code.
Definition: SMLoc.h:24
unsigned getArchAttr(ArchKind AK)
void FinishImpl() override
Streamer specific finalization.
StringRef getSectionName() const
Definition: MCSectionELF.h:73
void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI, bool=false) override
Emit the given Instruction into the current section.
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:60