Set default type and flags for .init and .fini.
[oota-llvm.git] / lib / MC / MCParser / ELFAsmParser.cpp
1 //===- ELFAsmParser.cpp - ELF Assembly Parser -----------------------------===//
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 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
11 #include "llvm/ADT/StringSwitch.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCParser/MCAsmLexer.h"
17 #include "llvm/MC/MCSectionELF.h"
18 #include "llvm/MC/MCStreamer.h"
19 using namespace llvm;
20
21 namespace {
22
23 class ELFAsmParser : public MCAsmParserExtension {
24   template<bool (ELFAsmParser::*Handler)(StringRef, SMLoc)>
25   void AddDirectiveHandler(StringRef Directive) {
26     getParser().AddDirectiveHandler(this, Directive,
27                                     HandleDirective<ELFAsmParser, Handler>);
28   }
29
30   bool ParseSectionSwitch(StringRef Section, unsigned Type,
31                           unsigned Flags, SectionKind Kind);
32
33 public:
34   ELFAsmParser() {}
35
36   virtual void Initialize(MCAsmParser &Parser) {
37     // Call the base implementation.
38     this->MCAsmParserExtension::Initialize(Parser);
39
40     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveData>(".data");
41     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveText>(".text");
42     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveBSS>(".bss");
43     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveRoData>(".rodata");
44     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTData>(".tdata");
45     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTBSS>(".tbss");
46     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRel>(".data.rel");
47     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRelRo>(".data.rel.ro");
48     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRelRoLocal>(".data.rel.ro.local");
49     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveEhFrame>(".eh_frame");
50     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSection>(".section");
51     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSize>(".size");
52     AddDirectiveHandler<&ELFAsmParser::ParseDirectivePrevious>(".previous");
53     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveType>(".type");
54     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveIdent>(".ident");
55     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSymver>(".symver");
56   }
57
58   // FIXME: Part of this logic is duplicated in the MCELFStreamer. What is
59   // the best way for us to get access to it?
60   bool ParseSectionDirectiveData(StringRef, SMLoc) {
61     return ParseSectionSwitch(".data", MCSectionELF::SHT_PROGBITS,
62                               MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
63                               SectionKind::getDataRel());
64   }
65   bool ParseSectionDirectiveText(StringRef, SMLoc) {
66     return ParseSectionSwitch(".text", MCSectionELF::SHT_PROGBITS,
67                               MCSectionELF::SHF_EXECINSTR |
68                               MCSectionELF::SHF_ALLOC, SectionKind::getText());
69   }
70   bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
71     return ParseSectionSwitch(".bss", MCSectionELF::SHT_NOBITS,
72                               MCSectionELF::SHF_WRITE |
73                               MCSectionELF::SHF_ALLOC, SectionKind::getBSS());
74   }
75   bool ParseSectionDirectiveRoData(StringRef, SMLoc) {
76     return ParseSectionSwitch(".rodata", MCSectionELF::SHT_PROGBITS,
77                               MCSectionELF::SHF_ALLOC,
78                               SectionKind::getReadOnly());
79   }
80   bool ParseSectionDirectiveTData(StringRef, SMLoc) {
81     return ParseSectionSwitch(".tdata", MCSectionELF::SHT_PROGBITS,
82                               MCSectionELF::SHF_ALLOC |
83                               MCSectionELF::SHF_TLS | MCSectionELF::SHF_WRITE,
84                               SectionKind::getThreadData());
85   }
86   bool ParseSectionDirectiveTBSS(StringRef, SMLoc) {
87     return ParseSectionSwitch(".tbss", MCSectionELF::SHT_NOBITS,
88                               MCSectionELF::SHF_ALLOC |
89                               MCSectionELF::SHF_TLS | MCSectionELF::SHF_WRITE,
90                               SectionKind::getThreadBSS());
91   }
92   bool ParseSectionDirectiveDataRel(StringRef, SMLoc) {
93     return ParseSectionSwitch(".data.rel", MCSectionELF::SHT_PROGBITS,
94                               MCSectionELF::SHF_ALLOC |
95                               MCSectionELF::SHF_WRITE,
96                               SectionKind::getDataRel());
97   }
98   bool ParseSectionDirectiveDataRelRo(StringRef, SMLoc) {
99     return ParseSectionSwitch(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
100                               MCSectionELF::SHF_ALLOC |
101                               MCSectionELF::SHF_WRITE,
102                               SectionKind::getReadOnlyWithRel());
103   }
104   bool ParseSectionDirectiveDataRelRoLocal(StringRef, SMLoc) {
105     return ParseSectionSwitch(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
106                               MCSectionELF::SHF_ALLOC |
107                               MCSectionELF::SHF_WRITE,
108                               SectionKind::getReadOnlyWithRelLocal());
109   }
110   bool ParseSectionDirectiveEhFrame(StringRef, SMLoc) {
111     return ParseSectionSwitch(".eh_frame", MCSectionELF::SHT_PROGBITS,
112                               MCSectionELF::SHF_ALLOC |
113                               MCSectionELF::SHF_WRITE,
114                               SectionKind::getDataRel());
115   }
116   bool ParseDirectiveSection(StringRef, SMLoc);
117   bool ParseDirectiveSize(StringRef, SMLoc);
118   bool ParseDirectivePrevious(StringRef, SMLoc);
119   bool ParseDirectiveType(StringRef, SMLoc);
120   bool ParseDirectiveIdent(StringRef, SMLoc);
121   bool ParseDirectiveSymver(StringRef, SMLoc);
122
123 private:
124   bool ParseSectionName(StringRef &SectionName);
125 };
126
127 }
128
129 bool ELFAsmParser::ParseSectionSwitch(StringRef Section, unsigned Type,
130                                       unsigned Flags, SectionKind Kind) {
131   if (getLexer().isNot(AsmToken::EndOfStatement))
132     return TokError("unexpected token in section switching directive");
133   Lex();
134
135   getStreamer().SwitchSection(getContext().getELFSection(
136                                 Section, Type, Flags, Kind));
137
138   return false;
139 }
140
141 bool ELFAsmParser::ParseDirectiveSize(StringRef, SMLoc) {
142   StringRef Name;
143   if (getParser().ParseIdentifier(Name))
144     return TokError("expected identifier in directive");
145   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);;
146
147   if (getLexer().isNot(AsmToken::Comma))
148     return TokError("unexpected token in directive");
149   Lex();
150
151   const MCExpr *Expr;
152   if (getParser().ParseExpression(Expr))
153     return true;
154
155   if (getLexer().isNot(AsmToken::EndOfStatement))
156     return TokError("unexpected token in directive");
157
158   getStreamer().EmitELFSize(Sym, Expr);
159   return false;
160 }
161
162 bool ELFAsmParser::ParseSectionName(StringRef &SectionName) {
163   // A section name can contain -, so we cannot just use
164   // ParseIdentifier.
165   SMLoc FirstLoc = getLexer().getLoc();
166   unsigned Size = 0;
167
168   for (;;) {
169     StringRef Tmp;
170     unsigned CurSize;
171
172     SMLoc PrevLoc = getLexer().getLoc();
173     if (getLexer().is(AsmToken::Minus)) {
174       CurSize = 1;
175       Lex(); // Consume the "-".
176     } else if (!getParser().ParseIdentifier(Tmp))
177       CurSize = Tmp.size();
178     else
179       break;
180
181     Size += CurSize;
182     SectionName = StringRef(FirstLoc.getPointer(), Size);
183
184     // Make sure the following token is adjacent.
185     if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer())
186       break;
187   }
188   if (Size == 0)
189     return true;
190
191   return false;
192 }
193
194 // FIXME: This is a work in progress.
195 bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc) {
196   StringRef SectionName;
197
198   if (ParseSectionName(SectionName))
199     return TokError("expected identifier in directive");
200
201   std::string FlagsStr;
202   StringRef TypeName;
203   int64_t Size = 0;
204   if (getLexer().is(AsmToken::Comma)) {
205     Lex();
206
207     if (getLexer().isNot(AsmToken::String))
208       return TokError("expected string in directive");
209
210     FlagsStr = getTok().getStringContents();
211     Lex();
212
213     AsmToken::TokenKind TypeStartToken;
214     if (getContext().getAsmInfo().getCommentString()[0] == '@')
215       TypeStartToken = AsmToken::Percent;
216     else
217       TypeStartToken = AsmToken::At;
218
219     if (getLexer().is(AsmToken::Comma)) {
220       Lex();
221       if (getLexer().is(TypeStartToken)) {
222         Lex();
223         if (getParser().ParseIdentifier(TypeName))
224           return TokError("expected identifier in directive");
225
226         if (getLexer().is(AsmToken::Comma)) {
227           Lex();
228
229           if (getParser().ParseAbsoluteExpression(Size))
230             return true;
231
232           if (Size <= 0)
233             return TokError("section size must be positive");
234         }
235       }
236     }
237   }
238
239   if (getLexer().isNot(AsmToken::EndOfStatement))
240     return TokError("unexpected token in directive");
241
242   unsigned Flags = 0;
243   unsigned Type = MCSectionELF::SHT_NULL;
244
245   // Set the defaults first.
246   if (SectionName == ".fini" || SectionName == ".init") {
247     Type = MCSectionELF::SHT_PROGBITS;
248     Flags |= MCSectionELF::SHF_ALLOC;
249     Flags |= MCSectionELF::SHF_EXECINSTR;
250   }
251
252   for (unsigned i = 0; i < FlagsStr.size(); i++) {
253     switch (FlagsStr[i]) {
254     case 'a':
255       Flags |= MCSectionELF::SHF_ALLOC;
256       break;
257     case 'x':
258       Flags |= MCSectionELF::SHF_EXECINSTR;
259       break;
260     case 'w':
261       Flags |= MCSectionELF::SHF_WRITE;
262       break;
263     case 'M':
264       Flags |= MCSectionELF::SHF_MERGE;
265       break;
266     case 'S':
267       Flags |= MCSectionELF::SHF_STRINGS;
268       break;
269     case 'T':
270       Flags |= MCSectionELF::SHF_TLS;
271       break;
272     case 'c':
273       Flags |= MCSectionELF::XCORE_SHF_CP_SECTION;
274       break;
275     case 'd':
276       Flags |= MCSectionELF::XCORE_SHF_DP_SECTION;
277       break;
278     default:
279       return TokError("unknown flag");
280     }
281   }
282
283   if (!TypeName.empty()) {
284     if (TypeName == "init_array")
285       Type = MCSectionELF::SHT_INIT_ARRAY;
286     else if (TypeName == "fini_array")
287       Type = MCSectionELF::SHT_FINI_ARRAY;
288     else if (TypeName == "preinit_array")
289       Type = MCSectionELF::SHT_PREINIT_ARRAY;
290     else if (TypeName == "nobits")
291       Type = MCSectionELF::SHT_NOBITS;
292     else if (TypeName == "progbits")
293       Type = MCSectionELF::SHT_PROGBITS;
294     else
295       return TokError("unknown section type");
296   }
297
298   SectionKind Kind = (Flags & MCSectionELF::SHF_EXECINSTR)
299                      ? SectionKind::getText()
300                      : SectionKind::getDataRel();
301   getStreamer().SwitchSection(getContext().getELFSection(SectionName, Type,
302                                                          Flags, Kind, false,
303                                                          Size));
304   return false;
305 }
306
307 bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
308   const MCSection *PreviousSection = getStreamer().getPreviousSection();
309   if (PreviousSection != NULL)
310     getStreamer().SwitchSection(PreviousSection);
311
312   return false;
313 }
314
315 /// ParseDirectiveELFType
316 ///  ::= .type identifier , @attribute
317 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
318   StringRef Name;
319   if (getParser().ParseIdentifier(Name))
320     return TokError("expected identifier in directive");
321
322   // Handle the identifier as the key symbol.
323   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
324
325   if (getLexer().isNot(AsmToken::Comma))
326     return TokError("unexpected token in '.type' directive");
327   Lex();
328
329   if (getLexer().isNot(AsmToken::At))
330     return TokError("expected '@' before type");
331   Lex();
332
333   StringRef Type;
334   SMLoc TypeLoc;
335
336   TypeLoc = getLexer().getLoc();
337   if (getParser().ParseIdentifier(Type))
338     return TokError("expected symbol type in directive");
339
340   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
341     .Case("function", MCSA_ELF_TypeFunction)
342     .Case("object", MCSA_ELF_TypeObject)
343     .Case("tls_object", MCSA_ELF_TypeTLS)
344     .Case("common", MCSA_ELF_TypeCommon)
345     .Case("notype", MCSA_ELF_TypeNoType)
346     .Default(MCSA_Invalid);
347
348   if (Attr == MCSA_Invalid)
349     return Error(TypeLoc, "unsupported attribute in '.type' directive");
350
351   if (getLexer().isNot(AsmToken::EndOfStatement))
352     return TokError("unexpected token in '.type' directive");
353
354   Lex();
355
356   getStreamer().EmitSymbolAttribute(Sym, Attr);
357
358   return false;
359 }
360
361 /// ParseDirectiveIdent
362 ///  ::= .ident string
363 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
364   if (getLexer().isNot(AsmToken::String))
365     return TokError("unexpected token in '.ident' directive");
366
367   StringRef Data = getTok().getIdentifier();
368
369   Lex();
370
371   const MCSection *OldSection = getStreamer().getCurrentSection();
372   const MCSection *Comment =
373     getContext().getELFSection(".comment", MCSectionELF::SHT_PROGBITS,
374                                MCSectionELF::SHF_MERGE |
375                                MCSectionELF::SHF_STRINGS,
376                                SectionKind::getReadOnly(),
377                                false, 1);
378
379   static bool First = true;
380
381   getStreamer().SwitchSection(Comment);
382   if (First)
383     getStreamer().EmitIntValue(0, 1);
384   First = false;
385   getStreamer().EmitBytes(Data, 0);
386   getStreamer().EmitIntValue(0, 1);
387   getStreamer().SwitchSection(OldSection);
388   return false;
389 }
390
391 /// ParseDirectiveSymver
392 ///  ::= .symver foo, bar2@zed
393 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
394   StringRef Name;
395   if (getParser().ParseIdentifier(Name))
396     return TokError("expected identifier in directive");
397
398   if (getLexer().isNot(AsmToken::Comma))
399     return TokError("expected a comma");
400
401   Lex();
402
403   StringRef AliasName;
404   if (getParser().ParseIdentifier(AliasName))
405     return TokError("expected identifier in directive");
406
407   if (AliasName.find('@') == StringRef::npos)
408     return TokError("expected a '@' in the name");
409
410   MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
411   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
412   const MCExpr *Value = MCSymbolRefExpr::Create(Sym, getContext());
413
414   getStreamer().EmitAssignment(Alias, Value);
415   return false;
416 }
417
418 namespace llvm {
419
420 MCAsmParserExtension *createELFAsmParser() {
421   return new ELFAsmParser;
422 }
423
424 }