llvm-mc: Evaluation for relocatable expressions.
[oota-llvm.git] / tools / llvm-mc / AsmParser.cpp
1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
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 class implements the parser for assembly files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AsmParser.h"
15
16 #include "AsmExpr.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCSymbol.h"
21 #include "llvm/Support/SourceMgr.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace llvm;
24
25 void AsmParser::Warning(SMLoc L, const char *Msg) {
26   Lexer.PrintMessage(L, Msg, "warning");
27 }
28
29 bool AsmParser::Error(SMLoc L, const char *Msg) {
30   Lexer.PrintMessage(L, Msg, "error");
31   return true;
32 }
33
34 bool AsmParser::TokError(const char *Msg) {
35   Lexer.PrintMessage(Lexer.getLoc(), Msg, "error");
36   return true;
37 }
38
39 bool AsmParser::Run() {
40   // Prime the lexer.
41   Lexer.Lex();
42   
43   while (Lexer.isNot(asmtok::Eof))
44     if (ParseStatement())
45       return true;
46   
47   return false;
48 }
49
50 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
51 void AsmParser::EatToEndOfStatement() {
52   while (Lexer.isNot(asmtok::EndOfStatement) &&
53          Lexer.isNot(asmtok::Eof))
54     Lexer.Lex();
55   
56   // Eat EOL.
57   if (Lexer.is(asmtok::EndOfStatement))
58     Lexer.Lex();
59 }
60
61
62 /// ParseParenExpr - Parse a paren expression and return it.
63 /// NOTE: This assumes the leading '(' has already been consumed.
64 ///
65 /// parenexpr ::= expr)
66 ///
67 bool AsmParser::ParseParenExpr(AsmExpr *&Res) {
68   if (ParseExpression(Res)) return true;
69   if (Lexer.isNot(asmtok::RParen))
70     return TokError("expected ')' in parentheses expression");
71   Lexer.Lex();
72   return false;
73 }
74
75 /// ParsePrimaryExpr - Parse a primary expression and return it.
76 ///  primaryexpr ::= (parenexpr
77 ///  primaryexpr ::= symbol
78 ///  primaryexpr ::= number
79 ///  primaryexpr ::= ~,+,- primaryexpr
80 bool AsmParser::ParsePrimaryExpr(AsmExpr *&Res) {
81   switch (Lexer.getKind()) {
82   default:
83     return TokError("unknown token in expression");
84   case asmtok::Exclaim:
85     Lexer.Lex(); // Eat the operator.
86     if (ParsePrimaryExpr(Res))
87       return true;
88     Res = new AsmUnaryExpr(AsmUnaryExpr::LNot, Res);
89     return false;
90   case asmtok::Identifier: {
91     // This is a label, this should be parsed as part of an expression, to
92     // handle things like LFOO+4.
93     MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getCurStrVal());
94
95     // If this is use of an undefined symbol then mark it external.
96     if (!Sym->getSection() && !Ctx.GetSymbolValue(Sym))
97       Sym->setExternal(true);
98     
99     Res = new AsmSymbolRefExpr(Sym);
100     Lexer.Lex(); // Eat identifier.
101     return false;
102   }
103   case asmtok::IntVal:
104     Res = new AsmConstantExpr(Lexer.getCurIntVal());
105     Lexer.Lex(); // Eat identifier.
106     return false;
107   case asmtok::LParen:
108     Lexer.Lex(); // Eat the '('.
109     return ParseParenExpr(Res);
110   case asmtok::Minus:
111     Lexer.Lex(); // Eat the operator.
112     if (ParsePrimaryExpr(Res))
113       return true;
114     Res = new AsmUnaryExpr(AsmUnaryExpr::Minus, Res);
115     return false;
116   case asmtok::Plus:
117     Lexer.Lex(); // Eat the operator.
118     if (ParsePrimaryExpr(Res))
119       return true;
120     Res = new AsmUnaryExpr(AsmUnaryExpr::Plus, Res);
121     return false;
122   case asmtok::Tilde:
123     Lexer.Lex(); // Eat the operator.
124     if (ParsePrimaryExpr(Res))
125       return true;
126     Res = new AsmUnaryExpr(AsmUnaryExpr::Not, Res);
127     return false;
128   }
129 }
130
131 /// ParseExpression - Parse an expression and return it.
132 /// 
133 ///  expr ::= expr +,- expr          -> lowest.
134 ///  expr ::= expr |,^,&,! expr      -> middle.
135 ///  expr ::= expr *,/,%,<<,>> expr  -> highest.
136 ///  expr ::= primaryexpr
137 ///
138 bool AsmParser::ParseExpression(AsmExpr *&Res) {
139   Res = 0;
140   return ParsePrimaryExpr(Res) ||
141          ParseBinOpRHS(1, Res);
142 }
143
144 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
145   AsmExpr *Expr;
146   
147   if (ParseExpression(Expr))
148     return true;
149
150   if (!Expr->EvaluateAsAbsolute(Ctx, Res))
151     return TokError("expected absolute expression");
152
153   return false;
154 }
155
156 bool AsmParser::ParseRelocatableExpression(MCValue &Res) {
157   AsmExpr *Expr;
158   
159   if (ParseExpression(Expr))
160     return true;
161
162   if (!Expr->EvaluateAsRelocatable(Ctx, Res))
163     return TokError("expected relocatable expression");
164
165   return false;
166 }
167
168 static unsigned getBinOpPrecedence(asmtok::TokKind K, 
169                                    AsmBinaryExpr::Opcode &Kind) {
170   switch (K) {
171   default: return 0;    // not a binop.
172
173     // Lowest Precedence: &&, ||
174   case asmtok::AmpAmp:
175     Kind = AsmBinaryExpr::LAnd;
176     return 1;
177   case asmtok::PipePipe:
178     Kind = AsmBinaryExpr::LOr;
179     return 1;
180
181     // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
182   case asmtok::Plus:
183     Kind = AsmBinaryExpr::Add;
184     return 2;
185   case asmtok::Minus:
186     Kind = AsmBinaryExpr::Sub;
187     return 2;
188   case asmtok::EqualEqual:
189     Kind = AsmBinaryExpr::EQ;
190     return 2;
191   case asmtok::ExclaimEqual:
192   case asmtok::LessGreater:
193     Kind = AsmBinaryExpr::NE;
194     return 2;
195   case asmtok::Less:
196     Kind = AsmBinaryExpr::LT;
197     return 2;
198   case asmtok::LessEqual:
199     Kind = AsmBinaryExpr::LTE;
200     return 2;
201   case asmtok::Greater:
202     Kind = AsmBinaryExpr::GT;
203     return 2;
204   case asmtok::GreaterEqual:
205     Kind = AsmBinaryExpr::GTE;
206     return 2;
207
208     // Intermediate Precedence: |, &, ^
209     //
210     // FIXME: gas seems to support '!' as an infix operator?
211   case asmtok::Pipe:
212     Kind = AsmBinaryExpr::Or;
213     return 3;
214   case asmtok::Caret:
215     Kind = AsmBinaryExpr::Xor;
216     return 3;
217   case asmtok::Amp:
218     Kind = AsmBinaryExpr::And;
219     return 3;
220
221     // Highest Precedence: *, /, %, <<, >>
222   case asmtok::Star:
223     Kind = AsmBinaryExpr::Mul;
224     return 4;
225   case asmtok::Slash:
226     Kind = AsmBinaryExpr::Div;
227     return 4;
228   case asmtok::Percent:
229     Kind = AsmBinaryExpr::Mod;
230     return 4;
231   case asmtok::LessLess:
232     Kind = AsmBinaryExpr::Shl;
233     return 4;
234   case asmtok::GreaterGreater:
235     Kind = AsmBinaryExpr::Shr;
236     return 4;
237   }
238 }
239
240
241 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
242 /// Res contains the LHS of the expression on input.
243 bool AsmParser::ParseBinOpRHS(unsigned Precedence, AsmExpr *&Res) {
244   while (1) {
245     AsmBinaryExpr::Opcode Kind = AsmBinaryExpr::Add;
246     unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
247     
248     // If the next token is lower precedence than we are allowed to eat, return
249     // successfully with what we ate already.
250     if (TokPrec < Precedence)
251       return false;
252     
253     Lexer.Lex();
254     
255     // Eat the next primary expression.
256     AsmExpr *RHS;
257     if (ParsePrimaryExpr(RHS)) return true;
258     
259     // If BinOp binds less tightly with RHS than the operator after RHS, let
260     // the pending operator take RHS as its LHS.
261     AsmBinaryExpr::Opcode Dummy;
262     unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
263     if (TokPrec < NextTokPrec) {
264       if (ParseBinOpRHS(Precedence+1, RHS)) return true;
265     }
266
267     // Merge LHS and RHS according to operator.
268     Res = new AsmBinaryExpr(Kind, Res, RHS);
269   }
270 }
271
272   
273   
274   
275 /// ParseStatement:
276 ///   ::= EndOfStatement
277 ///   ::= Label* Directive ...Operands... EndOfStatement
278 ///   ::= Label* Identifier OperandList* EndOfStatement
279 bool AsmParser::ParseStatement() {
280   switch (Lexer.getKind()) {
281   default:
282     return TokError("unexpected token at start of statement");
283   case asmtok::EndOfStatement:
284     Lexer.Lex();
285     return false;
286   case asmtok::Identifier:
287     break;
288   // TODO: Recurse on local labels etc.
289   }
290   
291   // If we have an identifier, handle it as the key symbol.
292   SMLoc IDLoc = Lexer.getLoc();
293   const char *IDVal = Lexer.getCurStrVal();
294   
295   // Consume the identifier, see what is after it.
296   switch (Lexer.Lex()) {
297   case asmtok::Colon: {
298     // identifier ':'   -> Label.
299     Lexer.Lex();
300
301     // Diagnose attempt to use a variable as a label.
302     //
303     // FIXME: Diagnostics. Note the location of the definition as a label.
304     // FIXME: This doesn't diagnose assignment to a symbol which has been
305     // implicitly marked as external.
306     MCSymbol *Sym = Ctx.GetOrCreateSymbol(IDVal);
307     if (Sym->getSection())
308       return Error(IDLoc, "invalid symbol redefinition");
309     if (Ctx.GetSymbolValue(Sym))
310       return Error(IDLoc, "symbol already used as assembler variable");
311     
312     // Since we saw a label, create a symbol and emit it.
313     // FIXME: If the label starts with L it is an assembler temporary label.
314     // Why does the client of this api need to know this?
315     Out.EmitLabel(Sym);
316    
317     return ParseStatement();
318   }
319
320   case asmtok::Equal:
321     // identifier '=' ... -> assignment statement
322     Lexer.Lex();
323
324     return ParseAssignment(IDVal, false);
325
326   default: // Normal instruction or directive.
327     break;
328   }
329   
330   // Otherwise, we have a normal instruction or directive.  
331   if (IDVal[0] == '.') {
332     // FIXME: This should be driven based on a hash lookup and callback.
333     if (!strcmp(IDVal, ".section"))
334       return ParseDirectiveDarwinSection();
335     if (!strcmp(IDVal, ".text"))
336       // FIXME: This changes behavior based on the -static flag to the
337       // assembler.
338       return ParseDirectiveSectionSwitch("__TEXT,__text",
339                                          "regular,pure_instructions");
340     if (!strcmp(IDVal, ".const"))
341       return ParseDirectiveSectionSwitch("__TEXT,__const");
342     if (!strcmp(IDVal, ".static_const"))
343       return ParseDirectiveSectionSwitch("__TEXT,__static_const");
344     if (!strcmp(IDVal, ".cstring"))
345       return ParseDirectiveSectionSwitch("__TEXT,__cstring", 
346                                          "cstring_literals");
347     if (!strcmp(IDVal, ".literal4"))
348       return ParseDirectiveSectionSwitch("__TEXT,__literal4", "4byte_literals");
349     if (!strcmp(IDVal, ".literal8"))
350       return ParseDirectiveSectionSwitch("__TEXT,__literal8", "8byte_literals");
351     if (!strcmp(IDVal, ".literal16"))
352       return ParseDirectiveSectionSwitch("__TEXT,__literal16",
353                                          "16byte_literals");
354     if (!strcmp(IDVal, ".constructor"))
355       return ParseDirectiveSectionSwitch("__TEXT,__constructor");
356     if (!strcmp(IDVal, ".destructor"))
357       return ParseDirectiveSectionSwitch("__TEXT,__destructor");
358     if (!strcmp(IDVal, ".fvmlib_init0"))
359       return ParseDirectiveSectionSwitch("__TEXT,__fvmlib_init0");
360     if (!strcmp(IDVal, ".fvmlib_init1"))
361       return ParseDirectiveSectionSwitch("__TEXT,__fvmlib_init1");
362     if (!strcmp(IDVal, ".symbol_stub")) // FIXME: Different on PPC.
363       return ParseDirectiveSectionSwitch("__IMPORT,__jump_table,symbol_stubs",
364                                     "self_modifying_code+pure_instructions,5");
365     // FIXME: .picsymbol_stub on PPC.
366     if (!strcmp(IDVal, ".data"))
367       return ParseDirectiveSectionSwitch("__DATA,__data");
368     if (!strcmp(IDVal, ".static_data"))
369       return ParseDirectiveSectionSwitch("__DATA,__static_data");
370     if (!strcmp(IDVal, ".non_lazy_symbol_pointer"))
371       return ParseDirectiveSectionSwitch("__DATA,__nl_symbol_pointer",
372                                          "non_lazy_symbol_pointers");
373     if (!strcmp(IDVal, ".lazy_symbol_pointer"))
374       return ParseDirectiveSectionSwitch("__DATA,__la_symbol_pointer",
375                                          "lazy_symbol_pointers");
376     if (!strcmp(IDVal, ".dyld"))
377       return ParseDirectiveSectionSwitch("__DATA,__dyld");
378     if (!strcmp(IDVal, ".mod_init_func"))
379       return ParseDirectiveSectionSwitch("__DATA,__mod_init_func",
380                                          "mod_init_funcs");
381     if (!strcmp(IDVal, ".mod_term_func"))
382       return ParseDirectiveSectionSwitch("__DATA,__mod_term_func",
383                                          "mod_term_funcs");
384     if (!strcmp(IDVal, ".const_data"))
385       return ParseDirectiveSectionSwitch("__DATA,__const", "regular");
386     
387     
388     // FIXME: Verify attributes on sections.
389     if (!strcmp(IDVal, ".objc_class"))
390       return ParseDirectiveSectionSwitch("__OBJC,__class");
391     if (!strcmp(IDVal, ".objc_meta_class"))
392       return ParseDirectiveSectionSwitch("__OBJC,__meta_class");
393     if (!strcmp(IDVal, ".objc_cat_cls_meth"))
394       return ParseDirectiveSectionSwitch("__OBJC,__cat_cls_meth");
395     if (!strcmp(IDVal, ".objc_cat_inst_meth"))
396       return ParseDirectiveSectionSwitch("__OBJC,__cat_inst_meth");
397     if (!strcmp(IDVal, ".objc_protocol"))
398       return ParseDirectiveSectionSwitch("__OBJC,__protocol");
399     if (!strcmp(IDVal, ".objc_string_object"))
400       return ParseDirectiveSectionSwitch("__OBJC,__string_object");
401     if (!strcmp(IDVal, ".objc_cls_meth"))
402       return ParseDirectiveSectionSwitch("__OBJC,__cls_meth");
403     if (!strcmp(IDVal, ".objc_inst_meth"))
404       return ParseDirectiveSectionSwitch("__OBJC,__inst_meth");
405     if (!strcmp(IDVal, ".objc_cls_refs"))
406       return ParseDirectiveSectionSwitch("__OBJC,__cls_refs");
407     if (!strcmp(IDVal, ".objc_message_refs"))
408       return ParseDirectiveSectionSwitch("__OBJC,__message_refs");
409     if (!strcmp(IDVal, ".objc_symbols"))
410       return ParseDirectiveSectionSwitch("__OBJC,__symbols");
411     if (!strcmp(IDVal, ".objc_category"))
412       return ParseDirectiveSectionSwitch("__OBJC,__category");
413     if (!strcmp(IDVal, ".objc_class_vars"))
414       return ParseDirectiveSectionSwitch("__OBJC,__class_vars");
415     if (!strcmp(IDVal, ".objc_instance_vars"))
416       return ParseDirectiveSectionSwitch("__OBJC,__instance_vars");
417     if (!strcmp(IDVal, ".objc_module_info"))
418       return ParseDirectiveSectionSwitch("__OBJC,__module_info");
419     if (!strcmp(IDVal, ".objc_class_names"))
420       return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
421     if (!strcmp(IDVal, ".objc_meth_var_types"))
422       return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
423     if (!strcmp(IDVal, ".objc_meth_var_names"))
424       return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
425     if (!strcmp(IDVal, ".objc_selector_strs"))
426       return ParseDirectiveSectionSwitch("__OBJC,__selector_strs");
427     
428     // Assembler features
429     if (!strcmp(IDVal, ".set"))
430       return ParseDirectiveSet();
431
432     // Data directives
433
434     if (!strcmp(IDVal, ".ascii"))
435       return ParseDirectiveAscii(false);
436     if (!strcmp(IDVal, ".asciz"))
437       return ParseDirectiveAscii(true);
438
439     // FIXME: Target hooks for size? Also for "word", "hword".
440     if (!strcmp(IDVal, ".byte"))
441       return ParseDirectiveValue(1);
442     if (!strcmp(IDVal, ".short"))
443       return ParseDirectiveValue(2);
444     if (!strcmp(IDVal, ".long"))
445       return ParseDirectiveValue(4);
446     if (!strcmp(IDVal, ".quad"))
447       return ParseDirectiveValue(8);
448
449     // FIXME: Target hooks for IsPow2.
450     if (!strcmp(IDVal, ".align"))
451       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
452     if (!strcmp(IDVal, ".align32"))
453       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
454     if (!strcmp(IDVal, ".balign"))
455       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
456     if (!strcmp(IDVal, ".balignw"))
457       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
458     if (!strcmp(IDVal, ".balignl"))
459       return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
460     if (!strcmp(IDVal, ".p2align"))
461       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
462     if (!strcmp(IDVal, ".p2alignw"))
463       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
464     if (!strcmp(IDVal, ".p2alignl"))
465       return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
466
467     if (!strcmp(IDVal, ".org"))
468       return ParseDirectiveOrg();
469
470     if (!strcmp(IDVal, ".fill"))
471       return ParseDirectiveFill();
472     if (!strcmp(IDVal, ".space"))
473       return ParseDirectiveSpace();
474
475     // Symbol attribute directives
476     if (!strcmp(IDVal, ".globl") || !strcmp(IDVal, ".global"))
477       return ParseDirectiveSymbolAttribute(MCStreamer::Global);
478     if (!strcmp(IDVal, ".hidden"))
479       return ParseDirectiveSymbolAttribute(MCStreamer::Hidden);
480     if (!strcmp(IDVal, ".indirect_symbol"))
481       return ParseDirectiveSymbolAttribute(MCStreamer::IndirectSymbol);
482     if (!strcmp(IDVal, ".internal"))
483       return ParseDirectiveSymbolAttribute(MCStreamer::Internal);
484     if (!strcmp(IDVal, ".lazy_reference"))
485       return ParseDirectiveSymbolAttribute(MCStreamer::LazyReference);
486     if (!strcmp(IDVal, ".no_dead_strip"))
487       return ParseDirectiveSymbolAttribute(MCStreamer::NoDeadStrip);
488     if (!strcmp(IDVal, ".private_extern"))
489       return ParseDirectiveSymbolAttribute(MCStreamer::PrivateExtern);
490     if (!strcmp(IDVal, ".protected"))
491       return ParseDirectiveSymbolAttribute(MCStreamer::Protected);
492     if (!strcmp(IDVal, ".reference"))
493       return ParseDirectiveSymbolAttribute(MCStreamer::Reference);
494     if (!strcmp(IDVal, ".weak"))
495       return ParseDirectiveSymbolAttribute(MCStreamer::Weak);
496     if (!strcmp(IDVal, ".weak_definition"))
497       return ParseDirectiveSymbolAttribute(MCStreamer::WeakDefinition);
498     if (!strcmp(IDVal, ".weak_reference"))
499       return ParseDirectiveSymbolAttribute(MCStreamer::WeakReference);
500
501     Warning(IDLoc, "ignoring directive for now");
502     EatToEndOfStatement();
503     return false;
504   }
505
506   MCInst Inst;
507   if (ParseX86InstOperands(Inst))
508     return true;
509   
510   if (Lexer.isNot(asmtok::EndOfStatement))
511     return TokError("unexpected token in argument list");
512
513   // Eat the end of statement marker.
514   Lexer.Lex();
515   
516   // Instruction is good, process it.
517   outs() << "Found instruction: " << IDVal << " with " << Inst.getNumOperands()
518          << " operands.\n";
519   
520   // Skip to end of line for now.
521   return false;
522 }
523
524 bool AsmParser::ParseAssignment(const char *Name, bool IsDotSet) {
525   // FIXME: Use better location, we should use proper tokens.
526   SMLoc EqualLoc = Lexer.getLoc();
527
528   int64_t Value;
529   if (ParseAbsoluteExpression(Value))
530     return true;
531   
532   if (Lexer.isNot(asmtok::EndOfStatement))
533     return TokError("unexpected token in assignment");
534
535   // Eat the end of statement marker.
536   Lexer.Lex();
537
538   // Diagnose assignment to a label.
539   //
540   // FIXME: Diagnostics. Note the location of the definition as a label.
541   // FIXME: This doesn't diagnose assignment to a symbol which has been
542   // implicitly marked as external.
543   // FIXME: Handle '.'.
544   // FIXME: Diagnose assignment to protected identifier (e.g., register name).
545   MCSymbol *Sym = Ctx.GetOrCreateSymbol(Name);
546   if (Sym->getSection())
547     return Error(EqualLoc, "invalid assignment to symbol emitted as a label");
548   if (Sym->isExternal())
549     return Error(EqualLoc, "invalid assignment to external symbol");
550
551   // Do the assignment.
552   Out.EmitAssignment(Sym, MCValue::get(Value), IsDotSet);
553
554   return false;
555 }
556
557 /// ParseDirectiveSet:
558 ///   ::= .set identifier ',' expression
559 bool AsmParser::ParseDirectiveSet() {
560   if (Lexer.isNot(asmtok::Identifier))
561     return TokError("expected identifier after '.set' directive");
562
563   const char *Name = Lexer.getCurStrVal();
564   
565   if (Lexer.Lex() != asmtok::Comma)
566     return TokError("unexpected token in '.set'");
567   Lexer.Lex();
568
569   return ParseAssignment(Name, true);
570 }
571
572 /// ParseDirectiveSection:
573 ///   ::= .section identifier (',' identifier)*
574 /// FIXME: This should actually parse out the segment, section, attributes and
575 /// sizeof_stub fields.
576 bool AsmParser::ParseDirectiveDarwinSection() {
577   if (Lexer.isNot(asmtok::Identifier))
578     return TokError("expected identifier after '.section' directive");
579   
580   std::string Section = Lexer.getCurStrVal();
581   Lexer.Lex();
582   
583   // Accept a comma separated list of modifiers.
584   while (Lexer.is(asmtok::Comma)) {
585     Lexer.Lex();
586     
587     if (Lexer.isNot(asmtok::Identifier))
588       return TokError("expected identifier in '.section' directive");
589     Section += ',';
590     Section += Lexer.getCurStrVal();
591     Lexer.Lex();
592   }
593   
594   if (Lexer.isNot(asmtok::EndOfStatement))
595     return TokError("unexpected token in '.section' directive");
596   Lexer.Lex();
597
598   Out.SwitchSection(Ctx.GetSection(Section.c_str()));
599   return false;
600 }
601
602 bool AsmParser::ParseDirectiveSectionSwitch(const char *Section,
603                                             const char *Directives) {
604   if (Lexer.isNot(asmtok::EndOfStatement))
605     return TokError("unexpected token in section switching directive");
606   Lexer.Lex();
607   
608   std::string SectionStr = Section;
609   if (Directives && Directives[0]) {
610     SectionStr += ","; 
611     SectionStr += Directives;
612   }
613   
614   Out.SwitchSection(Ctx.GetSection(Section));
615   return false;
616 }
617
618 /// ParseDirectiveAscii:
619 ///   ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
620 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
621   if (Lexer.isNot(asmtok::EndOfStatement)) {
622     for (;;) {
623       if (Lexer.isNot(asmtok::String))
624         return TokError("expected string in '.ascii' or '.asciz' directive");
625       
626       // FIXME: This shouldn't use a const char* + strlen, the string could have
627       // embedded nulls.
628       // FIXME: Should have accessor for getting string contents.
629       const char *Str = Lexer.getCurStrVal();
630       Out.EmitBytes(Str + 1, strlen(Str) - 2);
631       if (ZeroTerminated)
632         Out.EmitBytes("\0", 1);
633       
634       Lexer.Lex();
635       
636       if (Lexer.is(asmtok::EndOfStatement))
637         break;
638
639       if (Lexer.isNot(asmtok::Comma))
640         return TokError("unexpected token in '.ascii' or '.asciz' directive");
641       Lexer.Lex();
642     }
643   }
644
645   Lexer.Lex();
646   return false;
647 }
648
649 /// ParseDirectiveValue
650 ///  ::= (.byte | .short | ... ) [ expression (, expression)* ]
651 bool AsmParser::ParseDirectiveValue(unsigned Size) {
652   if (Lexer.isNot(asmtok::EndOfStatement)) {
653     for (;;) {
654       int64_t Expr;
655       if (ParseAbsoluteExpression(Expr))
656         return true;
657
658       Out.EmitValue(MCValue::get(Expr), Size);
659
660       if (Lexer.is(asmtok::EndOfStatement))
661         break;
662       
663       // FIXME: Improve diagnostic.
664       if (Lexer.isNot(asmtok::Comma))
665         return TokError("unexpected token in directive");
666       Lexer.Lex();
667     }
668   }
669
670   Lexer.Lex();
671   return false;
672 }
673
674 /// ParseDirectiveSpace
675 ///  ::= .space expression [ , expression ]
676 bool AsmParser::ParseDirectiveSpace() {
677   int64_t NumBytes;
678   if (ParseAbsoluteExpression(NumBytes))
679     return true;
680
681   int64_t FillExpr = 0;
682   bool HasFillExpr = false;
683   if (Lexer.isNot(asmtok::EndOfStatement)) {
684     if (Lexer.isNot(asmtok::Comma))
685       return TokError("unexpected token in '.space' directive");
686     Lexer.Lex();
687     
688     if (ParseAbsoluteExpression(FillExpr))
689       return true;
690
691     HasFillExpr = true;
692
693     if (Lexer.isNot(asmtok::EndOfStatement))
694       return TokError("unexpected token in '.space' directive");
695   }
696
697   Lexer.Lex();
698
699   if (NumBytes <= 0)
700     return TokError("invalid number of bytes in '.space' directive");
701
702   // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
703   for (uint64_t i = 0, e = NumBytes; i != e; ++i)
704     Out.EmitValue(MCValue::get(FillExpr), 1);
705
706   return false;
707 }
708
709 /// ParseDirectiveFill
710 ///  ::= .fill expression , expression , expression
711 bool AsmParser::ParseDirectiveFill() {
712   int64_t NumValues;
713   if (ParseAbsoluteExpression(NumValues))
714     return true;
715
716   if (Lexer.isNot(asmtok::Comma))
717     return TokError("unexpected token in '.fill' directive");
718   Lexer.Lex();
719   
720   int64_t FillSize;
721   if (ParseAbsoluteExpression(FillSize))
722     return true;
723
724   if (Lexer.isNot(asmtok::Comma))
725     return TokError("unexpected token in '.fill' directive");
726   Lexer.Lex();
727   
728   int64_t FillExpr;
729   if (ParseAbsoluteExpression(FillExpr))
730     return true;
731
732   if (Lexer.isNot(asmtok::EndOfStatement))
733     return TokError("unexpected token in '.fill' directive");
734   
735   Lexer.Lex();
736
737   if (FillSize != 1 && FillSize != 2 && FillSize != 4)
738     return TokError("invalid '.fill' size, expected 1, 2, or 4");
739
740   for (uint64_t i = 0, e = NumValues; i != e; ++i)
741     Out.EmitValue(MCValue::get(FillExpr), FillSize);
742
743   return false;
744 }
745
746 /// ParseDirectiveOrg
747 ///  ::= .org expression [ , expression ]
748 bool AsmParser::ParseDirectiveOrg() {
749   int64_t Offset;
750   if (ParseAbsoluteExpression(Offset))
751     return true;
752
753   // Parse optional fill expression.
754   int64_t FillExpr = 0;
755   if (Lexer.isNot(asmtok::EndOfStatement)) {
756     if (Lexer.isNot(asmtok::Comma))
757       return TokError("unexpected token in '.org' directive");
758     Lexer.Lex();
759     
760     if (ParseAbsoluteExpression(FillExpr))
761       return true;
762
763     if (Lexer.isNot(asmtok::EndOfStatement))
764       return TokError("unexpected token in '.org' directive");
765   }
766
767   Lexer.Lex();
768   
769   Out.EmitValueToOffset(MCValue::get(Offset), FillExpr);
770
771   return false;
772 }
773
774 /// ParseDirectiveAlign
775 ///  ::= {.align, ...} expression [ , expression [ , expression ]]
776 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
777   int64_t Alignment;
778   if (ParseAbsoluteExpression(Alignment))
779     return true;
780
781   SMLoc MaxBytesLoc;
782   bool HasFillExpr = false;
783   int64_t FillExpr = 0;
784   int64_t MaxBytesToFill = 0;
785   if (Lexer.isNot(asmtok::EndOfStatement)) {
786     if (Lexer.isNot(asmtok::Comma))
787       return TokError("unexpected token in directive");
788     Lexer.Lex();
789
790     // The fill expression can be omitted while specifying a maximum number of
791     // alignment bytes, e.g:
792     //  .align 3,,4
793     if (Lexer.isNot(asmtok::Comma)) {
794       HasFillExpr = true;
795       if (ParseAbsoluteExpression(FillExpr))
796         return true;
797     }
798
799     if (Lexer.isNot(asmtok::EndOfStatement)) {
800       if (Lexer.isNot(asmtok::Comma))
801         return TokError("unexpected token in directive");
802       Lexer.Lex();
803
804       MaxBytesLoc = Lexer.getLoc();
805       if (ParseAbsoluteExpression(MaxBytesToFill))
806         return true;
807       
808       if (Lexer.isNot(asmtok::EndOfStatement))
809         return TokError("unexpected token in directive");
810     }
811   }
812
813   Lexer.Lex();
814
815   if (!HasFillExpr) {
816     // FIXME: Sometimes fill with nop.
817     FillExpr = 0;
818   }
819
820   // Compute alignment in bytes.
821   if (IsPow2) {
822     // FIXME: Diagnose overflow.
823     Alignment = 1 << Alignment;
824   }
825
826   // Diagnose non-sensical max bytes to fill.
827   if (MaxBytesLoc.isValid()) {
828     if (MaxBytesToFill < 1) {
829       Warning(MaxBytesLoc, "alignment directive can never be satisfied in this "
830               "many bytes, ignoring");
831       return false;
832     }
833
834     if (MaxBytesToFill >= Alignment) {
835       Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
836               "has no effect");
837       MaxBytesToFill = 0;
838     }
839   }
840
841   // FIXME: Target specific behavior about how the "extra" bytes are filled.
842   Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
843
844   return false;
845 }
846
847 /// ParseDirectiveSymbolAttribute
848 ///  ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
849 bool AsmParser::ParseDirectiveSymbolAttribute(MCStreamer::SymbolAttr Attr) {
850   if (Lexer.isNot(asmtok::EndOfStatement)) {
851     for (;;) {
852       if (Lexer.isNot(asmtok::Identifier))
853         return TokError("expected identifier in directive");
854       
855       MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getCurStrVal());
856       Lexer.Lex();
857
858       // If this is use of an undefined symbol then mark it external.
859       if (!Sym->getSection() && !Ctx.GetSymbolValue(Sym))
860         Sym->setExternal(true);
861
862       Out.EmitSymbolAttribute(Sym, Attr);
863
864       if (Lexer.is(asmtok::EndOfStatement))
865         break;
866
867       if (Lexer.isNot(asmtok::Comma))
868         return TokError("unexpected token in directive");
869       Lexer.Lex();
870     }
871   }
872
873   Lexer.Lex();
874   return false;  
875 }