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