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