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