Add support for pushsection and popsection. Patch by Joerg Sonnenberger.
[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 #include "llvm/Support/ELF.h"
20 using namespace llvm;
21
22 namespace {
23
24 class ELFAsmParser : public MCAsmParserExtension {
25   template<bool (ELFAsmParser::*Handler)(StringRef, SMLoc)>
26   void AddDirectiveHandler(StringRef Directive) {
27     getParser().AddDirectiveHandler(this, Directive,
28                                     HandleDirective<ELFAsmParser, Handler>);
29   }
30
31   bool ParseSectionSwitch(StringRef Section, unsigned Type,
32                           unsigned Flags, SectionKind Kind);
33
34 public:
35   ELFAsmParser() {}
36
37   virtual void Initialize(MCAsmParser &Parser) {
38     // Call the base implementation.
39     this->MCAsmParserExtension::Initialize(Parser);
40
41     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveData>(".data");
42     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveText>(".text");
43     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveBSS>(".bss");
44     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveRoData>(".rodata");
45     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTData>(".tdata");
46     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTBSS>(".tbss");
47     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRel>(".data.rel");
48     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRelRo>(".data.rel.ro");
49     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRelRoLocal>(".data.rel.ro.local");
50     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveEhFrame>(".eh_frame");
51     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSection>(".section");
52     AddDirectiveHandler<&ELFAsmParser::ParseDirectivePushSection>(".pushsection");
53     AddDirectiveHandler<&ELFAsmParser::ParseDirectivePopSection>(".popsection");
54     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSize>(".size");
55     AddDirectiveHandler<&ELFAsmParser::ParseDirectivePrevious>(".previous");
56     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveType>(".type");
57     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveIdent>(".ident");
58     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSymver>(".symver");
59     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveWeakref>(".weakref");
60   }
61
62   // FIXME: Part of this logic is duplicated in the MCELFStreamer. What is
63   // the best way for us to get access to it?
64   bool ParseSectionDirectiveData(StringRef, SMLoc) {
65     return ParseSectionSwitch(".data", ELF::SHT_PROGBITS,
66                               ELF::SHF_WRITE |ELF::SHF_ALLOC,
67                               SectionKind::getDataRel());
68   }
69   bool ParseSectionDirectiveText(StringRef, SMLoc) {
70     return ParseSectionSwitch(".text", ELF::SHT_PROGBITS,
71                               ELF::SHF_EXECINSTR |
72                               ELF::SHF_ALLOC, SectionKind::getText());
73   }
74   bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
75     return ParseSectionSwitch(".bss", ELF::SHT_NOBITS,
76                               ELF::SHF_WRITE |
77                               ELF::SHF_ALLOC, SectionKind::getBSS());
78   }
79   bool ParseSectionDirectiveRoData(StringRef, SMLoc) {
80     return ParseSectionSwitch(".rodata", ELF::SHT_PROGBITS,
81                               ELF::SHF_ALLOC,
82                               SectionKind::getReadOnly());
83   }
84   bool ParseSectionDirectiveTData(StringRef, SMLoc) {
85     return ParseSectionSwitch(".tdata", ELF::SHT_PROGBITS,
86                               ELF::SHF_ALLOC |
87                               ELF::SHF_TLS | ELF::SHF_WRITE,
88                               SectionKind::getThreadData());
89   }
90   bool ParseSectionDirectiveTBSS(StringRef, SMLoc) {
91     return ParseSectionSwitch(".tbss", ELF::SHT_NOBITS,
92                               ELF::SHF_ALLOC |
93                               ELF::SHF_TLS | ELF::SHF_WRITE,
94                               SectionKind::getThreadBSS());
95   }
96   bool ParseSectionDirectiveDataRel(StringRef, SMLoc) {
97     return ParseSectionSwitch(".data.rel", ELF::SHT_PROGBITS,
98                               ELF::SHF_ALLOC |
99                               ELF::SHF_WRITE,
100                               SectionKind::getDataRel());
101   }
102   bool ParseSectionDirectiveDataRelRo(StringRef, SMLoc) {
103     return ParseSectionSwitch(".data.rel.ro", ELF::SHT_PROGBITS,
104                               ELF::SHF_ALLOC |
105                               ELF::SHF_WRITE,
106                               SectionKind::getReadOnlyWithRel());
107   }
108   bool ParseSectionDirectiveDataRelRoLocal(StringRef, SMLoc) {
109     return ParseSectionSwitch(".data.rel.ro.local", ELF::SHT_PROGBITS,
110                               ELF::SHF_ALLOC |
111                               ELF::SHF_WRITE,
112                               SectionKind::getReadOnlyWithRelLocal());
113   }
114   bool ParseSectionDirectiveEhFrame(StringRef, SMLoc) {
115     return ParseSectionSwitch(".eh_frame", ELF::SHT_PROGBITS,
116                               ELF::SHF_ALLOC |
117                               ELF::SHF_WRITE,
118                               SectionKind::getDataRel());
119   }
120   bool ParseDirectivePushSection(StringRef, SMLoc);
121   bool ParseDirectivePopSection(StringRef, SMLoc);
122   bool ParseDirectiveSection(StringRef, SMLoc);
123   bool ParseDirectiveSize(StringRef, SMLoc);
124   bool ParseDirectivePrevious(StringRef, SMLoc);
125   bool ParseDirectiveType(StringRef, SMLoc);
126   bool ParseDirectiveIdent(StringRef, SMLoc);
127   bool ParseDirectiveSymver(StringRef, SMLoc);
128   bool ParseDirectiveWeakref(StringRef, SMLoc);
129
130 private:
131   bool ParseSectionName(StringRef &SectionName);
132 };
133
134 }
135
136 bool ELFAsmParser::ParseSectionSwitch(StringRef Section, unsigned Type,
137                                       unsigned Flags, SectionKind Kind) {
138   if (getLexer().isNot(AsmToken::EndOfStatement))
139     return TokError("unexpected token in section switching directive");
140   Lex();
141
142   getStreamer().SwitchSection(getContext().getELFSection(
143                                 Section, Type, Flags, Kind));
144
145   return false;
146 }
147
148 bool ELFAsmParser::ParseDirectiveSize(StringRef, SMLoc) {
149   StringRef Name;
150   if (getParser().ParseIdentifier(Name))
151     return TokError("expected identifier in directive");
152   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);;
153
154   if (getLexer().isNot(AsmToken::Comma))
155     return TokError("unexpected token in directive");
156   Lex();
157
158   const MCExpr *Expr;
159   if (getParser().ParseExpression(Expr))
160     return true;
161
162   if (getLexer().isNot(AsmToken::EndOfStatement))
163     return TokError("unexpected token in directive");
164
165   getStreamer().EmitELFSize(Sym, Expr);
166   return false;
167 }
168
169 bool ELFAsmParser::ParseSectionName(StringRef &SectionName) {
170   // A section name can contain -, so we cannot just use
171   // ParseIdentifier.
172   SMLoc FirstLoc = getLexer().getLoc();
173   unsigned Size = 0;
174
175   if (getLexer().is(AsmToken::String)) {
176     SectionName = getTok().getIdentifier();
177     Lex();
178     return false;
179   }
180
181   for (;;) {
182     StringRef Tmp;
183     unsigned CurSize;
184
185     SMLoc PrevLoc = getLexer().getLoc();
186     if (getLexer().is(AsmToken::Minus)) {
187       CurSize = 1;
188       Lex(); // Consume the "-".
189     } else if (getLexer().is(AsmToken::String)) {
190       CurSize = getTok().getIdentifier().size() + 2;
191       Lex();
192     } else if (getLexer().is(AsmToken::Identifier)) {
193       CurSize = getTok().getIdentifier().size();
194       Lex();
195     } else {
196       break;
197     }
198
199     Size += CurSize;
200     SectionName = StringRef(FirstLoc.getPointer(), Size);
201
202     // Make sure the following token is adjacent.
203     if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer())
204       break;
205   }
206   if (Size == 0)
207     return true;
208
209   return false;
210 }
211
212 static SectionKind computeSectionKind(unsigned Flags) {
213   if (Flags & ELF::SHF_EXECINSTR)
214     return SectionKind::getText();
215   if (Flags & ELF::SHF_TLS)
216     return SectionKind::getThreadData();
217   return SectionKind::getDataRel();
218 }
219
220 static int parseSectionFlags(StringRef flagsStr) {
221   int flags = 0;
222
223   for (unsigned i = 0; i < flagsStr.size(); i++) {
224     switch (flagsStr[i]) {
225     case 'a':
226       flags |= ELF::SHF_ALLOC;
227       break;
228     case 'x':
229       flags |= ELF::SHF_EXECINSTR;
230       break;
231     case 'w':
232       flags |= ELF::SHF_WRITE;
233       break;
234     case 'M':
235       flags |= ELF::SHF_MERGE;
236       break;
237     case 'S':
238       flags |= ELF::SHF_STRINGS;
239       break;
240     case 'T':
241       flags |= ELF::SHF_TLS;
242       break;
243     case 'c':
244       flags |= ELF::XCORE_SHF_CP_SECTION;
245       break;
246     case 'd':
247       flags |= ELF::XCORE_SHF_DP_SECTION;
248       break;
249     case 'G':
250       flags |= ELF::SHF_GROUP;
251       break;
252     default:
253       return -1;
254     }
255   }
256
257   return flags;
258 }
259
260 bool ELFAsmParser::ParseDirectivePushSection(StringRef s, SMLoc loc) {
261   getStreamer().PushSection();
262
263   if (ParseDirectiveSection(s, loc)) {
264     getStreamer().PopSection();
265     return true;
266   }
267
268   return false;
269 }
270
271 bool ELFAsmParser::ParseDirectivePopSection(StringRef, SMLoc) {
272   if (!getStreamer().PopSection())
273     return TokError(".popsection without corresponding .pushsection");
274   return false;
275 }
276
277 // FIXME: This is a work in progress.
278 bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc) {
279   StringRef SectionName;
280
281   if (ParseSectionName(SectionName))
282     return TokError("expected identifier in directive");
283
284   StringRef TypeName;
285   int64_t Size = 0;
286   StringRef GroupName;
287   unsigned Flags = 0;
288
289   // Set the defaults first.
290   if (SectionName == ".fini" || SectionName == ".init" ||
291       SectionName == ".rodata")
292     Flags |= ELF::SHF_ALLOC;
293   if (SectionName == ".fini" || SectionName == ".init")
294     Flags |= ELF::SHF_EXECINSTR;
295
296   if (getLexer().is(AsmToken::Comma)) {
297     Lex();
298
299     if (getLexer().isNot(AsmToken::String))
300       return TokError("expected string in directive");
301
302     StringRef FlagsStr = getTok().getStringContents();
303     Lex();
304
305     int extraFlags = parseSectionFlags(FlagsStr);
306     if (extraFlags < 0)
307       return TokError("unknown flag");
308     Flags |= extraFlags;
309
310     bool Mergeable = Flags & ELF::SHF_MERGE;
311     bool Group = Flags & ELF::SHF_GROUP;
312
313     if (getLexer().isNot(AsmToken::Comma)) {
314       if (Mergeable)
315         return TokError("Mergeable section must specify the type");
316       if (Group)
317         return TokError("Group section must specify the type");
318     } else {
319       Lex();
320       if (getLexer().isNot(AsmToken::Percent) && getLexer().isNot(AsmToken::At))
321         return TokError("expected '@' or '%' before type");
322
323       Lex();
324       if (getParser().ParseIdentifier(TypeName))
325         return TokError("expected identifier in directive");
326
327       if (Mergeable) {
328         if (getLexer().isNot(AsmToken::Comma))
329           return TokError("expected the entry size");
330         Lex();
331         if (getParser().ParseAbsoluteExpression(Size))
332           return true;
333         if (Size <= 0)
334           return TokError("entry size must be positive");
335       }
336
337       if (Group) {
338         if (getLexer().isNot(AsmToken::Comma))
339           return TokError("expected group name");
340         Lex();
341         if (getParser().ParseIdentifier(GroupName))
342           return true;
343         if (getLexer().is(AsmToken::Comma)) {
344           Lex();
345           StringRef Linkage;
346           if (getParser().ParseIdentifier(Linkage))
347             return true;
348           if (Linkage != "comdat")
349             return TokError("Linkage must be 'comdat'");
350         }
351       }
352     }
353   }
354
355   if (getLexer().isNot(AsmToken::EndOfStatement))
356     return TokError("unexpected token in directive");
357
358   unsigned Type = ELF::SHT_PROGBITS;
359
360   if (!TypeName.empty()) {
361     if (TypeName == "init_array")
362       Type = ELF::SHT_INIT_ARRAY;
363     else if (TypeName == "fini_array")
364       Type = ELF::SHT_FINI_ARRAY;
365     else if (TypeName == "preinit_array")
366       Type = ELF::SHT_PREINIT_ARRAY;
367     else if (TypeName == "nobits")
368       Type = ELF::SHT_NOBITS;
369     else if (TypeName == "progbits")
370       Type = ELF::SHT_PROGBITS;
371     else if (TypeName == "note")
372       Type = ELF::SHT_NOTE;
373     else if (TypeName == "unwind")
374       Type = ELF::SHT_X86_64_UNWIND;
375     else
376       return TokError("unknown section type");
377   }
378
379   SectionKind Kind = computeSectionKind(Flags);
380   getStreamer().SwitchSection(getContext().getELFSection(SectionName, Type,
381                                                          Flags, Kind, Size,
382                                                          GroupName));
383   return false;
384 }
385
386 bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
387   const MCSection *PreviousSection = getStreamer().getPreviousSection();
388   if (PreviousSection == NULL)
389       return TokError(".previous without corresponding .section");
390   getStreamer().SwitchSection(PreviousSection);
391
392   return false;
393 }
394
395 /// ParseDirectiveELFType
396 ///  ::= .type identifier , @attribute
397 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
398   StringRef Name;
399   if (getParser().ParseIdentifier(Name))
400     return TokError("expected identifier in directive");
401
402   // Handle the identifier as the key symbol.
403   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
404
405   if (getLexer().isNot(AsmToken::Comma))
406     return TokError("unexpected token in '.type' directive");
407   Lex();
408
409   if (getLexer().isNot(AsmToken::Percent) && getLexer().isNot(AsmToken::At))
410     return TokError("expected '@' or '%' before type");
411   Lex();
412
413   StringRef Type;
414   SMLoc TypeLoc;
415
416   TypeLoc = getLexer().getLoc();
417   if (getParser().ParseIdentifier(Type))
418     return TokError("expected symbol type in directive");
419
420   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
421     .Case("function", MCSA_ELF_TypeFunction)
422     .Case("object", MCSA_ELF_TypeObject)
423     .Case("tls_object", MCSA_ELF_TypeTLS)
424     .Case("common", MCSA_ELF_TypeCommon)
425     .Case("notype", MCSA_ELF_TypeNoType)
426     .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
427     .Default(MCSA_Invalid);
428
429   if (Attr == MCSA_Invalid)
430     return Error(TypeLoc, "unsupported attribute in '.type' directive");
431
432   if (getLexer().isNot(AsmToken::EndOfStatement))
433     return TokError("unexpected token in '.type' directive");
434
435   Lex();
436
437   getStreamer().EmitSymbolAttribute(Sym, Attr);
438
439   return false;
440 }
441
442 /// ParseDirectiveIdent
443 ///  ::= .ident string
444 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
445   if (getLexer().isNot(AsmToken::String))
446     return TokError("unexpected token in '.ident' directive");
447
448   StringRef Data = getTok().getIdentifier();
449
450   Lex();
451
452   const MCSection *Comment =
453     getContext().getELFSection(".comment", ELF::SHT_PROGBITS,
454                                ELF::SHF_MERGE |
455                                ELF::SHF_STRINGS,
456                                SectionKind::getReadOnly(),
457                                1, "");
458
459   static bool First = true;
460
461   getStreamer().PushSection();
462   getStreamer().SwitchSection(Comment);
463   if (First)
464     getStreamer().EmitIntValue(0, 1);
465   First = false;
466   getStreamer().EmitBytes(Data, 0);
467   getStreamer().EmitIntValue(0, 1);
468   getStreamer().PopSection();
469   return false;
470 }
471
472 /// ParseDirectiveSymver
473 ///  ::= .symver foo, bar2@zed
474 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
475   StringRef Name;
476   if (getParser().ParseIdentifier(Name))
477     return TokError("expected identifier in directive");
478
479   if (getLexer().isNot(AsmToken::Comma))
480     return TokError("expected a comma");
481
482   Lex();
483
484   StringRef AliasName;
485   if (getParser().ParseIdentifier(AliasName))
486     return TokError("expected identifier in directive");
487
488   if (AliasName.find('@') == StringRef::npos)
489     return TokError("expected a '@' in the name");
490
491   MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
492   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
493   const MCExpr *Value = MCSymbolRefExpr::Create(Sym, getContext());
494
495   getStreamer().EmitAssignment(Alias, Value);
496   return false;
497 }
498
499 /// ParseDirectiveWeakref
500 ///  ::= .weakref foo, bar
501 bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
502   // FIXME: Share code with the other alias building directives.
503
504   StringRef AliasName;
505   if (getParser().ParseIdentifier(AliasName))
506     return TokError("expected identifier in directive");
507
508   if (getLexer().isNot(AsmToken::Comma))
509     return TokError("expected a comma");
510
511   Lex();
512
513   StringRef Name;
514   if (getParser().ParseIdentifier(Name))
515     return TokError("expected identifier in directive");
516
517   MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
518
519   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
520
521   getStreamer().EmitWeakReference(Alias, Sym);
522   return false;
523 }
524
525 namespace llvm {
526
527 MCAsmParserExtension *createELFAsmParser() {
528   return new ELFAsmParser;
529 }
530
531 }