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