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