1 //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This class implements the parser for assembly files.
12 //===----------------------------------------------------------------------===//
14 #include "AsmParser.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Target/TargetAsmParser.h"
27 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
28 Lexer.PrintMessage(L, Msg.str(), "warning");
31 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
32 Lexer.PrintMessage(L, Msg.str(), "error");
36 bool AsmParser::TokError(const char *Msg) {
37 Lexer.PrintMessage(Lexer.getLoc(), Msg, "error");
41 bool AsmParser::Run() {
45 bool HadError = false;
47 // While we have input, parse each statement.
48 while (Lexer.isNot(AsmToken::Eof)) {
49 if (!ParseStatement()) continue;
51 // If we had an error, remember it and recover by skipping to the next line.
53 EatToEndOfStatement();
59 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
60 void AsmParser::EatToEndOfStatement() {
61 while (Lexer.isNot(AsmToken::EndOfStatement) &&
62 Lexer.isNot(AsmToken::Eof))
66 if (Lexer.is(AsmToken::EndOfStatement))
71 /// ParseParenExpr - Parse a paren expression and return it.
72 /// NOTE: This assumes the leading '(' has already been consumed.
74 /// parenexpr ::= expr)
76 bool AsmParser::ParseParenExpr(AsmExpr *&Res) {
77 if (ParseExpression(Res)) return true;
78 if (Lexer.isNot(AsmToken::RParen))
79 return TokError("expected ')' in parentheses expression");
84 /// ParsePrimaryExpr - Parse a primary expression and return it.
85 /// primaryexpr ::= (parenexpr
86 /// primaryexpr ::= symbol
87 /// primaryexpr ::= number
88 /// primaryexpr ::= ~,+,- primaryexpr
89 bool AsmParser::ParsePrimaryExpr(AsmExpr *&Res) {
90 switch (Lexer.getKind()) {
92 return TokError("unknown token in expression");
93 case AsmToken::Exclaim:
94 Lexer.Lex(); // Eat the operator.
95 if (ParsePrimaryExpr(Res))
97 Res = new AsmUnaryExpr(AsmUnaryExpr::LNot, Res);
99 case AsmToken::Identifier: {
100 // This is a label, this should be parsed as part of an expression, to
101 // handle things like LFOO+4.
102 MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
104 // If this is use of an undefined symbol then mark it external.
105 if (!Sym->getSection() && !Ctx.GetSymbolValue(Sym))
106 Sym->setExternal(true);
108 Res = new AsmSymbolRefExpr(Sym);
109 Lexer.Lex(); // Eat identifier.
112 case AsmToken::Integer:
113 Res = new AsmConstantExpr(Lexer.getTok().getIntVal());
114 Lexer.Lex(); // Eat identifier.
116 case AsmToken::LParen:
117 Lexer.Lex(); // Eat the '('.
118 return ParseParenExpr(Res);
119 case AsmToken::Minus:
120 Lexer.Lex(); // Eat the operator.
121 if (ParsePrimaryExpr(Res))
123 Res = new AsmUnaryExpr(AsmUnaryExpr::Minus, Res);
126 Lexer.Lex(); // Eat the operator.
127 if (ParsePrimaryExpr(Res))
129 Res = new AsmUnaryExpr(AsmUnaryExpr::Plus, Res);
131 case AsmToken::Tilde:
132 Lexer.Lex(); // Eat the operator.
133 if (ParsePrimaryExpr(Res))
135 Res = new AsmUnaryExpr(AsmUnaryExpr::Not, Res);
140 /// ParseExpression - Parse an expression and return it.
142 /// expr ::= expr +,- expr -> lowest.
143 /// expr ::= expr |,^,&,! expr -> middle.
144 /// expr ::= expr *,/,%,<<,>> expr -> highest.
145 /// expr ::= primaryexpr
147 bool AsmParser::ParseExpression(AsmExpr *&Res) {
149 return ParsePrimaryExpr(Res) ||
150 ParseBinOpRHS(1, Res);
153 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
156 SMLoc StartLoc = Lexer.getLoc();
157 if (ParseExpression(Expr))
160 if (!Expr->EvaluateAsAbsolute(Ctx, Res))
161 return Error(StartLoc, "expected absolute expression");
166 bool AsmParser::ParseRelocatableExpression(MCValue &Res) {
169 SMLoc StartLoc = Lexer.getLoc();
170 if (ParseExpression(Expr))
173 if (!Expr->EvaluateAsRelocatable(Ctx, Res))
174 return Error(StartLoc, "expected relocatable expression");
179 bool AsmParser::ParseParenRelocatableExpression(MCValue &Res) {
182 SMLoc StartLoc = Lexer.getLoc();
183 if (ParseParenExpr(Expr))
186 if (!Expr->EvaluateAsRelocatable(Ctx, Res))
187 return Error(StartLoc, "expected relocatable expression");
192 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
193 AsmBinaryExpr::Opcode &Kind) {
195 default: return 0; // not a binop.
197 // Lowest Precedence: &&, ||
198 case AsmToken::AmpAmp:
199 Kind = AsmBinaryExpr::LAnd;
201 case AsmToken::PipePipe:
202 Kind = AsmBinaryExpr::LOr;
205 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
207 Kind = AsmBinaryExpr::Add;
209 case AsmToken::Minus:
210 Kind = AsmBinaryExpr::Sub;
212 case AsmToken::EqualEqual:
213 Kind = AsmBinaryExpr::EQ;
215 case AsmToken::ExclaimEqual:
216 case AsmToken::LessGreater:
217 Kind = AsmBinaryExpr::NE;
220 Kind = AsmBinaryExpr::LT;
222 case AsmToken::LessEqual:
223 Kind = AsmBinaryExpr::LTE;
225 case AsmToken::Greater:
226 Kind = AsmBinaryExpr::GT;
228 case AsmToken::GreaterEqual:
229 Kind = AsmBinaryExpr::GTE;
232 // Intermediate Precedence: |, &, ^
234 // FIXME: gas seems to support '!' as an infix operator?
236 Kind = AsmBinaryExpr::Or;
238 case AsmToken::Caret:
239 Kind = AsmBinaryExpr::Xor;
242 Kind = AsmBinaryExpr::And;
245 // Highest Precedence: *, /, %, <<, >>
247 Kind = AsmBinaryExpr::Mul;
249 case AsmToken::Slash:
250 Kind = AsmBinaryExpr::Div;
252 case AsmToken::Percent:
253 Kind = AsmBinaryExpr::Mod;
255 case AsmToken::LessLess:
256 Kind = AsmBinaryExpr::Shl;
258 case AsmToken::GreaterGreater:
259 Kind = AsmBinaryExpr::Shr;
265 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
266 /// Res contains the LHS of the expression on input.
267 bool AsmParser::ParseBinOpRHS(unsigned Precedence, AsmExpr *&Res) {
269 AsmBinaryExpr::Opcode Kind = AsmBinaryExpr::Add;
270 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
272 // If the next token is lower precedence than we are allowed to eat, return
273 // successfully with what we ate already.
274 if (TokPrec < Precedence)
279 // Eat the next primary expression.
281 if (ParsePrimaryExpr(RHS)) return true;
283 // If BinOp binds less tightly with RHS than the operator after RHS, let
284 // the pending operator take RHS as its LHS.
285 AsmBinaryExpr::Opcode Dummy;
286 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
287 if (TokPrec < NextTokPrec) {
288 if (ParseBinOpRHS(Precedence+1, RHS)) return true;
291 // Merge LHS and RHS according to operator.
292 Res = new AsmBinaryExpr(Kind, Res, RHS);
300 /// ::= EndOfStatement
301 /// ::= Label* Directive ...Operands... EndOfStatement
302 /// ::= Label* Identifier OperandList* EndOfStatement
303 bool AsmParser::ParseStatement() {
304 switch (Lexer.getKind()) {
306 return TokError("unexpected token at start of statement");
307 case AsmToken::EndOfStatement:
310 case AsmToken::Identifier:
312 // TODO: Recurse on local labels etc.
315 // If we have an identifier, handle it as the key symbol.
316 AsmToken ID = Lexer.getTok();
317 SMLoc IDLoc = ID.getLoc();
318 StringRef IDVal = ID.getString();
320 // Consume the identifier, see what is after it.
321 switch (Lexer.Lex().getKind()) {
322 case AsmToken::Colon: {
323 // identifier ':' -> Label.
326 // Diagnose attempt to use a variable as a label.
328 // FIXME: Diagnostics. Note the location of the definition as a label.
329 // FIXME: This doesn't diagnose assignment to a symbol which has been
330 // implicitly marked as external.
331 MCSymbol *Sym = Ctx.GetOrCreateSymbol(IDVal);
332 if (Sym->getSection())
333 return Error(IDLoc, "invalid symbol redefinition");
334 if (Ctx.GetSymbolValue(Sym))
335 return Error(IDLoc, "symbol already used as assembler variable");
337 // Since we saw a label, create a symbol and emit it.
338 // FIXME: If the label starts with L it is an assembler temporary label.
339 // Why does the client of this api need to know this?
342 return ParseStatement();
345 case AsmToken::Equal:
346 // identifier '=' ... -> assignment statement
349 return ParseAssignment(IDVal, false);
351 default: // Normal instruction or directive.
355 // Otherwise, we have a normal instruction or directive.
356 if (IDVal[0] == '.') {
357 // FIXME: This should be driven based on a hash lookup and callback.
358 if (IDVal == ".section")
359 return ParseDirectiveDarwinSection();
360 if (IDVal == ".text")
361 // FIXME: This changes behavior based on the -static flag to the
363 return ParseDirectiveSectionSwitch("__TEXT,__text",
364 "regular,pure_instructions");
365 if (IDVal == ".const")
366 return ParseDirectiveSectionSwitch("__TEXT,__const");
367 if (IDVal == ".static_const")
368 return ParseDirectiveSectionSwitch("__TEXT,__static_const");
369 if (IDVal == ".cstring")
370 return ParseDirectiveSectionSwitch("__TEXT,__cstring",
372 if (IDVal == ".literal4")
373 return ParseDirectiveSectionSwitch("__TEXT,__literal4", "4byte_literals");
374 if (IDVal == ".literal8")
375 return ParseDirectiveSectionSwitch("__TEXT,__literal8", "8byte_literals");
376 if (IDVal == ".literal16")
377 return ParseDirectiveSectionSwitch("__TEXT,__literal16",
379 if (IDVal == ".constructor")
380 return ParseDirectiveSectionSwitch("__TEXT,__constructor");
381 if (IDVal == ".destructor")
382 return ParseDirectiveSectionSwitch("__TEXT,__destructor");
383 if (IDVal == ".fvmlib_init0")
384 return ParseDirectiveSectionSwitch("__TEXT,__fvmlib_init0");
385 if (IDVal == ".fvmlib_init1")
386 return ParseDirectiveSectionSwitch("__TEXT,__fvmlib_init1");
387 if (IDVal == ".symbol_stub") // FIXME: Different on PPC.
388 return ParseDirectiveSectionSwitch("__IMPORT,__jump_table,symbol_stubs",
389 "self_modifying_code+pure_instructions,5");
390 // FIXME: .picsymbol_stub on PPC.
391 if (IDVal == ".data")
392 return ParseDirectiveSectionSwitch("__DATA,__data");
393 if (IDVal == ".static_data")
394 return ParseDirectiveSectionSwitch("__DATA,__static_data");
395 if (IDVal == ".non_lazy_symbol_pointer")
396 return ParseDirectiveSectionSwitch("__DATA,__nl_symbol_pointer",
397 "non_lazy_symbol_pointers");
398 if (IDVal == ".lazy_symbol_pointer")
399 return ParseDirectiveSectionSwitch("__DATA,__la_symbol_pointer",
400 "lazy_symbol_pointers");
401 if (IDVal == ".dyld")
402 return ParseDirectiveSectionSwitch("__DATA,__dyld");
403 if (IDVal == ".mod_init_func")
404 return ParseDirectiveSectionSwitch("__DATA,__mod_init_func",
406 if (IDVal == ".mod_term_func")
407 return ParseDirectiveSectionSwitch("__DATA,__mod_term_func",
409 if (IDVal == ".const_data")
410 return ParseDirectiveSectionSwitch("__DATA,__const", "regular");
413 // FIXME: Verify attributes on sections.
414 if (IDVal == ".objc_class")
415 return ParseDirectiveSectionSwitch("__OBJC,__class");
416 if (IDVal == ".objc_meta_class")
417 return ParseDirectiveSectionSwitch("__OBJC,__meta_class");
418 if (IDVal == ".objc_cat_cls_meth")
419 return ParseDirectiveSectionSwitch("__OBJC,__cat_cls_meth");
420 if (IDVal == ".objc_cat_inst_meth")
421 return ParseDirectiveSectionSwitch("__OBJC,__cat_inst_meth");
422 if (IDVal == ".objc_protocol")
423 return ParseDirectiveSectionSwitch("__OBJC,__protocol");
424 if (IDVal == ".objc_string_object")
425 return ParseDirectiveSectionSwitch("__OBJC,__string_object");
426 if (IDVal == ".objc_cls_meth")
427 return ParseDirectiveSectionSwitch("__OBJC,__cls_meth");
428 if (IDVal == ".objc_inst_meth")
429 return ParseDirectiveSectionSwitch("__OBJC,__inst_meth");
430 if (IDVal == ".objc_cls_refs")
431 return ParseDirectiveSectionSwitch("__OBJC,__cls_refs");
432 if (IDVal == ".objc_message_refs")
433 return ParseDirectiveSectionSwitch("__OBJC,__message_refs");
434 if (IDVal == ".objc_symbols")
435 return ParseDirectiveSectionSwitch("__OBJC,__symbols");
436 if (IDVal == ".objc_category")
437 return ParseDirectiveSectionSwitch("__OBJC,__category");
438 if (IDVal == ".objc_class_vars")
439 return ParseDirectiveSectionSwitch("__OBJC,__class_vars");
440 if (IDVal == ".objc_instance_vars")
441 return ParseDirectiveSectionSwitch("__OBJC,__instance_vars");
442 if (IDVal == ".objc_module_info")
443 return ParseDirectiveSectionSwitch("__OBJC,__module_info");
444 if (IDVal == ".objc_class_names")
445 return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
446 if (IDVal == ".objc_meth_var_types")
447 return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
448 if (IDVal == ".objc_meth_var_names")
449 return ParseDirectiveSectionSwitch("__TEXT,__cstring","cstring_literals");
450 if (IDVal == ".objc_selector_strs")
451 return ParseDirectiveSectionSwitch("__OBJC,__selector_strs");
453 // Assembler features
455 return ParseDirectiveSet();
459 if (IDVal == ".ascii")
460 return ParseDirectiveAscii(false);
461 if (IDVal == ".asciz")
462 return ParseDirectiveAscii(true);
464 // FIXME: Target hooks for size? Also for "word", "hword".
465 if (IDVal == ".byte")
466 return ParseDirectiveValue(1);
467 if (IDVal == ".short")
468 return ParseDirectiveValue(2);
469 if (IDVal == ".long")
470 return ParseDirectiveValue(4);
471 if (IDVal == ".quad")
472 return ParseDirectiveValue(8);
474 // FIXME: Target hooks for IsPow2.
475 if (IDVal == ".align")
476 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
477 if (IDVal == ".align32")
478 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
479 if (IDVal == ".balign")
480 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
481 if (IDVal == ".balignw")
482 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
483 if (IDVal == ".balignl")
484 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
485 if (IDVal == ".p2align")
486 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
487 if (IDVal == ".p2alignw")
488 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
489 if (IDVal == ".p2alignl")
490 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
493 return ParseDirectiveOrg();
495 if (IDVal == ".fill")
496 return ParseDirectiveFill();
497 if (IDVal == ".space")
498 return ParseDirectiveSpace();
500 // Symbol attribute directives
501 if (IDVal == ".globl" || IDVal == ".global")
502 return ParseDirectiveSymbolAttribute(MCStreamer::Global);
503 if (IDVal == ".hidden")
504 return ParseDirectiveSymbolAttribute(MCStreamer::Hidden);
505 if (IDVal == ".indirect_symbol")
506 return ParseDirectiveSymbolAttribute(MCStreamer::IndirectSymbol);
507 if (IDVal == ".internal")
508 return ParseDirectiveSymbolAttribute(MCStreamer::Internal);
509 if (IDVal == ".lazy_reference")
510 return ParseDirectiveSymbolAttribute(MCStreamer::LazyReference);
511 if (IDVal == ".no_dead_strip")
512 return ParseDirectiveSymbolAttribute(MCStreamer::NoDeadStrip);
513 if (IDVal == ".private_extern")
514 return ParseDirectiveSymbolAttribute(MCStreamer::PrivateExtern);
515 if (IDVal == ".protected")
516 return ParseDirectiveSymbolAttribute(MCStreamer::Protected);
517 if (IDVal == ".reference")
518 return ParseDirectiveSymbolAttribute(MCStreamer::Reference);
519 if (IDVal == ".weak")
520 return ParseDirectiveSymbolAttribute(MCStreamer::Weak);
521 if (IDVal == ".weak_definition")
522 return ParseDirectiveSymbolAttribute(MCStreamer::WeakDefinition);
523 if (IDVal == ".weak_reference")
524 return ParseDirectiveSymbolAttribute(MCStreamer::WeakReference);
526 if (IDVal == ".comm")
527 return ParseDirectiveComm(/*IsLocal=*/false);
528 if (IDVal == ".lcomm")
529 return ParseDirectiveComm(/*IsLocal=*/true);
530 if (IDVal == ".zerofill")
531 return ParseDirectiveDarwinZerofill();
532 if (IDVal == ".desc")
533 return ParseDirectiveDarwinSymbolDesc();
534 if (IDVal == ".lsym")
535 return ParseDirectiveDarwinLsym();
537 if (IDVal == ".subsections_via_symbols")
538 return ParseDirectiveDarwinSubsectionsViaSymbols();
539 if (IDVal == ".abort")
540 return ParseDirectiveAbort();
541 if (IDVal == ".include")
542 return ParseDirectiveInclude();
543 if (IDVal == ".dump")
544 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
545 if (IDVal == ".load")
546 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
548 Warning(IDLoc, "ignoring directive for now");
549 EatToEndOfStatement();
554 if (getTargetParser().ParseInstruction(IDVal, Inst))
557 if (Lexer.isNot(AsmToken::EndOfStatement))
558 return TokError("unexpected token in argument list");
560 // Eat the end of statement marker.
563 // Instruction is good, process it.
564 Out.EmitInstruction(Inst);
566 // Skip to end of line for now.
570 bool AsmParser::ParseAssignment(const StringRef &Name, bool IsDotSet) {
571 // FIXME: Use better location, we should use proper tokens.
572 SMLoc EqualLoc = Lexer.getLoc();
575 if (ParseRelocatableExpression(Value))
578 if (Lexer.isNot(AsmToken::EndOfStatement))
579 return TokError("unexpected token in assignment");
581 // Eat the end of statement marker.
584 // Diagnose assignment to a label.
586 // FIXME: Diagnostics. Note the location of the definition as a label.
587 // FIXME: This doesn't diagnose assignment to a symbol which has been
588 // implicitly marked as external.
589 // FIXME: Handle '.'.
590 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
591 MCSymbol *Sym = Ctx.GetOrCreateSymbol(Name);
592 if (Sym->getSection())
593 return Error(EqualLoc, "invalid assignment to symbol emitted as a label");
594 if (Sym->isExternal())
595 return Error(EqualLoc, "invalid assignment to external symbol");
597 // Do the assignment.
598 Out.EmitAssignment(Sym, Value, IsDotSet);
603 /// ParseDirectiveSet:
604 /// ::= .set identifier ',' expression
605 bool AsmParser::ParseDirectiveSet() {
606 if (Lexer.isNot(AsmToken::Identifier))
607 return TokError("expected identifier after '.set' directive");
609 StringRef Name = Lexer.getTok().getString();
611 if (Lexer.Lex().isNot(AsmToken::Comma))
612 return TokError("unexpected token in '.set'");
615 return ParseAssignment(Name, true);
618 /// ParseDirectiveSection:
619 /// ::= .section identifier (',' identifier)*
620 /// FIXME: This should actually parse out the segment, section, attributes and
621 /// sizeof_stub fields.
622 bool AsmParser::ParseDirectiveDarwinSection() {
623 if (Lexer.isNot(AsmToken::Identifier))
624 return TokError("expected identifier after '.section' directive");
626 std::string Section = Lexer.getTok().getString();
629 // Accept a comma separated list of modifiers.
630 while (Lexer.is(AsmToken::Comma)) {
633 if (Lexer.isNot(AsmToken::Identifier))
634 return TokError("expected identifier in '.section' directive");
636 Section += Lexer.getTok().getString().str();
640 if (Lexer.isNot(AsmToken::EndOfStatement))
641 return TokError("unexpected token in '.section' directive");
644 Out.SwitchSection(Ctx.GetSection(Section.c_str()));
648 bool AsmParser::ParseDirectiveSectionSwitch(const char *Section,
649 const char *Directives) {
650 if (Lexer.isNot(AsmToken::EndOfStatement))
651 return TokError("unexpected token in section switching directive");
654 std::string SectionStr = Section;
655 if (Directives && Directives[0]) {
657 SectionStr += Directives;
660 Out.SwitchSection(Ctx.GetSection(Section));
664 /// ParseDirectiveAscii:
665 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
666 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
667 if (Lexer.isNot(AsmToken::EndOfStatement)) {
669 if (Lexer.isNot(AsmToken::String))
670 return TokError("expected string in '.ascii' or '.asciz' directive");
672 // FIXME: This shouldn't use a const char* + strlen, the string could have
674 // FIXME: Should have accessor for getting string contents.
675 StringRef Str = Lexer.getTok().getString();
676 Out.EmitBytes(Str.substr(1, Str.size() - 2));
678 Out.EmitBytes(StringRef("\0", 1));
682 if (Lexer.is(AsmToken::EndOfStatement))
685 if (Lexer.isNot(AsmToken::Comma))
686 return TokError("unexpected token in '.ascii' or '.asciz' directive");
695 /// ParseDirectiveValue
696 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
697 bool AsmParser::ParseDirectiveValue(unsigned Size) {
698 if (Lexer.isNot(AsmToken::EndOfStatement)) {
701 if (ParseRelocatableExpression(Expr))
704 Out.EmitValue(Expr, Size);
706 if (Lexer.is(AsmToken::EndOfStatement))
709 // FIXME: Improve diagnostic.
710 if (Lexer.isNot(AsmToken::Comma))
711 return TokError("unexpected token in directive");
720 /// ParseDirectiveSpace
721 /// ::= .space expression [ , expression ]
722 bool AsmParser::ParseDirectiveSpace() {
724 if (ParseAbsoluteExpression(NumBytes))
727 int64_t FillExpr = 0;
728 bool HasFillExpr = false;
729 if (Lexer.isNot(AsmToken::EndOfStatement)) {
730 if (Lexer.isNot(AsmToken::Comma))
731 return TokError("unexpected token in '.space' directive");
734 if (ParseAbsoluteExpression(FillExpr))
739 if (Lexer.isNot(AsmToken::EndOfStatement))
740 return TokError("unexpected token in '.space' directive");
746 return TokError("invalid number of bytes in '.space' directive");
748 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
749 for (uint64_t i = 0, e = NumBytes; i != e; ++i)
750 Out.EmitValue(MCValue::get(FillExpr), 1);
755 /// ParseDirectiveFill
756 /// ::= .fill expression , expression , expression
757 bool AsmParser::ParseDirectiveFill() {
759 if (ParseAbsoluteExpression(NumValues))
762 if (Lexer.isNot(AsmToken::Comma))
763 return TokError("unexpected token in '.fill' directive");
767 if (ParseAbsoluteExpression(FillSize))
770 if (Lexer.isNot(AsmToken::Comma))
771 return TokError("unexpected token in '.fill' directive");
775 if (ParseAbsoluteExpression(FillExpr))
778 if (Lexer.isNot(AsmToken::EndOfStatement))
779 return TokError("unexpected token in '.fill' directive");
783 if (FillSize != 1 && FillSize != 2 && FillSize != 4)
784 return TokError("invalid '.fill' size, expected 1, 2, or 4");
786 for (uint64_t i = 0, e = NumValues; i != e; ++i)
787 Out.EmitValue(MCValue::get(FillExpr), FillSize);
792 /// ParseDirectiveOrg
793 /// ::= .org expression [ , expression ]
794 bool AsmParser::ParseDirectiveOrg() {
796 if (ParseRelocatableExpression(Offset))
799 // Parse optional fill expression.
800 int64_t FillExpr = 0;
801 if (Lexer.isNot(AsmToken::EndOfStatement)) {
802 if (Lexer.isNot(AsmToken::Comma))
803 return TokError("unexpected token in '.org' directive");
806 if (ParseAbsoluteExpression(FillExpr))
809 if (Lexer.isNot(AsmToken::EndOfStatement))
810 return TokError("unexpected token in '.org' directive");
815 // FIXME: Only limited forms of relocatable expressions are accepted here, it
816 // has to be relative to the current section.
817 Out.EmitValueToOffset(Offset, FillExpr);
822 /// ParseDirectiveAlign
823 /// ::= {.align, ...} expression [ , expression [ , expression ]]
824 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
826 if (ParseAbsoluteExpression(Alignment))
830 bool HasFillExpr = false;
831 int64_t FillExpr = 0;
832 int64_t MaxBytesToFill = 0;
833 if (Lexer.isNot(AsmToken::EndOfStatement)) {
834 if (Lexer.isNot(AsmToken::Comma))
835 return TokError("unexpected token in directive");
838 // The fill expression can be omitted while specifying a maximum number of
839 // alignment bytes, e.g:
841 if (Lexer.isNot(AsmToken::Comma)) {
843 if (ParseAbsoluteExpression(FillExpr))
847 if (Lexer.isNot(AsmToken::EndOfStatement)) {
848 if (Lexer.isNot(AsmToken::Comma))
849 return TokError("unexpected token in directive");
852 MaxBytesLoc = Lexer.getLoc();
853 if (ParseAbsoluteExpression(MaxBytesToFill))
856 if (Lexer.isNot(AsmToken::EndOfStatement))
857 return TokError("unexpected token in directive");
864 // FIXME: Sometimes fill with nop.
868 // Compute alignment in bytes.
870 // FIXME: Diagnose overflow.
871 Alignment = 1LL << Alignment;
874 // Diagnose non-sensical max bytes to fill.
875 if (MaxBytesLoc.isValid()) {
876 if (MaxBytesToFill < 1) {
877 Warning(MaxBytesLoc, "alignment directive can never be satisfied in this "
878 "many bytes, ignoring");
882 if (MaxBytesToFill >= Alignment) {
883 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
889 // FIXME: Target specific behavior about how the "extra" bytes are filled.
890 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
895 /// ParseDirectiveSymbolAttribute
896 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
897 bool AsmParser::ParseDirectiveSymbolAttribute(MCStreamer::SymbolAttr Attr) {
898 if (Lexer.isNot(AsmToken::EndOfStatement)) {
900 if (Lexer.isNot(AsmToken::Identifier))
901 return TokError("expected identifier in directive");
903 MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
906 // If this is use of an undefined symbol then mark it external.
907 if (!Sym->getSection() && !Ctx.GetSymbolValue(Sym))
908 Sym->setExternal(true);
910 Out.EmitSymbolAttribute(Sym, Attr);
912 if (Lexer.is(AsmToken::EndOfStatement))
915 if (Lexer.isNot(AsmToken::Comma))
916 return TokError("unexpected token in directive");
925 /// ParseDirectiveDarwinSymbolDesc
926 /// ::= .desc identifier , expression
927 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
928 if (Lexer.isNot(AsmToken::Identifier))
929 return TokError("expected identifier in directive");
931 // handle the identifier as the key symbol.
932 SMLoc IDLoc = Lexer.getLoc();
933 MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
936 if (Lexer.isNot(AsmToken::Comma))
937 return TokError("unexpected token in '.desc' directive");
940 SMLoc DescLoc = Lexer.getLoc();
942 if (ParseAbsoluteExpression(DescValue))
945 if (Lexer.isNot(AsmToken::EndOfStatement))
946 return TokError("unexpected token in '.desc' directive");
950 // Set the n_desc field of this Symbol to this DescValue
951 Out.EmitSymbolDesc(Sym, DescValue);
956 /// ParseDirectiveComm
957 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
958 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
959 if (Lexer.isNot(AsmToken::Identifier))
960 return TokError("expected identifier in directive");
962 // handle the identifier as the key symbol.
963 SMLoc IDLoc = Lexer.getLoc();
964 MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
967 if (Lexer.isNot(AsmToken::Comma))
968 return TokError("unexpected token in directive");
972 SMLoc SizeLoc = Lexer.getLoc();
973 if (ParseAbsoluteExpression(Size))
976 int64_t Pow2Alignment = 0;
977 SMLoc Pow2AlignmentLoc;
978 if (Lexer.is(AsmToken::Comma)) {
980 Pow2AlignmentLoc = Lexer.getLoc();
981 if (ParseAbsoluteExpression(Pow2Alignment))
985 if (Lexer.isNot(AsmToken::EndOfStatement))
986 return TokError("unexpected token in '.comm' or '.lcomm' directive");
990 // NOTE: a size of zero for a .comm should create a undefined symbol
991 // but a size of .lcomm creates a bss symbol of size zero.
993 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
994 "be less than zero");
996 // NOTE: The alignment in the directive is a power of 2 value, the assember
997 // may internally end up wanting an alignment in bytes.
998 // FIXME: Diagnose overflow.
999 if (Pow2Alignment < 0)
1000 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1001 "alignment, can't be less than zero");
1003 // TODO: Symbol must be undefined or it is a error to re-defined the symbol
1004 if (Sym->getSection() || Ctx.GetSymbolValue(Sym))
1005 return Error(IDLoc, "invalid symbol redefinition");
1007 // Create the Symbol as a common or local common with Size and Pow2Alignment
1008 Out.EmitCommonSymbol(Sym, Size, Pow2Alignment, IsLocal);
1013 /// ParseDirectiveDarwinZerofill
1014 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1015 /// , align_expression ]]
1016 bool AsmParser::ParseDirectiveDarwinZerofill() {
1017 if (Lexer.isNot(AsmToken::Identifier))
1018 return TokError("expected segment name after '.zerofill' directive");
1019 std::string Section = Lexer.getTok().getString();
1022 if (Lexer.isNot(AsmToken::Comma))
1023 return TokError("unexpected token in directive");
1027 if (Lexer.isNot(AsmToken::Identifier))
1028 return TokError("expected section name after comma in '.zerofill' "
1030 Section += Lexer.getTok().getString().str();
1033 // FIXME: we will need to tell GetSection() that this is to be created with or
1034 // must have the Mach-O section type of S_ZEROFILL. Something like the code
1035 // below could be done but for now it is not as EmitZerofill() does not know
1036 // how to deal with a section type in the section name like
1037 // ParseDirectiveDarwinSection() allows.
1039 // Section += "zerofill";
1041 // If this is the end of the line all that was wanted was to create the
1042 // the section but with no symbol.
1043 if (Lexer.is(AsmToken::EndOfStatement)) {
1044 // Create the zerofill section but no symbol
1045 Out.EmitZerofill(Ctx.GetSection(Section.c_str()));
1049 if (Lexer.isNot(AsmToken::Comma))
1050 return TokError("unexpected token in directive");
1053 if (Lexer.isNot(AsmToken::Identifier))
1054 return TokError("expected identifier in directive");
1056 // handle the identifier as the key symbol.
1057 SMLoc IDLoc = Lexer.getLoc();
1058 MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
1061 if (Lexer.isNot(AsmToken::Comma))
1062 return TokError("unexpected token in directive");
1066 SMLoc SizeLoc = Lexer.getLoc();
1067 if (ParseAbsoluteExpression(Size))
1070 int64_t Pow2Alignment = 0;
1071 SMLoc Pow2AlignmentLoc;
1072 if (Lexer.is(AsmToken::Comma)) {
1074 Pow2AlignmentLoc = Lexer.getLoc();
1075 if (ParseAbsoluteExpression(Pow2Alignment))
1079 if (Lexer.isNot(AsmToken::EndOfStatement))
1080 return TokError("unexpected token in '.zerofill' directive");
1085 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1088 // NOTE: The alignment in the directive is a power of 2 value, the assember
1089 // may internally end up wanting an alignment in bytes.
1090 // FIXME: Diagnose overflow.
1091 if (Pow2Alignment < 0)
1092 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1093 "can't be less than zero");
1095 // TODO: Symbol must be undefined or it is a error to re-defined the symbol
1096 if (Sym->getSection() || Ctx.GetSymbolValue(Sym))
1097 return Error(IDLoc, "invalid symbol redefinition");
1099 // Create the zerofill Symbol with Size and Pow2Alignment
1100 Out.EmitZerofill(Ctx.GetSection(Section.c_str()), Sym, Size, Pow2Alignment);
1105 /// ParseDirectiveDarwinSubsectionsViaSymbols
1106 /// ::= .subsections_via_symbols
1107 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1108 if (Lexer.isNot(AsmToken::EndOfStatement))
1109 return TokError("unexpected token in '.subsections_via_symbols' directive");
1113 Out.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1118 /// ParseDirectiveAbort
1119 /// ::= .abort [ "abort_string" ]
1120 bool AsmParser::ParseDirectiveAbort() {
1121 // FIXME: Use loc from directive.
1122 SMLoc Loc = Lexer.getLoc();
1125 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1126 if (Lexer.isNot(AsmToken::String))
1127 return TokError("expected string in '.abort' directive");
1129 Str = Lexer.getTok().getString();
1134 if (Lexer.isNot(AsmToken::EndOfStatement))
1135 return TokError("unexpected token in '.abort' directive");
1139 // FIXME: Handle here.
1141 Error(Loc, ".abort detected. Assembly stopping.");
1143 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1148 /// ParseDirectiveLsym
1149 /// ::= .lsym identifier , expression
1150 bool AsmParser::ParseDirectiveDarwinLsym() {
1151 if (Lexer.isNot(AsmToken::Identifier))
1152 return TokError("expected identifier in directive");
1154 // handle the identifier as the key symbol.
1155 SMLoc IDLoc = Lexer.getLoc();
1156 MCSymbol *Sym = Ctx.GetOrCreateSymbol(Lexer.getTok().getString());
1159 if (Lexer.isNot(AsmToken::Comma))
1160 return TokError("unexpected token in '.lsym' directive");
1164 if (ParseRelocatableExpression(Expr))
1167 if (Lexer.isNot(AsmToken::EndOfStatement))
1168 return TokError("unexpected token in '.lsym' directive");
1172 // Create the Sym with the value of the Expr
1173 Out.EmitLocalSymbol(Sym, Expr);
1178 /// ParseDirectiveInclude
1179 /// ::= .include "filename"
1180 bool AsmParser::ParseDirectiveInclude() {
1181 if (Lexer.isNot(AsmToken::String))
1182 return TokError("expected string in '.include' directive");
1184 std::string Filename = Lexer.getTok().getString();
1185 SMLoc IncludeLoc = Lexer.getLoc();
1188 if (Lexer.isNot(AsmToken::EndOfStatement))
1189 return TokError("unexpected token in '.include' directive");
1191 // Strip the quotes.
1192 Filename = Filename.substr(1, Filename.size()-2);
1194 // Attempt to switch the lexer to the included file before consuming the end
1195 // of statement to avoid losing it when we switch.
1196 if (Lexer.EnterIncludeFile(Filename)) {
1197 Lexer.PrintMessage(IncludeLoc,
1198 "Could not find include file '" + Filename + "'",
1206 /// ParseDirectiveDarwinDumpOrLoad
1207 /// ::= ( .dump | .load ) "filename"
1208 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1209 if (Lexer.isNot(AsmToken::String))
1210 return TokError("expected string in '.dump' or '.load' directive");
1214 if (Lexer.isNot(AsmToken::EndOfStatement))
1215 return TokError("unexpected token in '.dump' or '.load' directive");
1219 // FIXME: If/when .dump and .load are implemented they will be done in the
1220 // the assembly parser and not have any need for an MCStreamer API.
1222 Warning(IDLoc, "ignoring directive .dump for now");
1224 Warning(IDLoc, "ignoring directive .load for now");