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"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCParsedAsmOperand.h"
22 #include "llvm/MC/MCSectionMachO.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/MC/MCValue.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetAsmParser.h"
32 // Mach-O section uniquing.
34 // FIXME: Figure out where this should live, it should be shared by
35 // TargetLoweringObjectFile.
36 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
38 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
39 const MCAsmInfo &_MAI)
40 : Lexer(_SM, _MAI), Ctx(_Ctx), Out(_Out), TargetParser(0),
41 SectionUniquingMap(0) {
42 // Debugging directives.
43 AddDirectiveHandler(".file", &AsmParser::ParseDirectiveFile);
44 AddDirectiveHandler(".line", &AsmParser::ParseDirectiveLine);
45 AddDirectiveHandler(".loc", &AsmParser::ParseDirectiveLoc);
50 AsmParser::~AsmParser() {
51 // If we have the MachO uniquing map, free it.
52 delete (MachOUniqueMapTy*)SectionUniquingMap;
55 const MCSection *AsmParser::getMachOSection(const StringRef &Segment,
56 const StringRef &Section,
57 unsigned TypeAndAttributes,
59 SectionKind Kind) const {
60 // We unique sections by their segment/section pair. The returned section
61 // may not have the same flags as the requested section, if so this should be
62 // diagnosed by the client as an error.
64 // Create the map if it doesn't already exist.
65 if (SectionUniquingMap == 0)
66 SectionUniquingMap = new MachOUniqueMapTy();
67 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)SectionUniquingMap;
69 // Form the name to look up.
75 // Do the lookup, if we have a hit, return it.
76 const MCSectionMachO *&Entry = Map[Name.str()];
78 // FIXME: This should validate the type and attributes.
79 if (Entry) return Entry;
81 // Otherwise, return a new section.
82 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
83 Reserved2, Kind, Ctx);
86 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
87 Lexer.PrintMessage(L, Msg.str(), "warning");
90 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
91 Lexer.PrintMessage(L, Msg.str(), "error");
95 bool AsmParser::TokError(const char *Msg) {
96 Lexer.PrintMessage(Lexer.getLoc(), Msg, "error");
100 bool AsmParser::Run() {
101 // Create the initial section.
103 // FIXME: Support -n.
104 // FIXME: Target hook & command line option for initial section.
105 Out.SwitchSection(getMachOSection("__TEXT", "__text",
106 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
113 bool HadError = false;
115 AsmCond StartingCondState = TheCondState;
117 // While we have input, parse each statement.
118 while (Lexer.isNot(AsmToken::Eof)) {
119 // Handle conditional assembly here before calling ParseStatement()
120 if (Lexer.getKind() == AsmToken::Identifier) {
121 // If we have an identifier, handle it as the key symbol.
122 AsmToken ID = Lexer.getTok();
123 SMLoc IDLoc = ID.getLoc();
124 StringRef IDVal = ID.getString();
126 if (IDVal == ".if" ||
127 IDVal == ".elseif" ||
130 if (!ParseConditionalAssemblyDirectives(IDVal, IDLoc))
133 EatToEndOfStatement();
137 if (TheCondState.Ignore) {
138 EatToEndOfStatement();
142 if (!ParseStatement()) continue;
144 // We had an error, remember it and recover by skipping to the next line.
146 EatToEndOfStatement();
149 if (TheCondState.TheCond != StartingCondState.TheCond ||
150 TheCondState.Ignore != StartingCondState.Ignore)
151 return TokError("unmatched .ifs or .elses");
159 /// ParseConditionalAssemblyDirectives - parse the conditional assembly
161 bool AsmParser::ParseConditionalAssemblyDirectives(StringRef Directive,
162 SMLoc DirectiveLoc) {
163 if (Directive == ".if")
164 return ParseDirectiveIf(DirectiveLoc);
165 if (Directive == ".elseif")
166 return ParseDirectiveElseIf(DirectiveLoc);
167 if (Directive == ".else")
168 return ParseDirectiveElse(DirectiveLoc);
169 if (Directive == ".endif")
170 return ParseDirectiveEndIf(DirectiveLoc);
174 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
175 void AsmParser::EatToEndOfStatement() {
176 while (Lexer.isNot(AsmToken::EndOfStatement) &&
177 Lexer.isNot(AsmToken::Eof))
181 if (Lexer.is(AsmToken::EndOfStatement))
186 /// ParseParenExpr - Parse a paren expression and return it.
187 /// NOTE: This assumes the leading '(' has already been consumed.
189 /// parenexpr ::= expr)
191 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
192 if (ParseExpression(Res)) return true;
193 if (Lexer.isNot(AsmToken::RParen))
194 return TokError("expected ')' in parentheses expression");
195 EndLoc = Lexer.getLoc();
200 MCSymbol *AsmParser::CreateSymbol(StringRef Name) {
201 if (MCSymbol *S = Ctx.LookupSymbol(Name))
204 // If the label starts with L it is an assembler temporary label.
205 if (Name.startswith("L"))
206 return Ctx.CreateTemporarySymbol(Name);
208 return Ctx.CreateSymbol(Name);
211 /// ParsePrimaryExpr - Parse a primary expression and return it.
212 /// primaryexpr ::= (parenexpr
213 /// primaryexpr ::= symbol
214 /// primaryexpr ::= number
215 /// primaryexpr ::= ~,+,- primaryexpr
216 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
217 switch (Lexer.getKind()) {
219 return TokError("unknown token in expression");
220 case AsmToken::Exclaim:
221 Lexer.Lex(); // Eat the operator.
222 if (ParsePrimaryExpr(Res, EndLoc))
224 Res = MCUnaryExpr::CreateLNot(Res, getContext());
226 case AsmToken::String:
227 case AsmToken::Identifier: {
228 // This is a symbol reference.
229 MCSymbol *Sym = CreateSymbol(Lexer.getTok().getIdentifier());
230 EndLoc = Lexer.getLoc();
231 Lexer.Lex(); // Eat identifier.
233 // If this is an absolute variable reference, substitute it now to preserve
234 // semantics in the face of reassignment.
235 if (Sym->getValue() && isa<MCConstantExpr>(Sym->getValue())) {
236 Res = Sym->getValue();
240 // Otherwise create a symbol ref.
241 Res = MCSymbolRefExpr::Create(Sym, getContext());
244 case AsmToken::Integer:
245 Res = MCConstantExpr::Create(Lexer.getTok().getIntVal(), getContext());
246 EndLoc = Lexer.getLoc();
247 Lexer.Lex(); // Eat token.
249 case AsmToken::LParen:
250 Lexer.Lex(); // Eat the '('.
251 return ParseParenExpr(Res, EndLoc);
252 case AsmToken::Minus:
253 Lexer.Lex(); // Eat the operator.
254 if (ParsePrimaryExpr(Res, EndLoc))
256 Res = MCUnaryExpr::CreateMinus(Res, getContext());
259 Lexer.Lex(); // Eat the operator.
260 if (ParsePrimaryExpr(Res, EndLoc))
262 Res = MCUnaryExpr::CreatePlus(Res, getContext());
264 case AsmToken::Tilde:
265 Lexer.Lex(); // Eat the operator.
266 if (ParsePrimaryExpr(Res, EndLoc))
268 Res = MCUnaryExpr::CreateNot(Res, getContext());
273 bool AsmParser::ParseExpression(const MCExpr *&Res) {
275 return ParseExpression(Res, EndLoc);
278 /// ParseExpression - Parse an expression and return it.
280 /// expr ::= expr +,- expr -> lowest.
281 /// expr ::= expr |,^,&,! expr -> middle.
282 /// expr ::= expr *,/,%,<<,>> expr -> highest.
283 /// expr ::= primaryexpr
285 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
287 return ParsePrimaryExpr(Res, EndLoc) ||
288 ParseBinOpRHS(1, Res, EndLoc);
291 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
292 if (ParseParenExpr(Res, EndLoc))
298 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
301 SMLoc StartLoc = Lexer.getLoc();
302 if (ParseExpression(Expr))
305 if (!Expr->EvaluateAsAbsolute(Res))
306 return Error(StartLoc, "expected absolute expression");
311 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
312 MCBinaryExpr::Opcode &Kind) {
315 return 0; // not a binop.
317 // Lowest Precedence: &&, ||
318 case AsmToken::AmpAmp:
319 Kind = MCBinaryExpr::LAnd;
321 case AsmToken::PipePipe:
322 Kind = MCBinaryExpr::LOr;
325 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
327 Kind = MCBinaryExpr::Add;
329 case AsmToken::Minus:
330 Kind = MCBinaryExpr::Sub;
332 case AsmToken::EqualEqual:
333 Kind = MCBinaryExpr::EQ;
335 case AsmToken::ExclaimEqual:
336 case AsmToken::LessGreater:
337 Kind = MCBinaryExpr::NE;
340 Kind = MCBinaryExpr::LT;
342 case AsmToken::LessEqual:
343 Kind = MCBinaryExpr::LTE;
345 case AsmToken::Greater:
346 Kind = MCBinaryExpr::GT;
348 case AsmToken::GreaterEqual:
349 Kind = MCBinaryExpr::GTE;
352 // Intermediate Precedence: |, &, ^
354 // FIXME: gas seems to support '!' as an infix operator?
356 Kind = MCBinaryExpr::Or;
358 case AsmToken::Caret:
359 Kind = MCBinaryExpr::Xor;
362 Kind = MCBinaryExpr::And;
365 // Highest Precedence: *, /, %, <<, >>
367 Kind = MCBinaryExpr::Mul;
369 case AsmToken::Slash:
370 Kind = MCBinaryExpr::Div;
372 case AsmToken::Percent:
373 Kind = MCBinaryExpr::Mod;
375 case AsmToken::LessLess:
376 Kind = MCBinaryExpr::Shl;
378 case AsmToken::GreaterGreater:
379 Kind = MCBinaryExpr::Shr;
385 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
386 /// Res contains the LHS of the expression on input.
387 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
390 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
391 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
393 // If the next token is lower precedence than we are allowed to eat, return
394 // successfully with what we ate already.
395 if (TokPrec < Precedence)
400 // Eat the next primary expression.
402 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
404 // If BinOp binds less tightly with RHS than the operator after RHS, let
405 // the pending operator take RHS as its LHS.
406 MCBinaryExpr::Opcode Dummy;
407 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
408 if (TokPrec < NextTokPrec) {
409 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
412 // Merge LHS and RHS according to operator.
413 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
421 /// ::= EndOfStatement
422 /// ::= Label* Directive ...Operands... EndOfStatement
423 /// ::= Label* Identifier OperandList* EndOfStatement
424 bool AsmParser::ParseStatement() {
425 if (Lexer.is(AsmToken::EndOfStatement)) {
430 // Statements always start with an identifier.
431 AsmToken ID = Lexer.getTok();
432 SMLoc IDLoc = ID.getLoc();
434 if (ParseIdentifier(IDVal))
435 return TokError("unexpected token at start of statement");
437 // FIXME: Recurse on local labels?
439 // See what kind of statement we have.
440 switch (Lexer.getKind()) {
441 case AsmToken::Colon: {
442 // identifier ':' -> Label.
445 // Diagnose attempt to use a variable as a label.
447 // FIXME: Diagnostics. Note the location of the definition as a label.
448 // FIXME: This doesn't diagnose assignment to a symbol which has been
449 // implicitly marked as external.
450 MCSymbol *Sym = CreateSymbol(IDVal);
451 if (!Sym->isUndefined())
452 return Error(IDLoc, "invalid symbol redefinition");
457 return ParseStatement();
460 case AsmToken::Equal:
461 // identifier '=' ... -> assignment statement
464 return ParseAssignment(IDVal);
466 default: // Normal instruction or directive.
470 // Otherwise, we have a normal instruction or directive.
471 if (IDVal[0] == '.') {
472 // FIXME: This should be driven based on a hash lookup and callback.
473 if (IDVal == ".section")
474 return ParseDirectiveDarwinSection();
475 if (IDVal == ".text")
476 // FIXME: This changes behavior based on the -static flag to the
478 return ParseDirectiveSectionSwitch("__TEXT", "__text",
479 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
480 if (IDVal == ".const")
481 return ParseDirectiveSectionSwitch("__TEXT", "__const");
482 if (IDVal == ".static_const")
483 return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
484 if (IDVal == ".cstring")
485 return ParseDirectiveSectionSwitch("__TEXT","__cstring",
486 MCSectionMachO::S_CSTRING_LITERALS);
487 if (IDVal == ".literal4")
488 return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
489 MCSectionMachO::S_4BYTE_LITERALS,
491 if (IDVal == ".literal8")
492 return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
493 MCSectionMachO::S_8BYTE_LITERALS,
495 if (IDVal == ".literal16")
496 return ParseDirectiveSectionSwitch("__TEXT","__literal16",
497 MCSectionMachO::S_16BYTE_LITERALS,
499 if (IDVal == ".constructor")
500 return ParseDirectiveSectionSwitch("__TEXT","__constructor");
501 if (IDVal == ".destructor")
502 return ParseDirectiveSectionSwitch("__TEXT","__destructor");
503 if (IDVal == ".fvmlib_init0")
504 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
505 if (IDVal == ".fvmlib_init1")
506 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
508 // FIXME: The assembler manual claims that this has the self modify code
509 // flag, at least on x86-32, but that does not appear to be correct.
510 if (IDVal == ".symbol_stub")
511 return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
512 MCSectionMachO::S_SYMBOL_STUBS |
513 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
514 // FIXME: Different on PPC and ARM.
516 // FIXME: PowerPC only?
517 if (IDVal == ".picsymbol_stub")
518 return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
519 MCSectionMachO::S_SYMBOL_STUBS |
520 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
522 if (IDVal == ".data")
523 return ParseDirectiveSectionSwitch("__DATA", "__data");
524 if (IDVal == ".static_data")
525 return ParseDirectiveSectionSwitch("__DATA", "__static_data");
527 // FIXME: The section names of these two are misspelled in the assembler
529 if (IDVal == ".non_lazy_symbol_pointer")
530 return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
531 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
533 if (IDVal == ".lazy_symbol_pointer")
534 return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
535 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
538 if (IDVal == ".dyld")
539 return ParseDirectiveSectionSwitch("__DATA", "__dyld");
540 if (IDVal == ".mod_init_func")
541 return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
542 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
544 if (IDVal == ".mod_term_func")
545 return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
546 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
548 if (IDVal == ".const_data")
549 return ParseDirectiveSectionSwitch("__DATA", "__const");
552 if (IDVal == ".objc_class")
553 return ParseDirectiveSectionSwitch("__OBJC", "__class",
554 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
555 if (IDVal == ".objc_meta_class")
556 return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
557 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
558 if (IDVal == ".objc_cat_cls_meth")
559 return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
560 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
561 if (IDVal == ".objc_cat_inst_meth")
562 return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
563 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
564 if (IDVal == ".objc_protocol")
565 return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
566 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
567 if (IDVal == ".objc_string_object")
568 return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
569 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
570 if (IDVal == ".objc_cls_meth")
571 return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
572 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
573 if (IDVal == ".objc_inst_meth")
574 return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
575 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
576 if (IDVal == ".objc_cls_refs")
577 return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
578 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
579 MCSectionMachO::S_LITERAL_POINTERS,
581 if (IDVal == ".objc_message_refs")
582 return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
583 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
584 MCSectionMachO::S_LITERAL_POINTERS,
586 if (IDVal == ".objc_symbols")
587 return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
588 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
589 if (IDVal == ".objc_category")
590 return ParseDirectiveSectionSwitch("__OBJC", "__category",
591 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
592 if (IDVal == ".objc_class_vars")
593 return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
594 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
595 if (IDVal == ".objc_instance_vars")
596 return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
597 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
598 if (IDVal == ".objc_module_info")
599 return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
600 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
601 if (IDVal == ".objc_class_names")
602 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
603 MCSectionMachO::S_CSTRING_LITERALS);
604 if (IDVal == ".objc_meth_var_types")
605 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
606 MCSectionMachO::S_CSTRING_LITERALS);
607 if (IDVal == ".objc_meth_var_names")
608 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
609 MCSectionMachO::S_CSTRING_LITERALS);
610 if (IDVal == ".objc_selector_strs")
611 return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
612 MCSectionMachO::S_CSTRING_LITERALS);
614 // Assembler features
616 return ParseDirectiveSet();
620 if (IDVal == ".ascii")
621 return ParseDirectiveAscii(false);
622 if (IDVal == ".asciz")
623 return ParseDirectiveAscii(true);
625 if (IDVal == ".byte")
626 return ParseDirectiveValue(1);
627 if (IDVal == ".short")
628 return ParseDirectiveValue(2);
629 if (IDVal == ".long")
630 return ParseDirectiveValue(4);
631 if (IDVal == ".quad")
632 return ParseDirectiveValue(8);
634 // FIXME: Target hooks for IsPow2.
635 if (IDVal == ".align")
636 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
637 if (IDVal == ".align32")
638 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
639 if (IDVal == ".balign")
640 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
641 if (IDVal == ".balignw")
642 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
643 if (IDVal == ".balignl")
644 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
645 if (IDVal == ".p2align")
646 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
647 if (IDVal == ".p2alignw")
648 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
649 if (IDVal == ".p2alignl")
650 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
653 return ParseDirectiveOrg();
655 if (IDVal == ".fill")
656 return ParseDirectiveFill();
657 if (IDVal == ".space")
658 return ParseDirectiveSpace();
660 // Symbol attribute directives
662 if (IDVal == ".globl" || IDVal == ".global")
663 return ParseDirectiveSymbolAttribute(MCStreamer::Global);
664 if (IDVal == ".hidden")
665 return ParseDirectiveSymbolAttribute(MCStreamer::Hidden);
666 if (IDVal == ".indirect_symbol")
667 return ParseDirectiveSymbolAttribute(MCStreamer::IndirectSymbol);
668 if (IDVal == ".internal")
669 return ParseDirectiveSymbolAttribute(MCStreamer::Internal);
670 if (IDVal == ".lazy_reference")
671 return ParseDirectiveSymbolAttribute(MCStreamer::LazyReference);
672 if (IDVal == ".no_dead_strip")
673 return ParseDirectiveSymbolAttribute(MCStreamer::NoDeadStrip);
674 if (IDVal == ".private_extern")
675 return ParseDirectiveSymbolAttribute(MCStreamer::PrivateExtern);
676 if (IDVal == ".protected")
677 return ParseDirectiveSymbolAttribute(MCStreamer::Protected);
678 if (IDVal == ".reference")
679 return ParseDirectiveSymbolAttribute(MCStreamer::Reference);
680 if (IDVal == ".weak")
681 return ParseDirectiveSymbolAttribute(MCStreamer::Weak);
682 if (IDVal == ".weak_definition")
683 return ParseDirectiveSymbolAttribute(MCStreamer::WeakDefinition);
684 if (IDVal == ".weak_reference")
685 return ParseDirectiveSymbolAttribute(MCStreamer::WeakReference);
687 if (IDVal == ".comm")
688 return ParseDirectiveComm(/*IsLocal=*/false);
689 if (IDVal == ".lcomm")
690 return ParseDirectiveComm(/*IsLocal=*/true);
691 if (IDVal == ".zerofill")
692 return ParseDirectiveDarwinZerofill();
693 if (IDVal == ".desc")
694 return ParseDirectiveDarwinSymbolDesc();
695 if (IDVal == ".lsym")
696 return ParseDirectiveDarwinLsym();
698 if (IDVal == ".subsections_via_symbols")
699 return ParseDirectiveDarwinSubsectionsViaSymbols();
700 if (IDVal == ".abort")
701 return ParseDirectiveAbort();
702 if (IDVal == ".include")
703 return ParseDirectiveInclude();
704 if (IDVal == ".dump")
705 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
706 if (IDVal == ".load")
707 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
709 // Look up the handler in the handler table,
710 bool(AsmParser::*Handler)(StringRef, SMLoc) = DirectiveMap[IDVal];
712 return (this->*Handler)(IDVal, IDLoc);
714 // Target hook for parsing target specific directives.
715 if (!getTargetParser().ParseDirective(ID))
718 Warning(IDLoc, "ignoring directive for now");
719 EatToEndOfStatement();
724 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
725 if (getTargetParser().ParseInstruction(IDVal, IDLoc, ParsedOperands))
726 // FIXME: Leaking ParsedOperands on failure.
729 if (Lexer.isNot(AsmToken::EndOfStatement))
730 // FIXME: Leaking ParsedOperands on failure.
731 return TokError("unexpected token in argument list");
733 // Eat the end of statement marker.
739 bool MatchFail = getTargetParser().MatchInstruction(ParsedOperands, Inst);
741 // Free any parsed operands.
742 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
743 delete ParsedOperands[i];
746 // FIXME: We should give nicer diagnostics about the exact failure.
747 Error(IDLoc, "unrecognized instruction");
751 // Instruction is good, process it.
752 Out.EmitInstruction(Inst);
754 // Skip to end of line for now.
758 bool AsmParser::ParseAssignment(const StringRef &Name) {
759 // FIXME: Use better location, we should use proper tokens.
760 SMLoc EqualLoc = Lexer.getLoc();
763 SMLoc StartLoc = Lexer.getLoc();
764 if (ParseExpression(Value))
767 if (Lexer.isNot(AsmToken::EndOfStatement))
768 return TokError("unexpected token in assignment");
770 // Eat the end of statement marker.
773 // Validate that the LHS is allowed to be a variable (either it has not been
774 // used as a symbol, or it is an absolute symbol).
775 MCSymbol *Sym = getContext().LookupSymbol(Name);
777 // Diagnose assignment to a label.
779 // FIXME: Diagnostics. Note the location of the definition as a label.
780 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
781 if (!Sym->isUndefined() && !Sym->isAbsolute())
782 return Error(EqualLoc, "redefinition of '" + Name + "'");
783 else if (!Sym->isVariable())
784 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
785 else if (!isa<MCConstantExpr>(Sym->getValue()))
786 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
789 Sym = CreateSymbol(Name);
791 // FIXME: Handle '.'.
793 // Do the assignment.
794 Out.EmitAssignment(Sym, Value);
802 bool AsmParser::ParseIdentifier(StringRef &Res) {
803 if (Lexer.isNot(AsmToken::Identifier) &&
804 Lexer.isNot(AsmToken::String))
807 Res = Lexer.getTok().getIdentifier();
809 Lexer.Lex(); // Consume the identifier token.
814 /// ParseDirectiveSet:
815 /// ::= .set identifier ',' expression
816 bool AsmParser::ParseDirectiveSet() {
819 if (ParseIdentifier(Name))
820 return TokError("expected identifier after '.set' directive");
822 if (Lexer.isNot(AsmToken::Comma))
823 return TokError("unexpected token in '.set'");
826 return ParseAssignment(Name);
829 /// ParseDirectiveSection:
830 /// ::= .section identifier (',' identifier)*
831 /// FIXME: This should actually parse out the segment, section, attributes and
832 /// sizeof_stub fields.
833 bool AsmParser::ParseDirectiveDarwinSection() {
834 SMLoc Loc = Lexer.getLoc();
836 StringRef SectionName;
837 if (ParseIdentifier(SectionName))
838 return Error(Loc, "expected identifier after '.section' directive");
840 // Verify there is a following comma.
841 if (!Lexer.is(AsmToken::Comma))
842 return TokError("unexpected token in '.section' directive");
844 std::string SectionSpec = SectionName;
847 // Add all the tokens until the end of the line, ParseSectionSpecifier will
849 StringRef EOL = Lexer.LexUntilEndOfStatement();
850 SectionSpec.append(EOL.begin(), EOL.end());
853 if (Lexer.isNot(AsmToken::EndOfStatement))
854 return TokError("unexpected token in '.section' directive");
858 StringRef Segment, Section;
859 unsigned TAA, StubSize;
860 std::string ErrorStr =
861 MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
864 if (!ErrorStr.empty())
865 return Error(Loc, ErrorStr.c_str());
867 // FIXME: Arch specific.
868 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
873 /// ParseDirectiveSectionSwitch -
874 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
876 unsigned TAA, unsigned Align,
878 if (Lexer.isNot(AsmToken::EndOfStatement))
879 return TokError("unexpected token in section switching directive");
882 // FIXME: Arch specific.
883 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
886 // Set the implicit alignment, if any.
888 // FIXME: This isn't really what 'as' does; I think it just uses the implicit
889 // alignment on the section (e.g., if one manually inserts bytes into the
890 // section, then just issueing the section switch directive will not realign
891 // the section. However, this is arguably more reasonable behavior, and there
892 // is no good reason for someone to intentionally emit incorrectly sized
893 // values into the implicitly aligned sections.
895 Out.EmitValueToAlignment(Align, 0, 1, 0);
900 bool AsmParser::ParseEscapedString(std::string &Data) {
901 assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
904 StringRef Str = Lexer.getTok().getStringContents();
905 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
906 if (Str[i] != '\\') {
911 // Recognize escaped characters. Note that this escape semantics currently
912 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
915 return TokError("unexpected backslash at end of string");
917 // Recognize octal sequences.
918 if ((unsigned) (Str[i] - '0') <= 7) {
919 // Consume up to three octal characters.
920 unsigned Value = Str[i] - '0';
922 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
924 Value = Value * 8 + (Str[i] - '0');
926 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
928 Value = Value * 8 + (Str[i] - '0');
933 return TokError("invalid octal escape sequence (out of range)");
935 Data += (unsigned char) Value;
939 // Otherwise recognize individual escapes.
942 // Just reject invalid escape sequences for now.
943 return TokError("invalid escape sequence (unrecognized character)");
945 case 'b': Data += '\b'; break;
946 case 'f': Data += '\f'; break;
947 case 'n': Data += '\n'; break;
948 case 'r': Data += '\r'; break;
949 case 't': Data += '\t'; break;
950 case '"': Data += '"'; break;
951 case '\\': Data += '\\'; break;
958 /// ParseDirectiveAscii:
959 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
960 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
961 if (Lexer.isNot(AsmToken::EndOfStatement)) {
963 if (Lexer.isNot(AsmToken::String))
964 return TokError("expected string in '.ascii' or '.asciz' directive");
967 if (ParseEscapedString(Data))
972 Out.EmitBytes(StringRef("\0", 1));
976 if (Lexer.is(AsmToken::EndOfStatement))
979 if (Lexer.isNot(AsmToken::Comma))
980 return TokError("unexpected token in '.ascii' or '.asciz' directive");
989 /// ParseDirectiveValue
990 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
991 bool AsmParser::ParseDirectiveValue(unsigned Size) {
992 if (Lexer.isNot(AsmToken::EndOfStatement)) {
995 SMLoc ATTRIBUTE_UNUSED StartLoc = Lexer.getLoc();
996 if (ParseExpression(Value))
999 Out.EmitValue(Value, Size);
1001 if (Lexer.is(AsmToken::EndOfStatement))
1004 // FIXME: Improve diagnostic.
1005 if (Lexer.isNot(AsmToken::Comma))
1006 return TokError("unexpected token in directive");
1015 /// ParseDirectiveSpace
1016 /// ::= .space expression [ , expression ]
1017 bool AsmParser::ParseDirectiveSpace() {
1019 if (ParseAbsoluteExpression(NumBytes))
1022 int64_t FillExpr = 0;
1023 bool HasFillExpr = false;
1024 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1025 if (Lexer.isNot(AsmToken::Comma))
1026 return TokError("unexpected token in '.space' directive");
1029 if (ParseAbsoluteExpression(FillExpr))
1034 if (Lexer.isNot(AsmToken::EndOfStatement))
1035 return TokError("unexpected token in '.space' directive");
1041 return TokError("invalid number of bytes in '.space' directive");
1043 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1044 for (uint64_t i = 0, e = NumBytes; i != e; ++i)
1045 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), 1);
1050 /// ParseDirectiveFill
1051 /// ::= .fill expression , expression , expression
1052 bool AsmParser::ParseDirectiveFill() {
1054 if (ParseAbsoluteExpression(NumValues))
1057 if (Lexer.isNot(AsmToken::Comma))
1058 return TokError("unexpected token in '.fill' directive");
1062 if (ParseAbsoluteExpression(FillSize))
1065 if (Lexer.isNot(AsmToken::Comma))
1066 return TokError("unexpected token in '.fill' directive");
1070 if (ParseAbsoluteExpression(FillExpr))
1073 if (Lexer.isNot(AsmToken::EndOfStatement))
1074 return TokError("unexpected token in '.fill' directive");
1078 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1079 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1081 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1082 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), FillSize);
1087 /// ParseDirectiveOrg
1088 /// ::= .org expression [ , expression ]
1089 bool AsmParser::ParseDirectiveOrg() {
1090 const MCExpr *Offset;
1091 SMLoc StartLoc = Lexer.getLoc();
1092 if (ParseExpression(Offset))
1095 // Parse optional fill expression.
1096 int64_t FillExpr = 0;
1097 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1098 if (Lexer.isNot(AsmToken::Comma))
1099 return TokError("unexpected token in '.org' directive");
1102 if (ParseAbsoluteExpression(FillExpr))
1105 if (Lexer.isNot(AsmToken::EndOfStatement))
1106 return TokError("unexpected token in '.org' directive");
1111 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1112 // has to be relative to the current section.
1113 Out.EmitValueToOffset(Offset, FillExpr);
1118 /// ParseDirectiveAlign
1119 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1120 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1121 SMLoc AlignmentLoc = Lexer.getLoc();
1123 if (ParseAbsoluteExpression(Alignment))
1127 bool HasFillExpr = false;
1128 int64_t FillExpr = 0;
1129 int64_t MaxBytesToFill = 0;
1130 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1131 if (Lexer.isNot(AsmToken::Comma))
1132 return TokError("unexpected token in directive");
1135 // The fill expression can be omitted while specifying a maximum number of
1136 // alignment bytes, e.g:
1138 if (Lexer.isNot(AsmToken::Comma)) {
1140 if (ParseAbsoluteExpression(FillExpr))
1144 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1145 if (Lexer.isNot(AsmToken::Comma))
1146 return TokError("unexpected token in directive");
1149 MaxBytesLoc = Lexer.getLoc();
1150 if (ParseAbsoluteExpression(MaxBytesToFill))
1153 if (Lexer.isNot(AsmToken::EndOfStatement))
1154 return TokError("unexpected token in directive");
1161 // FIXME: Sometimes fill with nop.
1165 // Compute alignment in bytes.
1167 // FIXME: Diagnose overflow.
1168 if (Alignment >= 32) {
1169 Error(AlignmentLoc, "invalid alignment value");
1173 Alignment = 1ULL << Alignment;
1176 // Diagnose non-sensical max bytes to align.
1177 if (MaxBytesLoc.isValid()) {
1178 if (MaxBytesToFill < 1) {
1179 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1180 "many bytes, ignoring maximum bytes expression");
1184 if (MaxBytesToFill >= Alignment) {
1185 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1191 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1192 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1197 /// ParseDirectiveSymbolAttribute
1198 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1199 bool AsmParser::ParseDirectiveSymbolAttribute(MCStreamer::SymbolAttr Attr) {
1200 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1204 if (ParseIdentifier(Name))
1205 return TokError("expected identifier in directive");
1207 MCSymbol *Sym = CreateSymbol(Name);
1209 Out.EmitSymbolAttribute(Sym, Attr);
1211 if (Lexer.is(AsmToken::EndOfStatement))
1214 if (Lexer.isNot(AsmToken::Comma))
1215 return TokError("unexpected token in directive");
1224 /// ParseDirectiveDarwinSymbolDesc
1225 /// ::= .desc identifier , expression
1226 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1228 if (ParseIdentifier(Name))
1229 return TokError("expected identifier in directive");
1231 // Handle the identifier as the key symbol.
1232 MCSymbol *Sym = CreateSymbol(Name);
1234 if (Lexer.isNot(AsmToken::Comma))
1235 return TokError("unexpected token in '.desc' directive");
1238 SMLoc DescLoc = Lexer.getLoc();
1240 if (ParseAbsoluteExpression(DescValue))
1243 if (Lexer.isNot(AsmToken::EndOfStatement))
1244 return TokError("unexpected token in '.desc' directive");
1248 // Set the n_desc field of this Symbol to this DescValue
1249 Out.EmitSymbolDesc(Sym, DescValue);
1254 /// ParseDirectiveComm
1255 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1256 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1257 SMLoc IDLoc = Lexer.getLoc();
1259 if (ParseIdentifier(Name))
1260 return TokError("expected identifier in directive");
1262 // Handle the identifier as the key symbol.
1263 MCSymbol *Sym = CreateSymbol(Name);
1265 if (Lexer.isNot(AsmToken::Comma))
1266 return TokError("unexpected token in directive");
1270 SMLoc SizeLoc = Lexer.getLoc();
1271 if (ParseAbsoluteExpression(Size))
1274 int64_t Pow2Alignment = 0;
1275 SMLoc Pow2AlignmentLoc;
1276 if (Lexer.is(AsmToken::Comma)) {
1278 Pow2AlignmentLoc = Lexer.getLoc();
1279 if (ParseAbsoluteExpression(Pow2Alignment))
1283 if (Lexer.isNot(AsmToken::EndOfStatement))
1284 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1288 // NOTE: a size of zero for a .comm should create a undefined symbol
1289 // but a size of .lcomm creates a bss symbol of size zero.
1291 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1292 "be less than zero");
1294 // NOTE: The alignment in the directive is a power of 2 value, the assember
1295 // may internally end up wanting an alignment in bytes.
1296 // FIXME: Diagnose overflow.
1297 if (Pow2Alignment < 0)
1298 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1299 "alignment, can't be less than zero");
1301 if (!Sym->isUndefined())
1302 return Error(IDLoc, "invalid symbol redefinition");
1304 // '.lcomm' is equivalent to '.zerofill'.
1305 // Create the Symbol as a common or local common with Size and Pow2Alignment
1307 Out.EmitZerofill(getMachOSection("__DATA", "__bss",
1308 MCSectionMachO::S_ZEROFILL, 0,
1310 Sym, Size, 1 << Pow2Alignment);
1314 Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1318 /// ParseDirectiveDarwinZerofill
1319 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1320 /// , align_expression ]]
1321 bool AsmParser::ParseDirectiveDarwinZerofill() {
1322 // FIXME: Handle quoted names here.
1324 if (Lexer.isNot(AsmToken::Identifier))
1325 return TokError("expected segment name after '.zerofill' directive");
1326 StringRef Segment = Lexer.getTok().getString();
1329 if (Lexer.isNot(AsmToken::Comma))
1330 return TokError("unexpected token in directive");
1333 if (Lexer.isNot(AsmToken::Identifier))
1334 return TokError("expected section name after comma in '.zerofill' "
1336 StringRef Section = Lexer.getTok().getString();
1339 // If this is the end of the line all that was wanted was to create the
1340 // the section but with no symbol.
1341 if (Lexer.is(AsmToken::EndOfStatement)) {
1342 // Create the zerofill section but no symbol
1343 Out.EmitZerofill(getMachOSection(Segment, Section,
1344 MCSectionMachO::S_ZEROFILL, 0,
1349 if (Lexer.isNot(AsmToken::Comma))
1350 return TokError("unexpected token in directive");
1353 if (Lexer.isNot(AsmToken::Identifier))
1354 return TokError("expected identifier in directive");
1356 // handle the identifier as the key symbol.
1357 SMLoc IDLoc = Lexer.getLoc();
1358 MCSymbol *Sym = CreateSymbol(Lexer.getTok().getString());
1361 if (Lexer.isNot(AsmToken::Comma))
1362 return TokError("unexpected token in directive");
1366 SMLoc SizeLoc = Lexer.getLoc();
1367 if (ParseAbsoluteExpression(Size))
1370 int64_t Pow2Alignment = 0;
1371 SMLoc Pow2AlignmentLoc;
1372 if (Lexer.is(AsmToken::Comma)) {
1374 Pow2AlignmentLoc = Lexer.getLoc();
1375 if (ParseAbsoluteExpression(Pow2Alignment))
1379 if (Lexer.isNot(AsmToken::EndOfStatement))
1380 return TokError("unexpected token in '.zerofill' directive");
1385 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1388 // NOTE: The alignment in the directive is a power of 2 value, the assember
1389 // may internally end up wanting an alignment in bytes.
1390 // FIXME: Diagnose overflow.
1391 if (Pow2Alignment < 0)
1392 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1393 "can't be less than zero");
1395 if (!Sym->isUndefined())
1396 return Error(IDLoc, "invalid symbol redefinition");
1398 // Create the zerofill Symbol with Size and Pow2Alignment
1400 // FIXME: Arch specific.
1401 Out.EmitZerofill(getMachOSection(Segment, Section,
1402 MCSectionMachO::S_ZEROFILL, 0,
1404 Sym, Size, 1 << Pow2Alignment);
1409 /// ParseDirectiveDarwinSubsectionsViaSymbols
1410 /// ::= .subsections_via_symbols
1411 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1412 if (Lexer.isNot(AsmToken::EndOfStatement))
1413 return TokError("unexpected token in '.subsections_via_symbols' directive");
1417 Out.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1422 /// ParseDirectiveAbort
1423 /// ::= .abort [ "abort_string" ]
1424 bool AsmParser::ParseDirectiveAbort() {
1425 // FIXME: Use loc from directive.
1426 SMLoc Loc = Lexer.getLoc();
1429 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1430 if (Lexer.isNot(AsmToken::String))
1431 return TokError("expected string in '.abort' directive");
1433 Str = Lexer.getTok().getString();
1438 if (Lexer.isNot(AsmToken::EndOfStatement))
1439 return TokError("unexpected token in '.abort' directive");
1443 // FIXME: Handle here.
1445 Error(Loc, ".abort detected. Assembly stopping.");
1447 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1452 /// ParseDirectiveLsym
1453 /// ::= .lsym identifier , expression
1454 bool AsmParser::ParseDirectiveDarwinLsym() {
1456 if (ParseIdentifier(Name))
1457 return TokError("expected identifier in directive");
1459 // Handle the identifier as the key symbol.
1460 MCSymbol *Sym = CreateSymbol(Name);
1462 if (Lexer.isNot(AsmToken::Comma))
1463 return TokError("unexpected token in '.lsym' directive");
1466 const MCExpr *Value;
1467 SMLoc StartLoc = Lexer.getLoc();
1468 if (ParseExpression(Value))
1471 if (Lexer.isNot(AsmToken::EndOfStatement))
1472 return TokError("unexpected token in '.lsym' directive");
1476 // We don't currently support this directive.
1478 // FIXME: Diagnostic location!
1480 return TokError("directive '.lsym' is unsupported");
1483 /// ParseDirectiveInclude
1484 /// ::= .include "filename"
1485 bool AsmParser::ParseDirectiveInclude() {
1486 if (Lexer.isNot(AsmToken::String))
1487 return TokError("expected string in '.include' directive");
1489 std::string Filename = Lexer.getTok().getString();
1490 SMLoc IncludeLoc = Lexer.getLoc();
1493 if (Lexer.isNot(AsmToken::EndOfStatement))
1494 return TokError("unexpected token in '.include' directive");
1496 // Strip the quotes.
1497 Filename = Filename.substr(1, Filename.size()-2);
1499 // Attempt to switch the lexer to the included file before consuming the end
1500 // of statement to avoid losing it when we switch.
1501 if (Lexer.EnterIncludeFile(Filename)) {
1502 Lexer.PrintMessage(IncludeLoc,
1503 "Could not find include file '" + Filename + "'",
1511 /// ParseDirectiveDarwinDumpOrLoad
1512 /// ::= ( .dump | .load ) "filename"
1513 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1514 if (Lexer.isNot(AsmToken::String))
1515 return TokError("expected string in '.dump' or '.load' directive");
1519 if (Lexer.isNot(AsmToken::EndOfStatement))
1520 return TokError("unexpected token in '.dump' or '.load' directive");
1524 // FIXME: If/when .dump and .load are implemented they will be done in the
1525 // the assembly parser and not have any need for an MCStreamer API.
1527 Warning(IDLoc, "ignoring directive .dump for now");
1529 Warning(IDLoc, "ignoring directive .load for now");
1534 /// ParseDirectiveIf
1535 /// ::= .if expression
1536 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1537 // Consume the identifier that was the .if directive
1540 TheCondStack.push_back(TheCondState);
1541 TheCondState.TheCond = AsmCond::IfCond;
1542 if(TheCondState.Ignore) {
1543 EatToEndOfStatement();
1547 if (ParseAbsoluteExpression(ExprValue))
1550 if (Lexer.isNot(AsmToken::EndOfStatement))
1551 return TokError("unexpected token in '.if' directive");
1555 TheCondState.CondMet = ExprValue;
1556 TheCondState.Ignore = !TheCondState.CondMet;
1562 /// ParseDirectiveElseIf
1563 /// ::= .elseif expression
1564 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1565 if (TheCondState.TheCond != AsmCond::IfCond &&
1566 TheCondState.TheCond != AsmCond::ElseIfCond)
1567 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1569 TheCondState.TheCond = AsmCond::ElseIfCond;
1571 // Consume the identifier that was the .elseif directive
1574 bool LastIgnoreState = false;
1575 if (!TheCondStack.empty())
1576 LastIgnoreState = TheCondStack.back().Ignore;
1577 if (LastIgnoreState || TheCondState.CondMet) {
1578 TheCondState.Ignore = true;
1579 EatToEndOfStatement();
1583 if (ParseAbsoluteExpression(ExprValue))
1586 if (Lexer.isNot(AsmToken::EndOfStatement))
1587 return TokError("unexpected token in '.elseif' directive");
1590 TheCondState.CondMet = ExprValue;
1591 TheCondState.Ignore = !TheCondState.CondMet;
1597 /// ParseDirectiveElse
1599 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1600 // Consume the identifier that was the .else directive
1603 if (Lexer.isNot(AsmToken::EndOfStatement))
1604 return TokError("unexpected token in '.else' directive");
1608 if (TheCondState.TheCond != AsmCond::IfCond &&
1609 TheCondState.TheCond != AsmCond::ElseIfCond)
1610 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1612 TheCondState.TheCond = AsmCond::ElseCond;
1613 bool LastIgnoreState = false;
1614 if (!TheCondStack.empty())
1615 LastIgnoreState = TheCondStack.back().Ignore;
1616 if (LastIgnoreState || TheCondState.CondMet)
1617 TheCondState.Ignore = true;
1619 TheCondState.Ignore = false;
1624 /// ParseDirectiveEndIf
1626 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1627 // Consume the identifier that was the .endif directive
1630 if (Lexer.isNot(AsmToken::EndOfStatement))
1631 return TokError("unexpected token in '.endif' directive");
1635 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1636 TheCondStack.empty())
1637 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1639 if (!TheCondStack.empty()) {
1640 TheCondState = TheCondStack.back();
1641 TheCondStack.pop_back();
1647 /// ParseDirectiveFile
1648 /// ::= .file [number] string
1649 bool AsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1650 // FIXME: I'm not sure what this is.
1651 int64_t FileNumber = -1;
1652 if (Lexer.is(AsmToken::Integer)) {
1653 FileNumber = Lexer.getTok().getIntVal();
1657 return TokError("file number less than one");
1660 if (Lexer.isNot(AsmToken::String))
1661 return TokError("unexpected token in '.file' directive");
1663 StringRef ATTRIBUTE_UNUSED FileName = Lexer.getTok().getString();
1666 if (Lexer.isNot(AsmToken::EndOfStatement))
1667 return TokError("unexpected token in '.file' directive");
1669 // FIXME: Do something with the .file.
1674 /// ParseDirectiveLine
1675 /// ::= .line [number]
1676 bool AsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1677 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1678 if (Lexer.isNot(AsmToken::Integer))
1679 return TokError("unexpected token in '.line' directive");
1681 int64_t LineNumber = Lexer.getTok().getIntVal();
1685 // FIXME: Do something with the .line.
1688 if (Lexer.isNot(AsmToken::EndOfStatement))
1689 return TokError("unexpected token in '.file' directive");
1695 /// ParseDirectiveLoc
1696 /// ::= .loc number [number [number]]
1697 bool AsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1698 if (Lexer.isNot(AsmToken::Integer))
1699 return TokError("unexpected token in '.loc' directive");
1701 // FIXME: What are these fields?
1702 int64_t FileNumber = Lexer.getTok().getIntVal();
1704 // FIXME: Validate file.
1707 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1708 if (Lexer.isNot(AsmToken::Integer))
1709 return TokError("unexpected token in '.loc' directive");
1711 int64_t Param2 = Lexer.getTok().getIntVal();
1715 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1716 if (Lexer.isNot(AsmToken::Integer))
1717 return TokError("unexpected token in '.loc' directive");
1719 int64_t Param3 = Lexer.getTok().getIntVal();
1723 // FIXME: Do something with the .loc.
1727 if (Lexer.isNot(AsmToken::EndOfStatement))
1728 return TokError("unexpected token in '.file' directive");