ARM IAS: improve .eabi_attribute handling
[oota-llvm.git] / lib / Target / ARM / MCTargetDesc / ARMELFStreamer.cpp
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 "ARMBuildAttrs.h"
17 #include "ARMArchName.h"
18 #include "ARMFPUName.h"
19 #include "ARMRegisterInfo.h"
20 #include "ARMUnwindOpAsm.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/MC/MCAsmBackend.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCAssembler.h"
27 #include "llvm/MC/MCCodeEmitter.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCELF.h"
30 #include "llvm/MC/MCELFStreamer.h"
31 #include "llvm/MC/MCELFSymbolFlags.h"
32 #include "llvm/MC/MCExpr.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCInstPrinter.h"
35 #include "llvm/MC/MCObjectStreamer.h"
36 #include "llvm/MC/MCRegisterInfo.h"
37 #include "llvm/MC/MCSection.h"
38 #include "llvm/MC/MCSectionELF.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/MC/MCValue.h"
42 #include "llvm/Support/ARMEHABI.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ELF.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <algorithm>
48
49 using namespace llvm;
50
51 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
52   assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX &&
53          "Invalid personality index");
54   return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
55 }
56
57 static const char *GetFPUName(unsigned ID) {
58   switch (ID) {
59   default:
60     llvm_unreachable("Unknown FPU kind");
61     break;
62 #define ARM_FPU_NAME(NAME, ID) case ARM::ID: return NAME;
63 #include "ARMFPUName.def"
64   }
65   return NULL;
66 }
67
68 static const char *GetArchName(unsigned ID) {
69   switch (ID) {
70   default:
71     llvm_unreachable("Unknown ARCH kind");
72     break;
73 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
74   case ARM::ID: return NAME;
75 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
76 #include "ARMArchName.def"
77   }
78   return NULL;
79 }
80
81 static const char *GetArchDefaultCPUName(unsigned ID) {
82   switch (ID) {
83   default:
84     llvm_unreachable("Unknown ARCH kind");
85     break;
86 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
87   case ARM::ID: return DEFAULT_CPU_NAME;
88 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
89 #include "ARMArchName.def"
90   }
91   return NULL;
92 }
93
94 static unsigned GetArchDefaultCPUArch(unsigned ID) {
95   switch (ID) {
96   default:
97     llvm_unreachable("Unknown ARCH kind");
98     break;
99 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
100   case ARM::ID: return ARMBuildAttrs::DEFAULT_CPU_ARCH;
101 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
102 #include "ARMArchName.def"
103   }
104   return 0;
105 }
106
107 namespace {
108
109 class ARMELFStreamer;
110
111 class ARMTargetAsmStreamer : public ARMTargetStreamer {
112   formatted_raw_ostream &OS;
113   MCInstPrinter &InstPrinter;
114
115   virtual void emitFnStart();
116   virtual void emitFnEnd();
117   virtual void emitCantUnwind();
118   virtual void emitPersonality(const MCSymbol *Personality);
119   virtual void emitHandlerData();
120   virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
121   virtual void emitPad(int64_t Offset);
122   virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
123                            bool isVector);
124
125   virtual void switchVendor(StringRef Vendor);
126   virtual void emitAttribute(unsigned Attribute, unsigned Value);
127   virtual void emitTextAttribute(unsigned Attribute, StringRef String);
128   virtual void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
129                                     StringRef StrinValue);
130   virtual void emitArch(unsigned Arch);
131   virtual void emitFPU(unsigned FPU);
132   virtual void emitInst(uint32_t Inst, char Suffix = '\0');
133   virtual void finishAttributeSection();
134
135 public:
136   ARMTargetAsmStreamer(formatted_raw_ostream &OS, MCInstPrinter &InstPrinter);
137 };
138
139 ARMTargetAsmStreamer::ARMTargetAsmStreamer(formatted_raw_ostream &OS,
140                                            MCInstPrinter &InstPrinter)
141     : OS(OS), InstPrinter(InstPrinter) {}
142 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
143 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
144 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
145 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
146   OS << "\t.personality " << Personality->getName() << '\n';
147 }
148 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
149 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
150                                      int64_t Offset) {
151   OS << "\t.setfp\t";
152   InstPrinter.printRegName(OS, FpReg);
153   OS << ", ";
154   InstPrinter.printRegName(OS, SpReg);
155   if (Offset)
156     OS << ", #" << Offset;
157   OS << '\n';
158 }
159 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
160   OS << "\t.pad\t#" << Offset << '\n';
161 }
162 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
163                                        bool isVector) {
164   assert(RegList.size() && "RegList should not be empty");
165   if (isVector)
166     OS << "\t.vsave\t{";
167   else
168     OS << "\t.save\t{";
169
170   InstPrinter.printRegName(OS, RegList[0]);
171
172   for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
173     OS << ", ";
174     InstPrinter.printRegName(OS, RegList[i]);
175   }
176
177   OS << "}\n";
178 }
179 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
180 }
181 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
182   OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value) << "\n";
183 }
184 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
185                                              StringRef String) {
186   switch (Attribute) {
187   case ARMBuildAttrs::CPU_name:
188     OS << "\t.cpu\t" << String.lower();
189     break;
190   default:
191     OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
192     break;
193   }
194   OS << "\n";
195 }
196 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
197                                                 unsigned IntValue,
198                                                 StringRef StringValue) {
199   switch (Attribute) {
200   default: llvm_unreachable("unsupported multi-value attribute in asm mode");
201   case ARMBuildAttrs::compatibility:
202     OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
203     if (!StringValue.empty())
204       OS << ", \"" << StringValue << "\"";
205     break;
206   }
207   OS << "\n";
208 }
209 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
210   OS << "\t.arch\t" << GetArchName(Arch) << "\n";
211 }
212 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
213   OS << "\t.fpu\t" << GetFPUName(FPU) << "\n";
214 }
215 void ARMTargetAsmStreamer::finishAttributeSection() {
216 }
217
218 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
219   OS << "\t.inst";
220   if (Suffix)
221     OS << "." << Suffix;
222   OS << "\t0x" << utohexstr(Inst) << "\n";
223 }
224
225 class ARMTargetELFStreamer : public ARMTargetStreamer {
226 private:
227   // This structure holds all attributes, accounting for
228   // their string/numeric value, so we can later emmit them
229   // in declaration order, keeping all in the same vector
230   struct AttributeItem {
231     enum {
232       HiddenAttribute = 0,
233       NumericAttribute,
234       TextAttribute,
235       NumericAndTextAttributes
236     } Type;
237     unsigned Tag;
238     unsigned IntValue;
239     StringRef StringValue;
240
241     static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
242       return (LHS.Tag < RHS.Tag);
243     }
244   };
245
246   StringRef CurrentVendor;
247   unsigned FPU;
248   unsigned Arch;
249   SmallVector<AttributeItem, 64> Contents;
250
251   const MCSection *AttributeSection;
252
253   // FIXME: this should be in a more generic place, but
254   // getULEBSize() is in MCAsmInfo and will be moved to MCDwarf
255   static size_t getULEBSize(int Value) {
256     size_t Size = 0;
257     do {
258       Value >>= 7;
259       Size += sizeof(int8_t); // Is this really necessary?
260     } while (Value);
261     return Size;
262   }
263
264   AttributeItem *getAttributeItem(unsigned Attribute) {
265     for (size_t i = 0; i < Contents.size(); ++i)
266       if (Contents[i].Tag == Attribute)
267         return &Contents[i];
268     return 0;
269   }
270
271   void setAttributeItem(unsigned Attribute, unsigned Value,
272                         bool OverwriteExisting) {
273     // Look for existing attribute item
274     if (AttributeItem *Item = getAttributeItem(Attribute)) {
275       if (!OverwriteExisting)
276         return;
277       Item->IntValue = Value;
278       return;
279     }
280
281     // Create new attribute item
282     AttributeItem Item = {
283       AttributeItem::NumericAttribute,
284       Attribute,
285       Value,
286       StringRef("")
287     };
288     Contents.push_back(Item);
289   }
290
291   void setAttributeItem(unsigned Attribute, StringRef Value,
292                         bool OverwriteExisting) {
293     // Look for existing attribute item
294     if (AttributeItem *Item = getAttributeItem(Attribute)) {
295       if (!OverwriteExisting)
296         return;
297       Item->StringValue = Value;
298       return;
299     }
300
301     // Create new attribute item
302     AttributeItem Item = {
303       AttributeItem::TextAttribute,
304       Attribute,
305       0,
306       Value
307     };
308     Contents.push_back(Item);
309   }
310
311   void setAttributeItems(unsigned Attribute, unsigned IntValue,
312                          StringRef StringValue, bool OverwriteExisting) {
313     // Look for existing attribute item
314     if (AttributeItem *Item = getAttributeItem(Attribute)) {
315       if (!OverwriteExisting)
316         return;
317       Item->IntValue = IntValue;
318       Item->StringValue = StringValue;
319       return;
320     }
321
322     // Create new attribute item
323     AttributeItem Item = {
324       AttributeItem::NumericAndTextAttributes,
325       Attribute,
326       IntValue,
327       StringValue
328     };
329     Contents.push_back(Item);
330   }
331
332   void emitArchDefaultAttributes();
333   void emitFPUDefaultAttributes();
334
335   ARMELFStreamer &getStreamer();
336
337   virtual void emitFnStart();
338   virtual void emitFnEnd();
339   virtual void emitCantUnwind();
340   virtual void emitPersonality(const MCSymbol *Personality);
341   virtual void emitHandlerData();
342   virtual void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
343   virtual void emitPad(int64_t Offset);
344   virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
345                            bool isVector);
346
347   virtual void switchVendor(StringRef Vendor);
348   virtual void emitAttribute(unsigned Attribute, unsigned Value);
349   virtual void emitTextAttribute(unsigned Attribute, StringRef String);
350   virtual void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
351                                     StringRef StringValue);
352   virtual void emitArch(unsigned Arch);
353   virtual void emitFPU(unsigned FPU);
354   virtual void emitInst(uint32_t Inst, char Suffix = '\0');
355   virtual void finishAttributeSection();
356
357   size_t calculateContentSize() const;
358
359 public:
360   ARMTargetELFStreamer()
361     : ARMTargetStreamer(), CurrentVendor("aeabi"), FPU(ARM::INVALID_FPU),
362       Arch(ARM::INVALID_ARCH), AttributeSection(0) {
363   }
364 };
365
366 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
367 /// the appropriate points in the object files. These symbols are defined in the
368 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
369 ///
370 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
371 /// region of ARM code, Thumb code or data in a section. In practice, this
372 /// emission does not rely on explicit assembler directives but on inherent
373 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
374 /// r0, r0, r0" an instruction).
375 ///
376 /// As a result this system is orthogonal to the DataRegion infrastructure used
377 /// by MachO. Beware!
378 class ARMELFStreamer : public MCELFStreamer {
379 public:
380   friend class ARMTargetELFStreamer;
381
382   ARMELFStreamer(MCContext &Context, MCTargetStreamer *TargetStreamer,
383                  MCAsmBackend &TAB, raw_ostream &OS, MCCodeEmitter *Emitter,
384                  bool IsThumb)
385       : MCELFStreamer(Context, TargetStreamer, TAB, OS, Emitter),
386         IsThumb(IsThumb), MappingSymbolCounter(0), LastEMS(EMS_None) {
387     Reset();
388   }
389
390   ~ARMELFStreamer() {}
391
392   virtual void FinishImpl();
393
394   // ARM exception handling directives
395   void emitFnStart();
396   void emitFnEnd();
397   void emitCantUnwind();
398   void emitPersonality(const MCSymbol *Per);
399   void emitHandlerData();
400   void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
401   void emitPad(int64_t Offset);
402   void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
403
404   virtual void ChangeSection(const MCSection *Section,
405                              const MCExpr *Subsection) {
406     // We have to keep track of the mapping symbol state of any sections we
407     // use. Each one should start off as EMS_None, which is provided as the
408     // default constructor by DenseMap::lookup.
409     LastMappingSymbols[getPreviousSection().first] = LastEMS;
410     LastEMS = LastMappingSymbols.lookup(Section);
411
412     MCELFStreamer::ChangeSection(Section, Subsection);
413   }
414
415   /// This function is the one used to emit instruction data into the ELF
416   /// streamer. We override it to add the appropriate mapping symbol if
417   /// necessary.
418   virtual void EmitInstruction(const MCInst& Inst) {
419     if (IsThumb)
420       EmitThumbMappingSymbol();
421     else
422       EmitARMMappingSymbol();
423
424     MCELFStreamer::EmitInstruction(Inst);
425   }
426
427   virtual void emitInst(uint32_t Inst, char Suffix) {
428     unsigned Size;
429     char Buffer[4];
430     const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
431
432     switch (Suffix) {
433     case '\0':
434       Size = 4;
435
436       assert(!IsThumb);
437       EmitARMMappingSymbol();
438       for (unsigned II = 0, IE = Size; II != IE; II++) {
439         const unsigned I = LittleEndian ? (Size - II - 1) : II;
440         Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
441       }
442
443       break;
444     case 'n':
445     case 'w':
446       Size = (Suffix == 'n' ? 2 : 4);
447
448       assert(IsThumb);
449       EmitThumbMappingSymbol();
450       for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
451         const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
452         const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
453         Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
454         Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
455       }
456
457       break;
458     default:
459       llvm_unreachable("Invalid Suffix");
460     }
461
462     MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
463   }
464
465   /// This is one of the functions used to emit data into an ELF section, so the
466   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
467   /// necessary.
468   virtual void EmitBytes(StringRef Data) {
469     EmitDataMappingSymbol();
470     MCELFStreamer::EmitBytes(Data);
471   }
472
473   /// This is one of the functions used to emit data into an ELF section, so the
474   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
475   /// necessary.
476   virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {
477     EmitDataMappingSymbol();
478     MCELFStreamer::EmitValueImpl(Value, Size);
479   }
480
481   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {
482     MCELFStreamer::EmitAssemblerFlag(Flag);
483
484     switch (Flag) {
485     case MCAF_SyntaxUnified:
486       return; // no-op here.
487     case MCAF_Code16:
488       IsThumb = true;
489       return; // Change to Thumb mode
490     case MCAF_Code32:
491       IsThumb = false;
492       return; // Change to ARM mode
493     case MCAF_Code64:
494       return;
495     case MCAF_SubsectionsViaSymbols:
496       return;
497     }
498   }
499
500 private:
501   enum ElfMappingSymbol {
502     EMS_None,
503     EMS_ARM,
504     EMS_Thumb,
505     EMS_Data
506   };
507
508   void EmitDataMappingSymbol() {
509     if (LastEMS == EMS_Data) return;
510     EmitMappingSymbol("$d");
511     LastEMS = EMS_Data;
512   }
513
514   void EmitThumbMappingSymbol() {
515     if (LastEMS == EMS_Thumb) return;
516     EmitMappingSymbol("$t");
517     LastEMS = EMS_Thumb;
518   }
519
520   void EmitARMMappingSymbol() {
521     if (LastEMS == EMS_ARM) return;
522     EmitMappingSymbol("$a");
523     LastEMS = EMS_ARM;
524   }
525
526   void EmitMappingSymbol(StringRef Name) {
527     MCSymbol *Start = getContext().CreateTempSymbol();
528     EmitLabel(Start);
529
530     MCSymbol *Symbol =
531       getContext().GetOrCreateSymbol(Name + "." +
532                                      Twine(MappingSymbolCounter++));
533
534     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
535     MCELF::SetType(SD, ELF::STT_NOTYPE);
536     MCELF::SetBinding(SD, ELF::STB_LOCAL);
537     SD.setExternal(false);
538     AssignSection(Symbol, getCurrentSection().first);
539
540     const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
541     Symbol->setVariableValue(Value);
542   }
543
544   void EmitThumbFunc(MCSymbol *Func) {
545     // FIXME: Anything needed here to flag the function as thumb?
546
547     getAssembler().setIsThumbFunc(Func);
548
549     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Func);
550     SD.setFlags(SD.getFlags() | ELF_Other_ThumbFunc);
551   }
552
553   // Helper functions for ARM exception handling directives
554   void Reset();
555
556   void EmitPersonalityFixup(StringRef Name);
557   void FlushPendingOffset();
558   void FlushUnwindOpcodes(bool NoHandlerData);
559
560   void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
561                          SectionKind Kind, const MCSymbol &Fn);
562   void SwitchToExTabSection(const MCSymbol &FnStart);
563   void SwitchToExIdxSection(const MCSymbol &FnStart);
564
565   bool IsThumb;
566   int64_t MappingSymbolCounter;
567
568   DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
569   ElfMappingSymbol LastEMS;
570
571   // ARM Exception Handling Frame Information
572   MCSymbol *ExTab;
573   MCSymbol *FnStart;
574   const MCSymbol *Personality;
575   unsigned PersonalityIndex;
576   unsigned FPReg; // Frame pointer register
577   int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
578   int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
579   int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
580   bool UsedFP;
581   bool CantUnwind;
582   SmallVector<uint8_t, 64> Opcodes;
583   UnwindOpcodeAssembler UnwindOpAsm;
584 };
585 } // end anonymous namespace
586
587 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
588   ARMELFStreamer *S = static_cast<ARMELFStreamer *>(Streamer);
589   return *S;
590 }
591
592 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
593 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
594 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
595 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
596   getStreamer().emitPersonality(Personality);
597 }
598 void ARMTargetELFStreamer::emitHandlerData() {
599   getStreamer().emitHandlerData();
600 }
601 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
602                                      int64_t Offset) {
603   getStreamer().emitSetFP(FpReg, SpReg, Offset);
604 }
605 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
606   getStreamer().emitPad(Offset);
607 }
608 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
609                                        bool isVector) {
610   getStreamer().emitRegSave(RegList, isVector);
611 }
612 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
613   assert(!Vendor.empty() && "Vendor cannot be empty.");
614
615   if (CurrentVendor == Vendor)
616     return;
617
618   if (!CurrentVendor.empty())
619     finishAttributeSection();
620
621   assert(Contents.empty() &&
622          ".ARM.attributes should be flushed before changing vendor");
623   CurrentVendor = Vendor;
624
625 }
626 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
627   setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
628 }
629 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
630                                              StringRef Value) {
631   setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
632 }
633 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
634                                                 unsigned IntValue,
635                                                 StringRef StringValue) {
636   setAttributeItems(Attribute, IntValue, StringValue,
637                     /* OverwriteExisting= */ true);
638 }
639 void ARMTargetELFStreamer::emitArch(unsigned Value) {
640   Arch = Value;
641 }
642 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
643   using namespace ARMBuildAttrs;
644   setAttributeItem(CPU_name, GetArchDefaultCPUName(Arch), false);
645   setAttributeItem(CPU_arch, GetArchDefaultCPUArch(Arch), false);
646
647   switch (Arch) {
648   case ARM::ARMV2:
649   case ARM::ARMV2A:
650   case ARM::ARMV3:
651   case ARM::ARMV3M:
652   case ARM::ARMV4:
653   case ARM::ARMV5:
654     setAttributeItem(ARM_ISA_use, Allowed, false);
655     break;
656
657   case ARM::ARMV4T:
658   case ARM::ARMV5T:
659   case ARM::ARMV5TE:
660   case ARM::ARMV6:
661   case ARM::ARMV6J:
662     setAttributeItem(ARM_ISA_use, Allowed, false);
663     setAttributeItem(THUMB_ISA_use, Allowed, false);
664     break;
665
666   case ARM::ARMV6T2:
667     setAttributeItem(ARM_ISA_use, Allowed, false);
668     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
669     break;
670
671   case ARM::ARMV6Z:
672   case ARM::ARMV6ZK:
673     setAttributeItem(ARM_ISA_use, Allowed, false);
674     setAttributeItem(THUMB_ISA_use, Allowed, false);
675     setAttributeItem(Virtualization_use, AllowTZ, false);
676     break;
677
678   case ARM::ARMV6M:
679     setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
680     setAttributeItem(THUMB_ISA_use, Allowed, false);
681     break;
682
683   case ARM::ARMV7:
684     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
685     break;
686
687   case ARM::ARMV7A:
688     setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
689     setAttributeItem(ARM_ISA_use, Allowed, false);
690     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
691     break;
692
693   case ARM::ARMV7R:
694     setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
695     setAttributeItem(ARM_ISA_use, Allowed, false);
696     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
697     break;
698
699   case ARM::ARMV7M:
700     setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
701     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
702     break;
703
704   case ARM::ARMV8A:
705     setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
706     setAttributeItem(ARM_ISA_use, Allowed, false);
707     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
708     setAttributeItem(MPextension_use, Allowed, false);
709     setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
710     break;
711
712   case ARM::IWMMXT:
713     setAttributeItem(ARM_ISA_use, Allowed, false);
714     setAttributeItem(THUMB_ISA_use, Allowed, false);
715     setAttributeItem(WMMX_arch, AllowWMMXv1, false);
716     break;
717
718   case ARM::IWMMXT2:
719     setAttributeItem(ARM_ISA_use, Allowed, false);
720     setAttributeItem(THUMB_ISA_use, Allowed, false);
721     setAttributeItem(WMMX_arch, AllowWMMXv2, false);
722     break;
723
724   default:
725     report_fatal_error("Unknown Arch: " + Twine(Arch));
726     break;
727   }
728 }
729 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
730   FPU = Value;
731 }
732 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
733   switch (FPU) {
734   case ARM::VFP:
735   case ARM::VFPV2:
736     setAttributeItem(ARMBuildAttrs::FP_arch,
737                      ARMBuildAttrs::AllowFPv2,
738                      /* OverwriteExisting= */ false);
739     break;
740
741   case ARM::VFPV3:
742     setAttributeItem(ARMBuildAttrs::FP_arch,
743                      ARMBuildAttrs::AllowFPv3A,
744                      /* OverwriteExisting= */ false);
745     break;
746
747   case ARM::VFPV3_D16:
748     setAttributeItem(ARMBuildAttrs::FP_arch,
749                      ARMBuildAttrs::AllowFPv3B,
750                      /* OverwriteExisting= */ false);
751     break;
752
753   case ARM::VFPV4:
754     setAttributeItem(ARMBuildAttrs::FP_arch,
755                      ARMBuildAttrs::AllowFPv4A,
756                      /* OverwriteExisting= */ false);
757     break;
758
759   case ARM::VFPV4_D16:
760     setAttributeItem(ARMBuildAttrs::FP_arch,
761                      ARMBuildAttrs::AllowFPv4B,
762                      /* OverwriteExisting= */ false);
763     break;
764
765   case ARM::FP_ARMV8:
766     setAttributeItem(ARMBuildAttrs::FP_arch,
767                      ARMBuildAttrs::AllowFPARMv8A,
768                      /* OverwriteExisting= */ false);
769     break;
770
771   case ARM::NEON:
772     setAttributeItem(ARMBuildAttrs::FP_arch,
773                      ARMBuildAttrs::AllowFPv3A,
774                      /* OverwriteExisting= */ false);
775     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
776                      ARMBuildAttrs::AllowNeon,
777                      /* OverwriteExisting= */ false);
778     break;
779
780   case ARM::NEON_VFPV4:
781     setAttributeItem(ARMBuildAttrs::FP_arch,
782                      ARMBuildAttrs::AllowFPv4A,
783                      /* OverwriteExisting= */ false);
784     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
785                      ARMBuildAttrs::AllowNeon2,
786                      /* OverwriteExisting= */ false);
787     break;
788
789   case ARM::NEON_FP_ARMV8:
790   case ARM::CRYPTO_NEON_FP_ARMV8:
791     setAttributeItem(ARMBuildAttrs::FP_arch,
792                      ARMBuildAttrs::AllowFPARMv8A,
793                      /* OverwriteExisting= */ false);
794     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
795                      ARMBuildAttrs::AllowNeonARMv8,
796                      /* OverwriteExisting= */ false);
797     break;
798
799   case ARM::SOFTVFP:
800     break;
801
802   default:
803     report_fatal_error("Unknown FPU: " + Twine(FPU));
804     break;
805   }
806 }
807 size_t ARMTargetELFStreamer::calculateContentSize() const {
808   size_t Result = 0;
809   for (size_t i = 0; i < Contents.size(); ++i) {
810     AttributeItem item = Contents[i];
811     switch (item.Type) {
812     case AttributeItem::HiddenAttribute:
813       break;
814     case AttributeItem::NumericAttribute:
815       Result += getULEBSize(item.Tag);
816       Result += getULEBSize(item.IntValue);
817       break;
818     case AttributeItem::TextAttribute:
819       Result += getULEBSize(item.Tag);
820       Result += item.StringValue.size() + 1; // string + '\0'
821       break;
822     case AttributeItem::NumericAndTextAttributes:
823       Result += getULEBSize(item.Tag);
824       Result += getULEBSize(item.IntValue);
825       Result += item.StringValue.size() + 1; // string + '\0';
826       break;
827     }
828   }
829   return Result;
830 }
831 void ARMTargetELFStreamer::finishAttributeSection() {
832   // <format-version>
833   // [ <section-length> "vendor-name"
834   // [ <file-tag> <size> <attribute>*
835   //   | <section-tag> <size> <section-number>* 0 <attribute>*
836   //   | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
837   //   ]+
838   // ]*
839
840   if (FPU != ARM::INVALID_FPU)
841     emitFPUDefaultAttributes();
842
843   if (Arch != ARM::INVALID_ARCH)
844     emitArchDefaultAttributes();
845
846   if (Contents.empty())
847     return;
848
849   std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
850
851   ARMELFStreamer &Streamer = getStreamer();
852
853   // Switch to .ARM.attributes section
854   if (AttributeSection) {
855     Streamer.SwitchSection(AttributeSection);
856   } else {
857     AttributeSection =
858       Streamer.getContext().getELFSection(".ARM.attributes",
859                                           ELF::SHT_ARM_ATTRIBUTES,
860                                           0,
861                                           SectionKind::getMetadata());
862     Streamer.SwitchSection(AttributeSection);
863
864     // Format version
865     Streamer.EmitIntValue(0x41, 1);
866   }
867
868   // Vendor size + Vendor name + '\0'
869   const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
870
871   // Tag + Tag Size
872   const size_t TagHeaderSize = 1 + 4;
873
874   const size_t ContentsSize = calculateContentSize();
875
876   Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
877   Streamer.EmitBytes(CurrentVendor);
878   Streamer.EmitIntValue(0, 1); // '\0'
879
880   Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
881   Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
882
883   // Size should have been accounted for already, now
884   // emit each field as its type (ULEB or String)
885   for (size_t i = 0; i < Contents.size(); ++i) {
886     AttributeItem item = Contents[i];
887     Streamer.EmitULEB128IntValue(item.Tag);
888     switch (item.Type) {
889     default: llvm_unreachable("Invalid attribute type");
890     case AttributeItem::NumericAttribute:
891       Streamer.EmitULEB128IntValue(item.IntValue);
892       break;
893     case AttributeItem::TextAttribute:
894       Streamer.EmitBytes(item.StringValue.upper());
895       Streamer.EmitIntValue(0, 1); // '\0'
896       break;
897     case AttributeItem::NumericAndTextAttributes:
898       Streamer.EmitULEB128IntValue(item.IntValue);
899       Streamer.EmitBytes(item.StringValue.upper());
900       Streamer.EmitIntValue(0, 1); // '\0'
901       break;
902     }
903   }
904
905   Contents.clear();
906   FPU = ARM::INVALID_FPU;
907 }
908 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
909   getStreamer().emitInst(Inst, Suffix);
910 }
911
912 void ARMELFStreamer::FinishImpl() {
913   MCTargetStreamer &TS = getTargetStreamer();
914   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
915   ATS.finishAttributeSection();
916
917   MCELFStreamer::FinishImpl();
918 }
919
920 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
921                                               unsigned Type,
922                                               unsigned Flags,
923                                               SectionKind Kind,
924                                               const MCSymbol &Fn) {
925   const MCSectionELF &FnSection =
926     static_cast<const MCSectionELF &>(Fn.getSection());
927
928   // Create the name for new section
929   StringRef FnSecName(FnSection.getSectionName());
930   SmallString<128> EHSecName(Prefix);
931   if (FnSecName != ".text") {
932     EHSecName += FnSecName;
933   }
934
935   // Get .ARM.extab or .ARM.exidx section
936   const MCSectionELF *EHSection = NULL;
937   if (const MCSymbol *Group = FnSection.getGroup()) {
938     EHSection = getContext().getELFSection(
939       EHSecName, Type, Flags | ELF::SHF_GROUP, Kind,
940       FnSection.getEntrySize(), Group->getName());
941   } else {
942     EHSection = getContext().getELFSection(EHSecName, Type, Flags, Kind);
943   }
944   assert(EHSection && "Failed to get the required EH section");
945
946   // Switch to .ARM.extab or .ARM.exidx section
947   SwitchSection(EHSection);
948   EmitCodeAlignment(4, 0);
949 }
950
951 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
952   SwitchToEHSection(".ARM.extab",
953                     ELF::SHT_PROGBITS,
954                     ELF::SHF_ALLOC,
955                     SectionKind::getDataRel(),
956                     FnStart);
957 }
958
959 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
960   SwitchToEHSection(".ARM.exidx",
961                     ELF::SHT_ARM_EXIDX,
962                     ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
963                     SectionKind::getDataRel(),
964                     FnStart);
965 }
966
967 void ARMELFStreamer::Reset() {
968   ExTab = NULL;
969   FnStart = NULL;
970   Personality = NULL;
971   PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
972   FPReg = ARM::SP;
973   FPOffset = 0;
974   SPOffset = 0;
975   PendingOffset = 0;
976   UsedFP = false;
977   CantUnwind = false;
978
979   Opcodes.clear();
980   UnwindOpAsm.Reset();
981 }
982
983 void ARMELFStreamer::emitFnStart() {
984   assert(FnStart == 0);
985   FnStart = getContext().CreateTempSymbol();
986   EmitLabel(FnStart);
987 }
988
989 void ARMELFStreamer::emitFnEnd() {
990   assert(FnStart && ".fnstart must preceeds .fnend");
991
992   // Emit unwind opcodes if there is no .handlerdata directive
993   if (!ExTab && !CantUnwind)
994     FlushUnwindOpcodes(true);
995
996   // Emit the exception index table entry
997   SwitchToExIdxSection(*FnStart);
998
999   if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
1000     EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
1001
1002   const MCSymbolRefExpr *FnStartRef =
1003     MCSymbolRefExpr::Create(FnStart,
1004                             MCSymbolRefExpr::VK_ARM_PREL31,
1005                             getContext());
1006
1007   EmitValue(FnStartRef, 4);
1008
1009   if (CantUnwind) {
1010     EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
1011   } else if (ExTab) {
1012     // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
1013     const MCSymbolRefExpr *ExTabEntryRef =
1014       MCSymbolRefExpr::Create(ExTab,
1015                               MCSymbolRefExpr::VK_ARM_PREL31,
1016                               getContext());
1017     EmitValue(ExTabEntryRef, 4);
1018   } else {
1019     // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
1020     // the second word of exception index table entry.  The size of the unwind
1021     // opcodes should always be 4 bytes.
1022     assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
1023            "Compact model must use __aeabi_cpp_unwind_pr0 as personality");
1024     assert(Opcodes.size() == 4u &&
1025            "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be equal to 4");
1026     EmitBytes(StringRef(reinterpret_cast<const char*>(Opcodes.data()),
1027                         Opcodes.size()));
1028   }
1029
1030   // Switch to the section containing FnStart
1031   SwitchSection(&FnStart->getSection());
1032
1033   // Clean exception handling frame information
1034   Reset();
1035 }
1036
1037 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
1038
1039 // Add the R_ARM_NONE fixup at the same position
1040 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
1041   const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
1042
1043   const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::Create(
1044       PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
1045
1046   AddValueSymbols(PersonalityRef);
1047   MCDataFragment *DF = getOrCreateDataFragment();
1048   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
1049                                             PersonalityRef,
1050                                             MCFixup::getKindForSize(4, false)));
1051 }
1052
1053 void ARMELFStreamer::FlushPendingOffset() {
1054   if (PendingOffset != 0) {
1055     UnwindOpAsm.EmitSPOffset(-PendingOffset);
1056     PendingOffset = 0;
1057   }
1058 }
1059
1060 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
1061   // Emit the unwind opcode to restore $sp.
1062   if (UsedFP) {
1063     const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1064     int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
1065     UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
1066     UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
1067   } else {
1068     FlushPendingOffset();
1069   }
1070
1071   // Finalize the unwind opcode sequence
1072   UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
1073
1074   // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
1075   // section.  Thus, we don't have to create an entry in the .ARM.extab
1076   // section.
1077   if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
1078     return;
1079
1080   // Switch to .ARM.extab section.
1081   SwitchToExTabSection(*FnStart);
1082
1083   // Create .ARM.extab label for offset in .ARM.exidx
1084   assert(!ExTab);
1085   ExTab = getContext().CreateTempSymbol();
1086   EmitLabel(ExTab);
1087
1088   // Emit personality
1089   if (Personality) {
1090     const MCSymbolRefExpr *PersonalityRef =
1091       MCSymbolRefExpr::Create(Personality,
1092                               MCSymbolRefExpr::VK_ARM_PREL31,
1093                               getContext());
1094
1095     EmitValue(PersonalityRef, 4);
1096   }
1097
1098   // Emit unwind opcodes
1099   EmitBytes(StringRef(reinterpret_cast<const char *>(Opcodes.data()),
1100                       Opcodes.size()));
1101
1102   // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
1103   // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
1104   // after the unwind opcodes.  The handler data consists of several 32-bit
1105   // words, and should be terminated by zero.
1106   //
1107   // In case that the .handlerdata directive is not specified by the
1108   // programmer, we should emit zero to terminate the handler data.
1109   if (NoHandlerData && !Personality)
1110     EmitIntValue(0, 4);
1111 }
1112
1113 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
1114
1115 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
1116   Personality = Per;
1117   UnwindOpAsm.setPersonality(Per);
1118 }
1119
1120 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
1121                                int64_t Offset) {
1122   assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
1123          "the operand of .setfp directive should be either $sp or $fp");
1124
1125   UsedFP = true;
1126   FPReg = NewFPReg;
1127
1128   if (NewSPReg == ARM::SP)
1129     FPOffset = SPOffset + Offset;
1130   else
1131     FPOffset += Offset;
1132 }
1133
1134 void ARMELFStreamer::emitPad(int64_t Offset) {
1135   // Track the change of the $sp offset
1136   SPOffset -= Offset;
1137
1138   // To squash multiple .pad directives, we should delay the unwind opcode
1139   // until the .save, .vsave, .handlerdata, or .fnend directives.
1140   PendingOffset -= Offset;
1141 }
1142
1143 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
1144                                  bool IsVector) {
1145   // Collect the registers in the register list
1146   unsigned Count = 0;
1147   uint32_t Mask = 0;
1148   const MCRegisterInfo *MRI = getContext().getRegisterInfo();
1149   for (size_t i = 0; i < RegList.size(); ++i) {
1150     unsigned Reg = MRI->getEncodingValue(RegList[i]);
1151     assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
1152     unsigned Bit = (1u << Reg);
1153     if ((Mask & Bit) == 0) {
1154       Mask |= Bit;
1155       ++Count;
1156     }
1157   }
1158
1159   // Track the change the $sp offset: For the .save directive, the
1160   // corresponding push instruction will decrease the $sp by (4 * Count).
1161   // For the .vsave directive, the corresponding vpush instruction will
1162   // decrease $sp by (8 * Count).
1163   SPOffset -= Count * (IsVector ? 8 : 4);
1164
1165   // Emit the opcode
1166   FlushPendingOffset();
1167   if (IsVector)
1168     UnwindOpAsm.EmitVFPRegSave(Mask);
1169   else
1170     UnwindOpAsm.EmitRegSave(Mask);
1171 }
1172
1173 namespace llvm {
1174
1175 MCStreamer *createMCAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
1176                                 bool isVerboseAsm, bool useLoc, bool useCFI,
1177                                 bool useDwarfDirectory,
1178                                 MCInstPrinter *InstPrint, MCCodeEmitter *CE,
1179                                 MCAsmBackend *TAB, bool ShowInst) {
1180   ARMTargetAsmStreamer *S = new ARMTargetAsmStreamer(OS, *InstPrint);
1181
1182   return llvm::createAsmStreamer(Ctx, S, OS, isVerboseAsm, useLoc, useCFI,
1183                                  useDwarfDirectory, InstPrint, CE, TAB,
1184                                  ShowInst);
1185 }
1186
1187   MCELFStreamer* createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
1188                                       raw_ostream &OS, MCCodeEmitter *Emitter,
1189                                       bool RelaxAll, bool NoExecStack,
1190                                       bool IsThumb) {
1191     ARMTargetELFStreamer *TS = new ARMTargetELFStreamer();
1192     ARMELFStreamer *S =
1193         new ARMELFStreamer(Context, TS, TAB, OS, Emitter, IsThumb);
1194     // FIXME: This should eventually end up somewhere else where more
1195     // intelligent flag decisions can be made. For now we are just maintaining
1196     // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
1197     S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
1198
1199     if (RelaxAll)
1200       S->getAssembler().setRelaxAll(true);
1201     if (NoExecStack)
1202       S->getAssembler().setNoExecStack(true);
1203     return S;
1204   }
1205
1206 }
1207
1208