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"
33 enum { DEFAULT_ADDRSPACE = 0 };
35 // Mach-O section uniquing.
37 // FIXME: Figure out where this should live, it should be shared by
38 // TargetLoweringObjectFile.
39 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
41 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
42 const MCAsmInfo &_MAI)
43 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM), TargetParser(0),
44 CurBuffer(0), SectionUniquingMap(0) {
45 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
47 // Debugging directives.
48 AddDirectiveHandler(".file", &AsmParser::ParseDirectiveFile);
49 AddDirectiveHandler(".line", &AsmParser::ParseDirectiveLine);
50 AddDirectiveHandler(".loc", &AsmParser::ParseDirectiveLoc);
55 AsmParser::~AsmParser() {
56 // If we have the MachO uniquing map, free it.
57 delete (MachOUniqueMapTy*)SectionUniquingMap;
60 const MCSection *AsmParser::getMachOSection(const StringRef &Segment,
61 const StringRef &Section,
62 unsigned TypeAndAttributes,
64 SectionKind Kind) const {
65 // We unique sections by their segment/section pair. The returned section
66 // may not have the same flags as the requested section, if so this should be
67 // diagnosed by the client as an error.
69 // Create the map if it doesn't already exist.
70 if (SectionUniquingMap == 0)
71 SectionUniquingMap = new MachOUniqueMapTy();
72 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)SectionUniquingMap;
74 // Form the name to look up.
80 // Do the lookup, if we have a hit, return it.
81 const MCSectionMachO *&Entry = Map[Name.str()];
83 // FIXME: This should validate the type and attributes.
84 if (Entry) return Entry;
86 // Otherwise, return a new section.
87 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
88 Reserved2, Kind, Ctx);
91 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
92 PrintMessage(L, Msg.str(), "warning");
95 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
96 PrintMessage(L, Msg.str(), "error");
100 bool AsmParser::TokError(const char *Msg) {
101 PrintMessage(Lexer.getLoc(), Msg, "error");
105 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
106 const char *Type) const {
107 SrcMgr.PrintMessage(Loc, Msg, Type);
110 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
111 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
117 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
122 const AsmToken &AsmParser::Lex() {
123 const AsmToken *tok = &Lexer.Lex();
125 if (tok->is(AsmToken::Eof)) {
126 // If this is the end of an included file, pop the parent file off the
128 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
129 if (ParentIncludeLoc != SMLoc()) {
130 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
131 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer),
132 ParentIncludeLoc.getPointer());
137 if (tok->is(AsmToken::Error))
138 PrintMessage(Lexer.getErrLoc(), Lexer.getErr(), "error");
143 bool AsmParser::Run() {
144 // Create the initial section.
146 // FIXME: Support -n.
147 // FIXME: Target hook & command line option for initial section.
148 Out.SwitchSection(getMachOSection("__TEXT", "__text",
149 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
156 bool HadError = false;
158 AsmCond StartingCondState = TheCondState;
160 // While we have input, parse each statement.
161 while (Lexer.isNot(AsmToken::Eof)) {
162 // Handle conditional assembly here before calling ParseStatement()
163 if (Lexer.getKind() == AsmToken::Identifier) {
164 // If we have an identifier, handle it as the key symbol.
165 AsmToken ID = getTok();
166 SMLoc IDLoc = ID.getLoc();
167 StringRef IDVal = ID.getString();
169 if (IDVal == ".if" ||
170 IDVal == ".elseif" ||
173 if (!ParseConditionalAssemblyDirectives(IDVal, IDLoc))
176 EatToEndOfStatement();
180 if (TheCondState.Ignore) {
181 EatToEndOfStatement();
185 if (!ParseStatement()) continue;
187 // We had an error, remember it and recover by skipping to the next line.
189 EatToEndOfStatement();
192 if (TheCondState.TheCond != StartingCondState.TheCond ||
193 TheCondState.Ignore != StartingCondState.Ignore)
194 return TokError("unmatched .ifs or .elses");
202 /// ParseConditionalAssemblyDirectives - parse the conditional assembly
204 bool AsmParser::ParseConditionalAssemblyDirectives(StringRef Directive,
205 SMLoc DirectiveLoc) {
206 if (Directive == ".if")
207 return ParseDirectiveIf(DirectiveLoc);
208 if (Directive == ".elseif")
209 return ParseDirectiveElseIf(DirectiveLoc);
210 if (Directive == ".else")
211 return ParseDirectiveElse(DirectiveLoc);
212 if (Directive == ".endif")
213 return ParseDirectiveEndIf(DirectiveLoc);
217 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
218 void AsmParser::EatToEndOfStatement() {
219 while (Lexer.isNot(AsmToken::EndOfStatement) &&
220 Lexer.isNot(AsmToken::Eof))
224 if (Lexer.is(AsmToken::EndOfStatement))
229 /// ParseParenExpr - Parse a paren expression and return it.
230 /// NOTE: This assumes the leading '(' has already been consumed.
232 /// parenexpr ::= expr)
234 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
235 if (ParseExpression(Res)) return true;
236 if (Lexer.isNot(AsmToken::RParen))
237 return TokError("expected ')' in parentheses expression");
238 EndLoc = Lexer.getLoc();
243 MCSymbol *AsmParser::CreateSymbol(StringRef Name) {
244 if (MCSymbol *S = Ctx.LookupSymbol(Name))
247 // If the label starts with L it is an assembler temporary label.
248 if (Name.startswith("L"))
249 return Ctx.CreateTemporarySymbol(Name);
251 return Ctx.CreateSymbol(Name);
254 /// ParsePrimaryExpr - Parse a primary expression and return it.
255 /// primaryexpr ::= (parenexpr
256 /// primaryexpr ::= symbol
257 /// primaryexpr ::= number
258 /// primaryexpr ::= ~,+,- primaryexpr
259 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
260 switch (Lexer.getKind()) {
262 return TokError("unknown token in expression");
263 case AsmToken::Exclaim:
264 Lex(); // Eat the operator.
265 if (ParsePrimaryExpr(Res, EndLoc))
267 Res = MCUnaryExpr::CreateLNot(Res, getContext());
269 case AsmToken::String:
270 case AsmToken::Identifier: {
271 // This is a symbol reference.
272 MCSymbol *Sym = CreateSymbol(getTok().getIdentifier());
273 EndLoc = Lexer.getLoc();
274 Lex(); // Eat identifier.
276 // If this is an absolute variable reference, substitute it now to preserve
277 // semantics in the face of reassignment.
278 if (Sym->getValue() && isa<MCConstantExpr>(Sym->getValue())) {
279 Res = Sym->getValue();
283 // Otherwise create a symbol ref.
284 Res = MCSymbolRefExpr::Create(Sym, getContext());
287 case AsmToken::Integer:
288 Res = MCConstantExpr::Create(getTok().getIntVal(), getContext());
289 EndLoc = Lexer.getLoc();
292 case AsmToken::LParen:
293 Lex(); // Eat the '('.
294 return ParseParenExpr(Res, EndLoc);
295 case AsmToken::Minus:
296 Lex(); // Eat the operator.
297 if (ParsePrimaryExpr(Res, EndLoc))
299 Res = MCUnaryExpr::CreateMinus(Res, getContext());
302 Lex(); // Eat the operator.
303 if (ParsePrimaryExpr(Res, EndLoc))
305 Res = MCUnaryExpr::CreatePlus(Res, getContext());
307 case AsmToken::Tilde:
308 Lex(); // Eat the operator.
309 if (ParsePrimaryExpr(Res, EndLoc))
311 Res = MCUnaryExpr::CreateNot(Res, getContext());
316 bool AsmParser::ParseExpression(const MCExpr *&Res) {
318 return ParseExpression(Res, EndLoc);
321 /// ParseExpression - Parse an expression and return it.
323 /// expr ::= expr +,- expr -> lowest.
324 /// expr ::= expr |,^,&,! expr -> middle.
325 /// expr ::= expr *,/,%,<<,>> expr -> highest.
326 /// expr ::= primaryexpr
328 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
330 return ParsePrimaryExpr(Res, EndLoc) ||
331 ParseBinOpRHS(1, Res, EndLoc);
334 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
335 if (ParseParenExpr(Res, EndLoc))
341 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
344 SMLoc StartLoc = Lexer.getLoc();
345 if (ParseExpression(Expr))
348 if (!Expr->EvaluateAsAbsolute(Res))
349 return Error(StartLoc, "expected absolute expression");
354 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
355 MCBinaryExpr::Opcode &Kind) {
358 return 0; // not a binop.
360 // Lowest Precedence: &&, ||
361 case AsmToken::AmpAmp:
362 Kind = MCBinaryExpr::LAnd;
364 case AsmToken::PipePipe:
365 Kind = MCBinaryExpr::LOr;
368 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
370 Kind = MCBinaryExpr::Add;
372 case AsmToken::Minus:
373 Kind = MCBinaryExpr::Sub;
375 case AsmToken::EqualEqual:
376 Kind = MCBinaryExpr::EQ;
378 case AsmToken::ExclaimEqual:
379 case AsmToken::LessGreater:
380 Kind = MCBinaryExpr::NE;
383 Kind = MCBinaryExpr::LT;
385 case AsmToken::LessEqual:
386 Kind = MCBinaryExpr::LTE;
388 case AsmToken::Greater:
389 Kind = MCBinaryExpr::GT;
391 case AsmToken::GreaterEqual:
392 Kind = MCBinaryExpr::GTE;
395 // Intermediate Precedence: |, &, ^
397 // FIXME: gas seems to support '!' as an infix operator?
399 Kind = MCBinaryExpr::Or;
401 case AsmToken::Caret:
402 Kind = MCBinaryExpr::Xor;
405 Kind = MCBinaryExpr::And;
408 // Highest Precedence: *, /, %, <<, >>
410 Kind = MCBinaryExpr::Mul;
412 case AsmToken::Slash:
413 Kind = MCBinaryExpr::Div;
415 case AsmToken::Percent:
416 Kind = MCBinaryExpr::Mod;
418 case AsmToken::LessLess:
419 Kind = MCBinaryExpr::Shl;
421 case AsmToken::GreaterGreater:
422 Kind = MCBinaryExpr::Shr;
428 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
429 /// Res contains the LHS of the expression on input.
430 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
433 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
434 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
436 // If the next token is lower precedence than we are allowed to eat, return
437 // successfully with what we ate already.
438 if (TokPrec < Precedence)
443 // Eat the next primary expression.
445 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
447 // If BinOp binds less tightly with RHS than the operator after RHS, let
448 // the pending operator take RHS as its LHS.
449 MCBinaryExpr::Opcode Dummy;
450 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
451 if (TokPrec < NextTokPrec) {
452 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
455 // Merge LHS and RHS according to operator.
456 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
464 /// ::= EndOfStatement
465 /// ::= Label* Directive ...Operands... EndOfStatement
466 /// ::= Label* Identifier OperandList* EndOfStatement
467 bool AsmParser::ParseStatement() {
468 if (Lexer.is(AsmToken::EndOfStatement)) {
473 // Statements always start with an identifier.
474 AsmToken ID = getTok();
475 SMLoc IDLoc = ID.getLoc();
477 if (ParseIdentifier(IDVal))
478 return TokError("unexpected token at start of statement");
480 // FIXME: Recurse on local labels?
482 // See what kind of statement we have.
483 switch (Lexer.getKind()) {
484 case AsmToken::Colon: {
485 // identifier ':' -> Label.
488 // Diagnose attempt to use a variable as a label.
490 // FIXME: Diagnostics. Note the location of the definition as a label.
491 // FIXME: This doesn't diagnose assignment to a symbol which has been
492 // implicitly marked as external.
493 MCSymbol *Sym = CreateSymbol(IDVal);
494 if (!Sym->isUndefined())
495 return Error(IDLoc, "invalid symbol redefinition");
500 return ParseStatement();
503 case AsmToken::Equal:
504 // identifier '=' ... -> assignment statement
507 return ParseAssignment(IDVal);
509 default: // Normal instruction or directive.
513 // Otherwise, we have a normal instruction or directive.
514 if (IDVal[0] == '.') {
515 // FIXME: This should be driven based on a hash lookup and callback.
516 if (IDVal == ".section")
517 return ParseDirectiveDarwinSection();
518 if (IDVal == ".text")
519 // FIXME: This changes behavior based on the -static flag to the
521 return ParseDirectiveSectionSwitch("__TEXT", "__text",
522 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
523 if (IDVal == ".const")
524 return ParseDirectiveSectionSwitch("__TEXT", "__const");
525 if (IDVal == ".static_const")
526 return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
527 if (IDVal == ".cstring")
528 return ParseDirectiveSectionSwitch("__TEXT","__cstring",
529 MCSectionMachO::S_CSTRING_LITERALS);
530 if (IDVal == ".literal4")
531 return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
532 MCSectionMachO::S_4BYTE_LITERALS,
534 if (IDVal == ".literal8")
535 return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
536 MCSectionMachO::S_8BYTE_LITERALS,
538 if (IDVal == ".literal16")
539 return ParseDirectiveSectionSwitch("__TEXT","__literal16",
540 MCSectionMachO::S_16BYTE_LITERALS,
542 if (IDVal == ".constructor")
543 return ParseDirectiveSectionSwitch("__TEXT","__constructor");
544 if (IDVal == ".destructor")
545 return ParseDirectiveSectionSwitch("__TEXT","__destructor");
546 if (IDVal == ".fvmlib_init0")
547 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
548 if (IDVal == ".fvmlib_init1")
549 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
551 // FIXME: The assembler manual claims that this has the self modify code
552 // flag, at least on x86-32, but that does not appear to be correct.
553 if (IDVal == ".symbol_stub")
554 return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
555 MCSectionMachO::S_SYMBOL_STUBS |
556 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
557 // FIXME: Different on PPC and ARM.
559 // FIXME: PowerPC only?
560 if (IDVal == ".picsymbol_stub")
561 return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
562 MCSectionMachO::S_SYMBOL_STUBS |
563 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
565 if (IDVal == ".data")
566 return ParseDirectiveSectionSwitch("__DATA", "__data");
567 if (IDVal == ".static_data")
568 return ParseDirectiveSectionSwitch("__DATA", "__static_data");
570 // FIXME: The section names of these two are misspelled in the assembler
572 if (IDVal == ".non_lazy_symbol_pointer")
573 return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
574 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
576 if (IDVal == ".lazy_symbol_pointer")
577 return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
578 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
581 if (IDVal == ".dyld")
582 return ParseDirectiveSectionSwitch("__DATA", "__dyld");
583 if (IDVal == ".mod_init_func")
584 return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
585 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
587 if (IDVal == ".mod_term_func")
588 return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
589 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
591 if (IDVal == ".const_data")
592 return ParseDirectiveSectionSwitch("__DATA", "__const");
595 if (IDVal == ".objc_class")
596 return ParseDirectiveSectionSwitch("__OBJC", "__class",
597 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
598 if (IDVal == ".objc_meta_class")
599 return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
600 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
601 if (IDVal == ".objc_cat_cls_meth")
602 return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
603 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
604 if (IDVal == ".objc_cat_inst_meth")
605 return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
606 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
607 if (IDVal == ".objc_protocol")
608 return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
609 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
610 if (IDVal == ".objc_string_object")
611 return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
612 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
613 if (IDVal == ".objc_cls_meth")
614 return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
615 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
616 if (IDVal == ".objc_inst_meth")
617 return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
618 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
619 if (IDVal == ".objc_cls_refs")
620 return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
621 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
622 MCSectionMachO::S_LITERAL_POINTERS,
624 if (IDVal == ".objc_message_refs")
625 return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
626 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
627 MCSectionMachO::S_LITERAL_POINTERS,
629 if (IDVal == ".objc_symbols")
630 return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
631 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
632 if (IDVal == ".objc_category")
633 return ParseDirectiveSectionSwitch("__OBJC", "__category",
634 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
635 if (IDVal == ".objc_class_vars")
636 return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
637 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
638 if (IDVal == ".objc_instance_vars")
639 return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
640 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
641 if (IDVal == ".objc_module_info")
642 return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
643 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
644 if (IDVal == ".objc_class_names")
645 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
646 MCSectionMachO::S_CSTRING_LITERALS);
647 if (IDVal == ".objc_meth_var_types")
648 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
649 MCSectionMachO::S_CSTRING_LITERALS);
650 if (IDVal == ".objc_meth_var_names")
651 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
652 MCSectionMachO::S_CSTRING_LITERALS);
653 if (IDVal == ".objc_selector_strs")
654 return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
655 MCSectionMachO::S_CSTRING_LITERALS);
657 // Assembler features
659 return ParseDirectiveSet();
663 if (IDVal == ".ascii")
664 return ParseDirectiveAscii(false);
665 if (IDVal == ".asciz")
666 return ParseDirectiveAscii(true);
668 if (IDVal == ".byte")
669 return ParseDirectiveValue(1);
670 if (IDVal == ".short")
671 return ParseDirectiveValue(2);
672 if (IDVal == ".long")
673 return ParseDirectiveValue(4);
674 if (IDVal == ".quad")
675 return ParseDirectiveValue(8);
677 // FIXME: Target hooks for IsPow2.
678 if (IDVal == ".align")
679 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
680 if (IDVal == ".align32")
681 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
682 if (IDVal == ".balign")
683 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
684 if (IDVal == ".balignw")
685 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
686 if (IDVal == ".balignl")
687 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
688 if (IDVal == ".p2align")
689 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
690 if (IDVal == ".p2alignw")
691 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
692 if (IDVal == ".p2alignl")
693 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
696 return ParseDirectiveOrg();
698 if (IDVal == ".fill")
699 return ParseDirectiveFill();
700 if (IDVal == ".space")
701 return ParseDirectiveSpace();
703 // Symbol attribute directives
705 if (IDVal == ".globl" || IDVal == ".global")
706 return ParseDirectiveSymbolAttribute(MCStreamer::Global);
707 if (IDVal == ".hidden")
708 return ParseDirectiveSymbolAttribute(MCStreamer::Hidden);
709 if (IDVal == ".indirect_symbol")
710 return ParseDirectiveSymbolAttribute(MCStreamer::IndirectSymbol);
711 if (IDVal == ".internal")
712 return ParseDirectiveSymbolAttribute(MCStreamer::Internal);
713 if (IDVal == ".lazy_reference")
714 return ParseDirectiveSymbolAttribute(MCStreamer::LazyReference);
715 if (IDVal == ".no_dead_strip")
716 return ParseDirectiveSymbolAttribute(MCStreamer::NoDeadStrip);
717 if (IDVal == ".private_extern")
718 return ParseDirectiveSymbolAttribute(MCStreamer::PrivateExtern);
719 if (IDVal == ".protected")
720 return ParseDirectiveSymbolAttribute(MCStreamer::Protected);
721 if (IDVal == ".reference")
722 return ParseDirectiveSymbolAttribute(MCStreamer::Reference);
723 if (IDVal == ".weak")
724 return ParseDirectiveSymbolAttribute(MCStreamer::Weak);
725 if (IDVal == ".weak_definition")
726 return ParseDirectiveSymbolAttribute(MCStreamer::WeakDefinition);
727 if (IDVal == ".weak_reference")
728 return ParseDirectiveSymbolAttribute(MCStreamer::WeakReference);
730 if (IDVal == ".comm")
731 return ParseDirectiveComm(/*IsLocal=*/false);
732 if (IDVal == ".lcomm")
733 return ParseDirectiveComm(/*IsLocal=*/true);
734 if (IDVal == ".zerofill")
735 return ParseDirectiveDarwinZerofill();
736 if (IDVal == ".desc")
737 return ParseDirectiveDarwinSymbolDesc();
738 if (IDVal == ".lsym")
739 return ParseDirectiveDarwinLsym();
741 if (IDVal == ".subsections_via_symbols")
742 return ParseDirectiveDarwinSubsectionsViaSymbols();
743 if (IDVal == ".abort")
744 return ParseDirectiveAbort();
745 if (IDVal == ".include")
746 return ParseDirectiveInclude();
747 if (IDVal == ".dump")
748 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
749 if (IDVal == ".load")
750 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
752 // Look up the handler in the handler table,
753 bool(AsmParser::*Handler)(StringRef, SMLoc) = DirectiveMap[IDVal];
755 return (this->*Handler)(IDVal, IDLoc);
757 // Target hook for parsing target specific directives.
758 if (!getTargetParser().ParseDirective(ID))
761 Warning(IDLoc, "ignoring directive for now");
762 EatToEndOfStatement();
767 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
768 if (getTargetParser().ParseInstruction(IDVal, IDLoc, ParsedOperands))
769 // FIXME: Leaking ParsedOperands on failure.
772 if (Lexer.isNot(AsmToken::EndOfStatement))
773 // FIXME: Leaking ParsedOperands on failure.
774 return TokError("unexpected token in argument list");
776 // Eat the end of statement marker.
782 bool MatchFail = getTargetParser().MatchInstruction(ParsedOperands, Inst);
784 // Free any parsed operands.
785 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
786 delete ParsedOperands[i];
789 // FIXME: We should give nicer diagnostics about the exact failure.
790 Error(IDLoc, "unrecognized instruction");
794 // Instruction is good, process it.
795 Out.EmitInstruction(Inst);
797 // Skip to end of line for now.
801 bool AsmParser::ParseAssignment(const StringRef &Name) {
802 // FIXME: Use better location, we should use proper tokens.
803 SMLoc EqualLoc = Lexer.getLoc();
806 SMLoc StartLoc = Lexer.getLoc();
807 if (ParseExpression(Value))
810 if (Lexer.isNot(AsmToken::EndOfStatement))
811 return TokError("unexpected token in assignment");
813 // Eat the end of statement marker.
816 // Validate that the LHS is allowed to be a variable (either it has not been
817 // used as a symbol, or it is an absolute symbol).
818 MCSymbol *Sym = getContext().LookupSymbol(Name);
820 // Diagnose assignment to a label.
822 // FIXME: Diagnostics. Note the location of the definition as a label.
823 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
824 if (!Sym->isUndefined() && !Sym->isAbsolute())
825 return Error(EqualLoc, "redefinition of '" + Name + "'");
826 else if (!Sym->isVariable())
827 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
828 else if (!isa<MCConstantExpr>(Sym->getValue()))
829 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
832 Sym = CreateSymbol(Name);
834 // FIXME: Handle '.'.
836 // Do the assignment.
837 Out.EmitAssignment(Sym, Value);
845 bool AsmParser::ParseIdentifier(StringRef &Res) {
846 if (Lexer.isNot(AsmToken::Identifier) &&
847 Lexer.isNot(AsmToken::String))
850 Res = getTok().getIdentifier();
852 Lex(); // Consume the identifier token.
857 /// ParseDirectiveSet:
858 /// ::= .set identifier ',' expression
859 bool AsmParser::ParseDirectiveSet() {
862 if (ParseIdentifier(Name))
863 return TokError("expected identifier after '.set' directive");
865 if (Lexer.isNot(AsmToken::Comma))
866 return TokError("unexpected token in '.set'");
869 return ParseAssignment(Name);
872 /// ParseDirectiveSection:
873 /// ::= .section identifier (',' identifier)*
874 /// FIXME: This should actually parse out the segment, section, attributes and
875 /// sizeof_stub fields.
876 bool AsmParser::ParseDirectiveDarwinSection() {
877 SMLoc Loc = Lexer.getLoc();
879 StringRef SectionName;
880 if (ParseIdentifier(SectionName))
881 return Error(Loc, "expected identifier after '.section' directive");
883 // Verify there is a following comma.
884 if (!Lexer.is(AsmToken::Comma))
885 return TokError("unexpected token in '.section' directive");
887 std::string SectionSpec = SectionName;
890 // Add all the tokens until the end of the line, ParseSectionSpecifier will
892 StringRef EOL = Lexer.LexUntilEndOfStatement();
893 SectionSpec.append(EOL.begin(), EOL.end());
896 if (Lexer.isNot(AsmToken::EndOfStatement))
897 return TokError("unexpected token in '.section' directive");
901 StringRef Segment, Section;
902 unsigned TAA, StubSize;
903 std::string ErrorStr =
904 MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
907 if (!ErrorStr.empty())
908 return Error(Loc, ErrorStr.c_str());
910 // FIXME: Arch specific.
911 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
916 /// ParseDirectiveSectionSwitch -
917 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
919 unsigned TAA, unsigned Align,
921 if (Lexer.isNot(AsmToken::EndOfStatement))
922 return TokError("unexpected token in section switching directive");
925 // FIXME: Arch specific.
926 Out.SwitchSection(getMachOSection(Segment, Section, TAA, StubSize,
929 // Set the implicit alignment, if any.
931 // FIXME: This isn't really what 'as' does; I think it just uses the implicit
932 // alignment on the section (e.g., if one manually inserts bytes into the
933 // section, then just issueing the section switch directive will not realign
934 // the section. However, this is arguably more reasonable behavior, and there
935 // is no good reason for someone to intentionally emit incorrectly sized
936 // values into the implicitly aligned sections.
938 Out.EmitValueToAlignment(Align, 0, 1, 0);
943 bool AsmParser::ParseEscapedString(std::string &Data) {
944 assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
947 StringRef Str = getTok().getStringContents();
948 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
949 if (Str[i] != '\\') {
954 // Recognize escaped characters. Note that this escape semantics currently
955 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
958 return TokError("unexpected backslash at end of string");
960 // Recognize octal sequences.
961 if ((unsigned) (Str[i] - '0') <= 7) {
962 // Consume up to three octal characters.
963 unsigned Value = Str[i] - '0';
965 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
967 Value = Value * 8 + (Str[i] - '0');
969 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
971 Value = Value * 8 + (Str[i] - '0');
976 return TokError("invalid octal escape sequence (out of range)");
978 Data += (unsigned char) Value;
982 // Otherwise recognize individual escapes.
985 // Just reject invalid escape sequences for now.
986 return TokError("invalid escape sequence (unrecognized character)");
988 case 'b': Data += '\b'; break;
989 case 'f': Data += '\f'; break;
990 case 'n': Data += '\n'; break;
991 case 'r': Data += '\r'; break;
992 case 't': Data += '\t'; break;
993 case '"': Data += '"'; break;
994 case '\\': Data += '\\'; break;
1001 /// ParseDirectiveAscii:
1002 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1003 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1004 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1006 if (Lexer.isNot(AsmToken::String))
1007 return TokError("expected string in '.ascii' or '.asciz' directive");
1010 if (ParseEscapedString(Data))
1013 Out.EmitBytes(Data, DEFAULT_ADDRSPACE);
1015 Out.EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1019 if (Lexer.is(AsmToken::EndOfStatement))
1022 if (Lexer.isNot(AsmToken::Comma))
1023 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1032 /// ParseDirectiveValue
1033 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1034 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1035 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1037 const MCExpr *Value;
1038 SMLoc ATTRIBUTE_UNUSED StartLoc = Lexer.getLoc();
1039 if (ParseExpression(Value))
1042 Out.EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1044 if (Lexer.is(AsmToken::EndOfStatement))
1047 // FIXME: Improve diagnostic.
1048 if (Lexer.isNot(AsmToken::Comma))
1049 return TokError("unexpected token in directive");
1058 /// ParseDirectiveSpace
1059 /// ::= .space expression [ , expression ]
1060 bool AsmParser::ParseDirectiveSpace() {
1062 if (ParseAbsoluteExpression(NumBytes))
1065 int64_t FillExpr = 0;
1066 bool HasFillExpr = false;
1067 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1068 if (Lexer.isNot(AsmToken::Comma))
1069 return TokError("unexpected token in '.space' directive");
1072 if (ParseAbsoluteExpression(FillExpr))
1077 if (Lexer.isNot(AsmToken::EndOfStatement))
1078 return TokError("unexpected token in '.space' directive");
1084 return TokError("invalid number of bytes in '.space' directive");
1086 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1087 Out.EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1092 /// ParseDirectiveFill
1093 /// ::= .fill expression , expression , expression
1094 bool AsmParser::ParseDirectiveFill() {
1096 if (ParseAbsoluteExpression(NumValues))
1099 if (Lexer.isNot(AsmToken::Comma))
1100 return TokError("unexpected token in '.fill' directive");
1104 if (ParseAbsoluteExpression(FillSize))
1107 if (Lexer.isNot(AsmToken::Comma))
1108 return TokError("unexpected token in '.fill' directive");
1112 if (ParseAbsoluteExpression(FillExpr))
1115 if (Lexer.isNot(AsmToken::EndOfStatement))
1116 return TokError("unexpected token in '.fill' directive");
1120 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1121 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1123 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1124 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), FillSize,
1130 /// ParseDirectiveOrg
1131 /// ::= .org expression [ , expression ]
1132 bool AsmParser::ParseDirectiveOrg() {
1133 const MCExpr *Offset;
1134 SMLoc StartLoc = Lexer.getLoc();
1135 if (ParseExpression(Offset))
1138 // Parse optional fill expression.
1139 int64_t FillExpr = 0;
1140 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1141 if (Lexer.isNot(AsmToken::Comma))
1142 return TokError("unexpected token in '.org' directive");
1145 if (ParseAbsoluteExpression(FillExpr))
1148 if (Lexer.isNot(AsmToken::EndOfStatement))
1149 return TokError("unexpected token in '.org' directive");
1154 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1155 // has to be relative to the current section.
1156 Out.EmitValueToOffset(Offset, FillExpr);
1161 /// ParseDirectiveAlign
1162 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1163 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1164 SMLoc AlignmentLoc = Lexer.getLoc();
1166 if (ParseAbsoluteExpression(Alignment))
1170 bool HasFillExpr = false;
1171 int64_t FillExpr = 0;
1172 int64_t MaxBytesToFill = 0;
1173 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1174 if (Lexer.isNot(AsmToken::Comma))
1175 return TokError("unexpected token in directive");
1178 // The fill expression can be omitted while specifying a maximum number of
1179 // alignment bytes, e.g:
1181 if (Lexer.isNot(AsmToken::Comma)) {
1183 if (ParseAbsoluteExpression(FillExpr))
1187 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1188 if (Lexer.isNot(AsmToken::Comma))
1189 return TokError("unexpected token in directive");
1192 MaxBytesLoc = Lexer.getLoc();
1193 if (ParseAbsoluteExpression(MaxBytesToFill))
1196 if (Lexer.isNot(AsmToken::EndOfStatement))
1197 return TokError("unexpected token in directive");
1204 // FIXME: Sometimes fill with nop.
1208 // Compute alignment in bytes.
1210 // FIXME: Diagnose overflow.
1211 if (Alignment >= 32) {
1212 Error(AlignmentLoc, "invalid alignment value");
1216 Alignment = 1ULL << Alignment;
1219 // Diagnose non-sensical max bytes to align.
1220 if (MaxBytesLoc.isValid()) {
1221 if (MaxBytesToFill < 1) {
1222 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1223 "many bytes, ignoring maximum bytes expression");
1227 if (MaxBytesToFill >= Alignment) {
1228 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1234 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1235 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1240 /// ParseDirectiveSymbolAttribute
1241 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1242 bool AsmParser::ParseDirectiveSymbolAttribute(MCStreamer::SymbolAttr Attr) {
1243 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1247 if (ParseIdentifier(Name))
1248 return TokError("expected identifier in directive");
1250 MCSymbol *Sym = CreateSymbol(Name);
1252 Out.EmitSymbolAttribute(Sym, Attr);
1254 if (Lexer.is(AsmToken::EndOfStatement))
1257 if (Lexer.isNot(AsmToken::Comma))
1258 return TokError("unexpected token in directive");
1267 /// ParseDirectiveDarwinSymbolDesc
1268 /// ::= .desc identifier , expression
1269 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1271 if (ParseIdentifier(Name))
1272 return TokError("expected identifier in directive");
1274 // Handle the identifier as the key symbol.
1275 MCSymbol *Sym = CreateSymbol(Name);
1277 if (Lexer.isNot(AsmToken::Comma))
1278 return TokError("unexpected token in '.desc' directive");
1281 SMLoc DescLoc = Lexer.getLoc();
1283 if (ParseAbsoluteExpression(DescValue))
1286 if (Lexer.isNot(AsmToken::EndOfStatement))
1287 return TokError("unexpected token in '.desc' directive");
1291 // Set the n_desc field of this Symbol to this DescValue
1292 Out.EmitSymbolDesc(Sym, DescValue);
1297 /// ParseDirectiveComm
1298 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1299 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1300 SMLoc IDLoc = Lexer.getLoc();
1302 if (ParseIdentifier(Name))
1303 return TokError("expected identifier in directive");
1305 // Handle the identifier as the key symbol.
1306 MCSymbol *Sym = CreateSymbol(Name);
1308 if (Lexer.isNot(AsmToken::Comma))
1309 return TokError("unexpected token in directive");
1313 SMLoc SizeLoc = Lexer.getLoc();
1314 if (ParseAbsoluteExpression(Size))
1317 int64_t Pow2Alignment = 0;
1318 SMLoc Pow2AlignmentLoc;
1319 if (Lexer.is(AsmToken::Comma)) {
1321 Pow2AlignmentLoc = Lexer.getLoc();
1322 if (ParseAbsoluteExpression(Pow2Alignment))
1325 // If this target takes alignments in bytes (not log) validate and convert.
1326 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1327 if (!isPowerOf2_64(Pow2Alignment))
1328 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1329 Pow2Alignment = Log2_64(Pow2Alignment);
1333 if (Lexer.isNot(AsmToken::EndOfStatement))
1334 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1338 // NOTE: a size of zero for a .comm should create a undefined symbol
1339 // but a size of .lcomm creates a bss symbol of size zero.
1341 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1342 "be less than zero");
1344 // NOTE: The alignment in the directive is a power of 2 value, the assember
1345 // may internally end up wanting an alignment in bytes.
1346 // FIXME: Diagnose overflow.
1347 if (Pow2Alignment < 0)
1348 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1349 "alignment, can't be less than zero");
1351 if (!Sym->isUndefined())
1352 return Error(IDLoc, "invalid symbol redefinition");
1354 // '.lcomm' is equivalent to '.zerofill'.
1355 // Create the Symbol as a common or local common with Size and Pow2Alignment
1357 Out.EmitZerofill(getMachOSection("__DATA", "__bss",
1358 MCSectionMachO::S_ZEROFILL, 0,
1360 Sym, Size, 1 << Pow2Alignment);
1364 Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1368 /// ParseDirectiveDarwinZerofill
1369 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1370 /// , align_expression ]]
1371 bool AsmParser::ParseDirectiveDarwinZerofill() {
1372 // FIXME: Handle quoted names here.
1374 if (Lexer.isNot(AsmToken::Identifier))
1375 return TokError("expected segment name after '.zerofill' directive");
1376 StringRef Segment = getTok().getString();
1379 if (Lexer.isNot(AsmToken::Comma))
1380 return TokError("unexpected token in directive");
1383 if (Lexer.isNot(AsmToken::Identifier))
1384 return TokError("expected section name after comma in '.zerofill' "
1386 StringRef Section = getTok().getString();
1389 // If this is the end of the line all that was wanted was to create the
1390 // the section but with no symbol.
1391 if (Lexer.is(AsmToken::EndOfStatement)) {
1392 // Create the zerofill section but no symbol
1393 Out.EmitZerofill(getMachOSection(Segment, Section,
1394 MCSectionMachO::S_ZEROFILL, 0,
1399 if (Lexer.isNot(AsmToken::Comma))
1400 return TokError("unexpected token in directive");
1403 if (Lexer.isNot(AsmToken::Identifier))
1404 return TokError("expected identifier in directive");
1406 // handle the identifier as the key symbol.
1407 SMLoc IDLoc = Lexer.getLoc();
1408 MCSymbol *Sym = CreateSymbol(getTok().getString());
1411 if (Lexer.isNot(AsmToken::Comma))
1412 return TokError("unexpected token in directive");
1416 SMLoc SizeLoc = Lexer.getLoc();
1417 if (ParseAbsoluteExpression(Size))
1420 int64_t Pow2Alignment = 0;
1421 SMLoc Pow2AlignmentLoc;
1422 if (Lexer.is(AsmToken::Comma)) {
1424 Pow2AlignmentLoc = Lexer.getLoc();
1425 if (ParseAbsoluteExpression(Pow2Alignment))
1429 if (Lexer.isNot(AsmToken::EndOfStatement))
1430 return TokError("unexpected token in '.zerofill' directive");
1435 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1438 // NOTE: The alignment in the directive is a power of 2 value, the assember
1439 // may internally end up wanting an alignment in bytes.
1440 // FIXME: Diagnose overflow.
1441 if (Pow2Alignment < 0)
1442 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1443 "can't be less than zero");
1445 if (!Sym->isUndefined())
1446 return Error(IDLoc, "invalid symbol redefinition");
1448 // Create the zerofill Symbol with Size and Pow2Alignment
1450 // FIXME: Arch specific.
1451 Out.EmitZerofill(getMachOSection(Segment, Section,
1452 MCSectionMachO::S_ZEROFILL, 0,
1454 Sym, Size, 1 << Pow2Alignment);
1459 /// ParseDirectiveDarwinSubsectionsViaSymbols
1460 /// ::= .subsections_via_symbols
1461 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1462 if (Lexer.isNot(AsmToken::EndOfStatement))
1463 return TokError("unexpected token in '.subsections_via_symbols' directive");
1467 Out.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1472 /// ParseDirectiveAbort
1473 /// ::= .abort [ "abort_string" ]
1474 bool AsmParser::ParseDirectiveAbort() {
1475 // FIXME: Use loc from directive.
1476 SMLoc Loc = Lexer.getLoc();
1479 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1480 if (Lexer.isNot(AsmToken::String))
1481 return TokError("expected string in '.abort' directive");
1483 Str = getTok().getString();
1488 if (Lexer.isNot(AsmToken::EndOfStatement))
1489 return TokError("unexpected token in '.abort' directive");
1493 // FIXME: Handle here.
1495 Error(Loc, ".abort detected. Assembly stopping.");
1497 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1502 /// ParseDirectiveLsym
1503 /// ::= .lsym identifier , expression
1504 bool AsmParser::ParseDirectiveDarwinLsym() {
1506 if (ParseIdentifier(Name))
1507 return TokError("expected identifier in directive");
1509 // Handle the identifier as the key symbol.
1510 MCSymbol *Sym = CreateSymbol(Name);
1512 if (Lexer.isNot(AsmToken::Comma))
1513 return TokError("unexpected token in '.lsym' directive");
1516 const MCExpr *Value;
1517 SMLoc StartLoc = Lexer.getLoc();
1518 if (ParseExpression(Value))
1521 if (Lexer.isNot(AsmToken::EndOfStatement))
1522 return TokError("unexpected token in '.lsym' directive");
1526 // We don't currently support this directive.
1528 // FIXME: Diagnostic location!
1530 return TokError("directive '.lsym' is unsupported");
1533 /// ParseDirectiveInclude
1534 /// ::= .include "filename"
1535 bool AsmParser::ParseDirectiveInclude() {
1536 if (Lexer.isNot(AsmToken::String))
1537 return TokError("expected string in '.include' directive");
1539 std::string Filename = getTok().getString();
1540 SMLoc IncludeLoc = Lexer.getLoc();
1543 if (Lexer.isNot(AsmToken::EndOfStatement))
1544 return TokError("unexpected token in '.include' directive");
1546 // Strip the quotes.
1547 Filename = Filename.substr(1, Filename.size()-2);
1549 // Attempt to switch the lexer to the included file before consuming the end
1550 // of statement to avoid losing it when we switch.
1551 if (EnterIncludeFile(Filename)) {
1552 PrintMessage(IncludeLoc,
1553 "Could not find include file '" + Filename + "'",
1561 /// ParseDirectiveDarwinDumpOrLoad
1562 /// ::= ( .dump | .load ) "filename"
1563 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1564 if (Lexer.isNot(AsmToken::String))
1565 return TokError("expected string in '.dump' or '.load' directive");
1569 if (Lexer.isNot(AsmToken::EndOfStatement))
1570 return TokError("unexpected token in '.dump' or '.load' directive");
1574 // FIXME: If/when .dump and .load are implemented they will be done in the
1575 // the assembly parser and not have any need for an MCStreamer API.
1577 Warning(IDLoc, "ignoring directive .dump for now");
1579 Warning(IDLoc, "ignoring directive .load for now");
1584 /// ParseDirectiveIf
1585 /// ::= .if expression
1586 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1587 // Consume the identifier that was the .if directive
1590 TheCondStack.push_back(TheCondState);
1591 TheCondState.TheCond = AsmCond::IfCond;
1592 if(TheCondState.Ignore) {
1593 EatToEndOfStatement();
1597 if (ParseAbsoluteExpression(ExprValue))
1600 if (Lexer.isNot(AsmToken::EndOfStatement))
1601 return TokError("unexpected token in '.if' directive");
1605 TheCondState.CondMet = ExprValue;
1606 TheCondState.Ignore = !TheCondState.CondMet;
1612 /// ParseDirectiveElseIf
1613 /// ::= .elseif expression
1614 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1615 if (TheCondState.TheCond != AsmCond::IfCond &&
1616 TheCondState.TheCond != AsmCond::ElseIfCond)
1617 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1619 TheCondState.TheCond = AsmCond::ElseIfCond;
1621 // Consume the identifier that was the .elseif directive
1624 bool LastIgnoreState = false;
1625 if (!TheCondStack.empty())
1626 LastIgnoreState = TheCondStack.back().Ignore;
1627 if (LastIgnoreState || TheCondState.CondMet) {
1628 TheCondState.Ignore = true;
1629 EatToEndOfStatement();
1633 if (ParseAbsoluteExpression(ExprValue))
1636 if (Lexer.isNot(AsmToken::EndOfStatement))
1637 return TokError("unexpected token in '.elseif' directive");
1640 TheCondState.CondMet = ExprValue;
1641 TheCondState.Ignore = !TheCondState.CondMet;
1647 /// ParseDirectiveElse
1649 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1650 // Consume the identifier that was the .else directive
1653 if (Lexer.isNot(AsmToken::EndOfStatement))
1654 return TokError("unexpected token in '.else' directive");
1658 if (TheCondState.TheCond != AsmCond::IfCond &&
1659 TheCondState.TheCond != AsmCond::ElseIfCond)
1660 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1662 TheCondState.TheCond = AsmCond::ElseCond;
1663 bool LastIgnoreState = false;
1664 if (!TheCondStack.empty())
1665 LastIgnoreState = TheCondStack.back().Ignore;
1666 if (LastIgnoreState || TheCondState.CondMet)
1667 TheCondState.Ignore = true;
1669 TheCondState.Ignore = false;
1674 /// ParseDirectiveEndIf
1676 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1677 // Consume the identifier that was the .endif directive
1680 if (Lexer.isNot(AsmToken::EndOfStatement))
1681 return TokError("unexpected token in '.endif' directive");
1685 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1686 TheCondStack.empty())
1687 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1689 if (!TheCondStack.empty()) {
1690 TheCondState = TheCondStack.back();
1691 TheCondStack.pop_back();
1697 /// ParseDirectiveFile
1698 /// ::= .file [number] string
1699 bool AsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1700 // FIXME: I'm not sure what this is.
1701 int64_t FileNumber = -1;
1702 if (Lexer.is(AsmToken::Integer)) {
1703 FileNumber = getTok().getIntVal();
1707 return TokError("file number less than one");
1710 if (Lexer.isNot(AsmToken::String))
1711 return TokError("unexpected token in '.file' directive");
1713 StringRef ATTRIBUTE_UNUSED FileName = getTok().getString();
1716 if (Lexer.isNot(AsmToken::EndOfStatement))
1717 return TokError("unexpected token in '.file' directive");
1719 // FIXME: Do something with the .file.
1724 /// ParseDirectiveLine
1725 /// ::= .line [number]
1726 bool AsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1727 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1728 if (Lexer.isNot(AsmToken::Integer))
1729 return TokError("unexpected token in '.line' directive");
1731 int64_t LineNumber = getTok().getIntVal();
1735 // FIXME: Do something with the .line.
1738 if (Lexer.isNot(AsmToken::EndOfStatement))
1739 return TokError("unexpected token in '.file' directive");
1745 /// ParseDirectiveLoc
1746 /// ::= .loc number [number [number]]
1747 bool AsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1748 if (Lexer.isNot(AsmToken::Integer))
1749 return TokError("unexpected token in '.loc' directive");
1751 // FIXME: What are these fields?
1752 int64_t FileNumber = getTok().getIntVal();
1754 // FIXME: Validate file.
1757 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1758 if (Lexer.isNot(AsmToken::Integer))
1759 return TokError("unexpected token in '.loc' directive");
1761 int64_t Param2 = getTok().getIntVal();
1765 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1766 if (Lexer.isNot(AsmToken::Integer))
1767 return TokError("unexpected token in '.loc' directive");
1769 int64_t Param3 = getTok().getIntVal();
1773 // FIXME: Do something with the .loc.
1777 if (Lexer.isNot(AsmToken::EndOfStatement))
1778 return TokError("unexpected token in '.file' directive");