Override virtual function for ARM EH directives.
[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 "ARMUnwindOp.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCCodeEmitter.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCELF.h"
24 #include "llvm/MC/MCELFStreamer.h"
25 #include "llvm/MC/MCELFSymbolFlags.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCObjectStreamer.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/MCValue.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ELF.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38
39 using namespace llvm;
40
41 namespace {
42
43 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
44 /// the appropriate points in the object files. These symbols are defined in the
45 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
46 ///
47 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
48 /// region of ARM code, Thumb code or data in a section. In practice, this
49 /// emission does not rely on explicit assembler directives but on inherent
50 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
51 /// r0, r0, r0" an instruction).
52 ///
53 /// As a result this system is orthogonal to the DataRegion infrastructure used
54 /// by MachO. Beware!
55 class ARMELFStreamer : public MCELFStreamer {
56 public:
57   ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
58                  raw_ostream &OS, MCCodeEmitter *Emitter, bool IsThumb)
59     : MCELFStreamer(Context, TAB, OS, Emitter),
60       IsThumb(IsThumb), MappingSymbolCounter(0), LastEMS(EMS_None),
61       ExTab(0), FnStart(0), Personality(0), CantUnwind(false) {
62   }
63
64   ~ARMELFStreamer() {}
65
66   // ARM exception handling directives
67   virtual void EmitFnStart();
68   virtual void EmitFnEnd();
69   virtual void EmitCantUnwind();
70   virtual void EmitPersonality(const MCSymbol *Per);
71   virtual void EmitHandlerData();
72   virtual void EmitSetFP(unsigned NewFpReg,
73                          unsigned NewSpReg,
74                          int64_t Offset = 0);
75   virtual void EmitPad(int64_t Offset);
76   virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
77                            bool isVector);
78
79   virtual void ChangeSection(const MCSection *Section) {
80     // We have to keep track of the mapping symbol state of any sections we
81     // use. Each one should start off as EMS_None, which is provided as the
82     // default constructor by DenseMap::lookup.
83     LastMappingSymbols[getPreviousSection()] = LastEMS;
84     LastEMS = LastMappingSymbols.lookup(Section);
85
86     MCELFStreamer::ChangeSection(Section);
87   }
88
89   /// This function is the one used to emit instruction data into the ELF
90   /// streamer. We override it to add the appropriate mapping symbol if
91   /// necessary.
92   virtual void EmitInstruction(const MCInst& Inst) {
93     if (IsThumb)
94       EmitThumbMappingSymbol();
95     else
96       EmitARMMappingSymbol();
97
98     MCELFStreamer::EmitInstruction(Inst);
99   }
100
101   /// This is one of the functions used to emit data into an ELF section, so the
102   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
103   /// necessary.
104   virtual void EmitBytes(StringRef Data, unsigned AddrSpace) {
105     EmitDataMappingSymbol();
106     MCELFStreamer::EmitBytes(Data, AddrSpace);
107   }
108
109   /// This is one of the functions used to emit data into an ELF section, so the
110   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
111   /// necessary.
112   virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
113                              unsigned AddrSpace) {
114     EmitDataMappingSymbol();
115     MCELFStreamer::EmitValueImpl(Value, Size, AddrSpace);
116   }
117
118   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {
119     MCELFStreamer::EmitAssemblerFlag(Flag);
120
121     switch (Flag) {
122     case MCAF_SyntaxUnified:
123       return; // no-op here.
124     case MCAF_Code16:
125       IsThumb = true;
126       return; // Change to Thumb mode
127     case MCAF_Code32:
128       IsThumb = false;
129       return; // Change to ARM mode
130     case MCAF_Code64:
131       return;
132     case MCAF_SubsectionsViaSymbols:
133       return;
134     }
135   }
136
137 private:
138   enum ElfMappingSymbol {
139     EMS_None,
140     EMS_ARM,
141     EMS_Thumb,
142     EMS_Data
143   };
144
145   void EmitDataMappingSymbol() {
146     if (LastEMS == EMS_Data) return;
147     EmitMappingSymbol("$d");
148     LastEMS = EMS_Data;
149   }
150
151   void EmitThumbMappingSymbol() {
152     if (LastEMS == EMS_Thumb) return;
153     EmitMappingSymbol("$t");
154     LastEMS = EMS_Thumb;
155   }
156
157   void EmitARMMappingSymbol() {
158     if (LastEMS == EMS_ARM) return;
159     EmitMappingSymbol("$a");
160     LastEMS = EMS_ARM;
161   }
162
163   void EmitMappingSymbol(StringRef Name) {
164     MCSymbol *Start = getContext().CreateTempSymbol();
165     EmitLabel(Start);
166
167     MCSymbol *Symbol =
168       getContext().GetOrCreateSymbol(Name + "." +
169                                      Twine(MappingSymbolCounter++));
170
171     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
172     MCELF::SetType(SD, ELF::STT_NOTYPE);
173     MCELF::SetBinding(SD, ELF::STB_LOCAL);
174     SD.setExternal(false);
175     Symbol->setSection(*getCurrentSection());
176
177     const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
178     Symbol->setVariableValue(Value);
179   }
180
181   void EmitThumbFunc(MCSymbol *Func) {
182     // FIXME: Anything needed here to flag the function as thumb?
183
184     getAssembler().setIsThumbFunc(Func);
185
186     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Func);
187     SD.setFlags(SD.getFlags() | ELF_Other_ThumbFunc);
188   }
189
190   // Helper functions for ARM exception handling directives
191   void Reset();
192
193   void EmitPersonalityFixup(StringRef Name);
194
195   void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
196                          SectionKind Kind, const MCSymbol &Fn);
197   void SwitchToExTabSection(const MCSymbol &FnStart);
198   void SwitchToExIdxSection(const MCSymbol &FnStart);
199
200   bool IsThumb;
201   int64_t MappingSymbolCounter;
202
203   DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
204   ElfMappingSymbol LastEMS;
205
206   // ARM Exception Handling Frame Information
207   MCSymbol *ExTab;
208   MCSymbol *FnStart;
209   const MCSymbol *Personality;
210   bool CantUnwind;
211 };
212 }
213
214 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
215                                               unsigned Type,
216                                               unsigned Flags,
217                                               SectionKind Kind,
218                                               const MCSymbol &Fn) {
219   const MCSectionELF &FnSection =
220     static_cast<const MCSectionELF &>(Fn.getSection());
221
222   // Create the name for new section
223   StringRef FnSecName(FnSection.getSectionName());
224   SmallString<128> EHSecName(Prefix);
225   if (FnSecName != ".text") {
226     EHSecName += FnSecName;
227   }
228
229   // Get .ARM.extab or .ARM.exidx section
230   const MCSectionELF *EHSection = NULL;
231   if (const MCSymbol *Group = FnSection.getGroup()) {
232     EHSection = getContext().getELFSection(
233       EHSecName, Type, Flags | ELF::SHF_GROUP, Kind,
234       FnSection.getEntrySize(), Group->getName());
235   } else {
236     EHSection = getContext().getELFSection(EHSecName, Type, Flags, Kind);
237   }
238   assert(EHSection);
239
240   // Switch to .ARM.extab or .ARM.exidx section
241   SwitchSection(EHSection);
242   EmitCodeAlignment(4, 0);
243 }
244
245 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
246   SwitchToEHSection(".ARM.extab",
247                     ELF::SHT_PROGBITS,
248                     ELF::SHF_ALLOC,
249                     SectionKind::getDataRel(),
250                     FnStart);
251 }
252
253 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
254   SwitchToEHSection(".ARM.exidx",
255                     ELF::SHT_ARM_EXIDX,
256                     ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
257                     SectionKind::getDataRel(),
258                     FnStart);
259 }
260
261 void ARMELFStreamer::Reset() {
262   ExTab = NULL;
263   FnStart = NULL;
264   Personality = NULL;
265   CantUnwind = false;
266 }
267
268 // Add the R_ARM_NONE fixup at the same position
269 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
270   const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
271
272   const MCSymbolRefExpr *PersonalityRef =
273     MCSymbolRefExpr::Create(PersonalitySym,
274                             MCSymbolRefExpr::VK_ARM_NONE,
275                             getContext());
276
277   AddValueSymbols(PersonalityRef);
278   MCDataFragment *DF = getOrCreateDataFragment();
279   DF->getFixups().push_back(
280     MCFixup::Create(DF->getContents().size(), PersonalityRef,
281                     MCFixup::getKindForSize(4, false)));
282 }
283
284 void ARMELFStreamer::EmitFnStart() {
285   assert(FnStart == 0);
286   FnStart = getContext().CreateTempSymbol();
287   EmitLabel(FnStart);
288 }
289
290 void ARMELFStreamer::EmitFnEnd() {
291   assert(FnStart && ".fnstart must preceeds .fnend");
292
293   // Emit unwind opcodes if there is no .handlerdata directive
294   int PersonalityIndex = -1;
295   if (!ExTab && !CantUnwind) {
296     // For __aeabi_unwind_cpp_pr1, we have to emit opcodes in .ARM.extab.
297     SwitchToExTabSection(*FnStart);
298
299     // Create .ARM.extab label for offset in .ARM.exidx
300     ExTab = getContext().CreateTempSymbol();
301     EmitLabel(ExTab);
302
303     PersonalityIndex = 1;
304
305     uint32_t Entry = 0;
306     uint32_t NumExtraEntryWords = 0;
307     Entry |= NumExtraEntryWords << 24;
308     Entry |= (EHT_COMPACT | PersonalityIndex) << 16;
309
310     // TODO: This should be generated according to .save, .vsave, .setfp
311     // directives.  Currently, we are simply generating FINISH opcode.
312     Entry |= UNWIND_OPCODE_FINISH << 8;
313     Entry |= UNWIND_OPCODE_FINISH;
314
315     EmitIntValue(Entry, 4, 0);
316   }
317
318   // Emit the exception index table entry
319   SwitchToExIdxSection(*FnStart);
320
321   if (PersonalityIndex == 1)
322     EmitPersonalityFixup("__aeabi_unwind_cpp_pr1");
323
324   const MCSymbolRefExpr *FnStartRef =
325     MCSymbolRefExpr::Create(FnStart,
326                             MCSymbolRefExpr::VK_ARM_PREL31,
327                             getContext());
328
329   EmitValue(FnStartRef, 4, 0);
330
331   if (CantUnwind) {
332     EmitIntValue(EXIDX_CANTUNWIND, 4, 0);
333   } else {
334     const MCSymbolRefExpr *ExTabEntryRef =
335       MCSymbolRefExpr::Create(ExTab,
336                               MCSymbolRefExpr::VK_ARM_PREL31,
337                               getContext());
338     EmitValue(ExTabEntryRef, 4, 0);
339   }
340
341   // Clean exception handling frame information
342   Reset();
343 }
344
345 void ARMELFStreamer::EmitCantUnwind() {
346   CantUnwind = true;
347 }
348
349 void ARMELFStreamer::EmitHandlerData() {
350   SwitchToExTabSection(*FnStart);
351
352   // Create .ARM.extab label for offset in .ARM.exidx
353   assert(!ExTab);
354   ExTab = getContext().CreateTempSymbol();
355   EmitLabel(ExTab);
356
357   // Emit Personality
358   assert(Personality && ".personality directive must preceed .handlerdata");
359
360   const MCSymbolRefExpr *PersonalityRef =
361     MCSymbolRefExpr::Create(Personality,
362                             MCSymbolRefExpr::VK_ARM_PREL31,
363                             getContext());
364
365   EmitValue(PersonalityRef, 4, 0);
366
367   // Emit unwind opcodes
368   uint32_t Entry = 0;
369   uint32_t NumExtraEntryWords = 0;
370
371   // TODO: This should be generated according to .save, .vsave, .setfp
372   // directives.  Currently, we are simply generating FINISH opcode.
373   Entry |= NumExtraEntryWords << 24;
374   Entry |= UNWIND_OPCODE_FINISH << 16;
375   Entry |= UNWIND_OPCODE_FINISH << 8;
376   Entry |= UNWIND_OPCODE_FINISH;
377
378   EmitIntValue(Entry, 4, 0);
379 }
380
381 void ARMELFStreamer::EmitPersonality(const MCSymbol *Per) {
382   Personality = Per;
383 }
384
385 void ARMELFStreamer::EmitSetFP(unsigned NewFpReg,
386                                unsigned NewSpReg,
387                                int64_t Offset) {
388   // TODO: Not implemented
389 }
390
391 void ARMELFStreamer::EmitPad(int64_t Offset) {
392   // TODO: Not implemented
393 }
394
395 void ARMELFStreamer::EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
396                                  bool IsVector) {
397   // TODO: Not implemented
398 }
399
400 namespace llvm {
401   MCELFStreamer* createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
402                                       raw_ostream &OS, MCCodeEmitter *Emitter,
403                                       bool RelaxAll, bool NoExecStack,
404                                       bool IsThumb) {
405     ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
406     if (RelaxAll)
407       S->getAssembler().setRelaxAll(true);
408     if (NoExecStack)
409       S->getAssembler().setNoExecStack(true);
410     return S;
411   }
412
413 }
414
415