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 "llvm/MC/MCParser/AsmParser.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetAsmParser.h"
31 enum { DEFAULT_ADDRSPACE = 0 };
33 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
34 const MCAsmInfo &_MAI)
35 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM), TargetParser(0),
37 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
39 // Debugging directives.
40 AddDirectiveHandler(".file", &AsmParser::ParseDirectiveFile);
41 AddDirectiveHandler(".line", &AsmParser::ParseDirectiveLine);
42 AddDirectiveHandler(".loc", &AsmParser::ParseDirectiveLoc);
47 AsmParser::~AsmParser() {
50 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
51 PrintMessage(L, Msg.str(), "warning");
54 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
55 PrintMessage(L, Msg.str(), "error");
59 bool AsmParser::TokError(const char *Msg) {
60 PrintMessage(Lexer.getLoc(), Msg, "error");
64 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
65 const char *Type) const {
66 SrcMgr.PrintMessage(Loc, Msg, Type);
69 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
70 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
76 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
81 const AsmToken &AsmParser::Lex() {
82 const AsmToken *tok = &Lexer.Lex();
84 if (tok->is(AsmToken::Eof)) {
85 // If this is the end of an included file, pop the parent file off the
87 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
88 if (ParentIncludeLoc != SMLoc()) {
89 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
90 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer),
91 ParentIncludeLoc.getPointer());
96 if (tok->is(AsmToken::Error))
97 PrintMessage(Lexer.getErrLoc(), Lexer.getErr(), "error");
102 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
103 // Create the initial section, if requested.
105 // FIXME: Target hook & command line option for initial section.
106 if (!NoInitialTextSection)
107 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
108 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
109 0, SectionKind::getText()));
114 bool HadError = false;
116 AsmCond StartingCondState = TheCondState;
118 // While we have input, parse each statement.
119 while (Lexer.isNot(AsmToken::Eof)) {
120 if (!ParseStatement()) continue;
122 // We had an error, remember it and recover by skipping to the next line.
124 EatToEndOfStatement();
127 if (TheCondState.TheCond != StartingCondState.TheCond ||
128 TheCondState.Ignore != StartingCondState.Ignore)
129 return TokError("unmatched .ifs or .elses");
131 // Finalize the output stream if there are no errors and if the client wants
133 if (!HadError && !NoFinalize)
139 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
140 void AsmParser::EatToEndOfStatement() {
141 while (Lexer.isNot(AsmToken::EndOfStatement) &&
142 Lexer.isNot(AsmToken::Eof))
146 if (Lexer.is(AsmToken::EndOfStatement))
151 /// ParseParenExpr - Parse a paren expression and return it.
152 /// NOTE: This assumes the leading '(' has already been consumed.
154 /// parenexpr ::= expr)
156 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
157 if (ParseExpression(Res)) return true;
158 if (Lexer.isNot(AsmToken::RParen))
159 return TokError("expected ')' in parentheses expression");
160 EndLoc = Lexer.getLoc();
165 MCSymbol *AsmParser::CreateSymbol(StringRef Name) {
166 // FIXME: Inline into callers.
167 return Ctx.GetOrCreateSymbol(Name);
170 /// ParsePrimaryExpr - Parse a primary expression and return it.
171 /// primaryexpr ::= (parenexpr
172 /// primaryexpr ::= symbol
173 /// primaryexpr ::= number
174 /// primaryexpr ::= '.'
175 /// primaryexpr ::= ~,+,- primaryexpr
176 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
177 switch (Lexer.getKind()) {
179 return TokError("unknown token in expression");
180 case AsmToken::Exclaim:
181 Lex(); // Eat the operator.
182 if (ParsePrimaryExpr(Res, EndLoc))
184 Res = MCUnaryExpr::CreateLNot(Res, getContext());
186 case AsmToken::String:
187 case AsmToken::Identifier: {
188 // This is a symbol reference.
189 std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
190 MCSymbol *Sym = CreateSymbol(Split.first);
192 // Mark the symbol as used in an expression.
193 Sym->setUsedInExpr(true);
195 // Lookup the symbol variant if used.
196 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
197 if (Split.first.size() != getTok().getIdentifier().size())
198 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
200 EndLoc = Lexer.getLoc();
201 Lex(); // Eat identifier.
203 // If this is an absolute variable reference, substitute it now to preserve
204 // semantics in the face of reassignment.
205 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
207 return Error(EndLoc, "unexpected modified on variable reference");
209 Res = Sym->getVariableValue();
213 // Otherwise create a symbol ref.
214 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
217 case AsmToken::Integer:
218 Res = MCConstantExpr::Create(getTok().getIntVal(), getContext());
219 EndLoc = Lexer.getLoc();
222 case AsmToken::Dot: {
223 // This is a '.' reference, which references the current PC. Emit a
224 // temporary label to the streamer and refer to it.
225 MCSymbol *Sym = Ctx.CreateTempSymbol();
227 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
228 EndLoc = Lexer.getLoc();
229 Lex(); // Eat identifier.
233 case AsmToken::LParen:
234 Lex(); // Eat the '('.
235 return ParseParenExpr(Res, EndLoc);
236 case AsmToken::Minus:
237 Lex(); // Eat the operator.
238 if (ParsePrimaryExpr(Res, EndLoc))
240 Res = MCUnaryExpr::CreateMinus(Res, getContext());
243 Lex(); // Eat the operator.
244 if (ParsePrimaryExpr(Res, EndLoc))
246 Res = MCUnaryExpr::CreatePlus(Res, getContext());
248 case AsmToken::Tilde:
249 Lex(); // Eat the operator.
250 if (ParsePrimaryExpr(Res, EndLoc))
252 Res = MCUnaryExpr::CreateNot(Res, getContext());
257 bool AsmParser::ParseExpression(const MCExpr *&Res) {
259 return ParseExpression(Res, EndLoc);
262 /// ParseExpression - Parse an expression and return it.
264 /// expr ::= expr +,- expr -> lowest.
265 /// expr ::= expr |,^,&,! expr -> middle.
266 /// expr ::= expr *,/,%,<<,>> expr -> highest.
267 /// expr ::= primaryexpr
269 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
270 // Parse the expression.
272 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
275 // Try to constant fold it up front, if possible.
277 if (Res->EvaluateAsAbsolute(Value))
278 Res = MCConstantExpr::Create(Value, getContext());
283 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
285 return ParseParenExpr(Res, EndLoc) ||
286 ParseBinOpRHS(1, Res, EndLoc);
289 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
292 SMLoc StartLoc = Lexer.getLoc();
293 if (ParseExpression(Expr))
296 if (!Expr->EvaluateAsAbsolute(Res))
297 return Error(StartLoc, "expected absolute expression");
302 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
303 MCBinaryExpr::Opcode &Kind) {
306 return 0; // not a binop.
308 // Lowest Precedence: &&, ||
309 case AsmToken::AmpAmp:
310 Kind = MCBinaryExpr::LAnd;
312 case AsmToken::PipePipe:
313 Kind = MCBinaryExpr::LOr;
316 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
318 Kind = MCBinaryExpr::Add;
320 case AsmToken::Minus:
321 Kind = MCBinaryExpr::Sub;
323 case AsmToken::EqualEqual:
324 Kind = MCBinaryExpr::EQ;
326 case AsmToken::ExclaimEqual:
327 case AsmToken::LessGreater:
328 Kind = MCBinaryExpr::NE;
331 Kind = MCBinaryExpr::LT;
333 case AsmToken::LessEqual:
334 Kind = MCBinaryExpr::LTE;
336 case AsmToken::Greater:
337 Kind = MCBinaryExpr::GT;
339 case AsmToken::GreaterEqual:
340 Kind = MCBinaryExpr::GTE;
343 // Intermediate Precedence: |, &, ^
345 // FIXME: gas seems to support '!' as an infix operator?
347 Kind = MCBinaryExpr::Or;
349 case AsmToken::Caret:
350 Kind = MCBinaryExpr::Xor;
353 Kind = MCBinaryExpr::And;
356 // Highest Precedence: *, /, %, <<, >>
358 Kind = MCBinaryExpr::Mul;
360 case AsmToken::Slash:
361 Kind = MCBinaryExpr::Div;
363 case AsmToken::Percent:
364 Kind = MCBinaryExpr::Mod;
366 case AsmToken::LessLess:
367 Kind = MCBinaryExpr::Shl;
369 case AsmToken::GreaterGreater:
370 Kind = MCBinaryExpr::Shr;
376 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
377 /// Res contains the LHS of the expression on input.
378 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
381 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
382 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
384 // If the next token is lower precedence than we are allowed to eat, return
385 // successfully with what we ate already.
386 if (TokPrec < Precedence)
391 // Eat the next primary expression.
393 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
395 // If BinOp binds less tightly with RHS than the operator after RHS, let
396 // the pending operator take RHS as its LHS.
397 MCBinaryExpr::Opcode Dummy;
398 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
399 if (TokPrec < NextTokPrec) {
400 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
403 // Merge LHS and RHS according to operator.
404 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
412 /// ::= EndOfStatement
413 /// ::= Label* Directive ...Operands... EndOfStatement
414 /// ::= Label* Identifier OperandList* EndOfStatement
415 bool AsmParser::ParseStatement() {
416 if (Lexer.is(AsmToken::EndOfStatement)) {
421 // Statements always start with an identifier.
422 AsmToken ID = getTok();
423 SMLoc IDLoc = ID.getLoc();
425 if (ParseIdentifier(IDVal)) {
426 if (!TheCondState.Ignore)
427 return TokError("unexpected token at start of statement");
431 // Handle conditional assembly here before checking for skipping. We
432 // have to do this so that .endif isn't skipped in a ".if 0" block for
435 return ParseDirectiveIf(IDLoc);
436 if (IDVal == ".elseif")
437 return ParseDirectiveElseIf(IDLoc);
438 if (IDVal == ".else")
439 return ParseDirectiveElse(IDLoc);
440 if (IDVal == ".endif")
441 return ParseDirectiveEndIf(IDLoc);
443 // If we are in a ".if 0" block, ignore this statement.
444 if (TheCondState.Ignore) {
445 EatToEndOfStatement();
449 // FIXME: Recurse on local labels?
451 // See what kind of statement we have.
452 switch (Lexer.getKind()) {
453 case AsmToken::Colon: {
454 // identifier ':' -> Label.
457 // Diagnose attempt to use a variable as a label.
459 // FIXME: Diagnostics. Note the location of the definition as a label.
460 // FIXME: This doesn't diagnose assignment to a symbol which has been
461 // implicitly marked as external.
462 MCSymbol *Sym = CreateSymbol(IDVal);
463 if (!Sym->isUndefined() || Sym->isVariable())
464 return Error(IDLoc, "invalid symbol redefinition");
469 return ParseStatement();
472 case AsmToken::Equal:
473 // identifier '=' ... -> assignment statement
476 return ParseAssignment(IDVal);
478 default: // Normal instruction or directive.
482 // Otherwise, we have a normal instruction or directive.
483 if (IDVal[0] == '.') {
484 // FIXME: This should be driven based on a hash lookup and callback.
485 if (IDVal == ".section")
486 return ParseDirectiveDarwinSection();
487 if (IDVal == ".text")
488 // FIXME: This changes behavior based on the -static flag to the
490 return ParseDirectiveSectionSwitch("__TEXT", "__text",
491 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
492 if (IDVal == ".const")
493 return ParseDirectiveSectionSwitch("__TEXT", "__const");
494 if (IDVal == ".static_const")
495 return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
496 if (IDVal == ".cstring")
497 return ParseDirectiveSectionSwitch("__TEXT","__cstring",
498 MCSectionMachO::S_CSTRING_LITERALS);
499 if (IDVal == ".literal4")
500 return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
501 MCSectionMachO::S_4BYTE_LITERALS,
503 if (IDVal == ".literal8")
504 return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
505 MCSectionMachO::S_8BYTE_LITERALS,
507 if (IDVal == ".literal16")
508 return ParseDirectiveSectionSwitch("__TEXT","__literal16",
509 MCSectionMachO::S_16BYTE_LITERALS,
511 if (IDVal == ".constructor")
512 return ParseDirectiveSectionSwitch("__TEXT","__constructor");
513 if (IDVal == ".destructor")
514 return ParseDirectiveSectionSwitch("__TEXT","__destructor");
515 if (IDVal == ".fvmlib_init0")
516 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
517 if (IDVal == ".fvmlib_init1")
518 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
520 // FIXME: The assembler manual claims that this has the self modify code
521 // flag, at least on x86-32, but that does not appear to be correct.
522 if (IDVal == ".symbol_stub")
523 return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
524 MCSectionMachO::S_SYMBOL_STUBS |
525 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
526 // FIXME: Different on PPC and ARM.
528 // FIXME: PowerPC only?
529 if (IDVal == ".picsymbol_stub")
530 return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
531 MCSectionMachO::S_SYMBOL_STUBS |
532 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
534 if (IDVal == ".data")
535 return ParseDirectiveSectionSwitch("__DATA", "__data");
536 if (IDVal == ".static_data")
537 return ParseDirectiveSectionSwitch("__DATA", "__static_data");
539 // FIXME: The section names of these two are misspelled in the assembler
541 if (IDVal == ".non_lazy_symbol_pointer")
542 return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
543 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
545 if (IDVal == ".lazy_symbol_pointer")
546 return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
547 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
550 if (IDVal == ".dyld")
551 return ParseDirectiveSectionSwitch("__DATA", "__dyld");
552 if (IDVal == ".mod_init_func")
553 return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
554 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
556 if (IDVal == ".mod_term_func")
557 return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
558 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
560 if (IDVal == ".const_data")
561 return ParseDirectiveSectionSwitch("__DATA", "__const");
564 if (IDVal == ".objc_class")
565 return ParseDirectiveSectionSwitch("__OBJC", "__class",
566 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
567 if (IDVal == ".objc_meta_class")
568 return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
569 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
570 if (IDVal == ".objc_cat_cls_meth")
571 return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
572 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
573 if (IDVal == ".objc_cat_inst_meth")
574 return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
575 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
576 if (IDVal == ".objc_protocol")
577 return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
578 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
579 if (IDVal == ".objc_string_object")
580 return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
581 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
582 if (IDVal == ".objc_cls_meth")
583 return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
584 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
585 if (IDVal == ".objc_inst_meth")
586 return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
587 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
588 if (IDVal == ".objc_cls_refs")
589 return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
590 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
591 MCSectionMachO::S_LITERAL_POINTERS,
593 if (IDVal == ".objc_message_refs")
594 return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
595 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
596 MCSectionMachO::S_LITERAL_POINTERS,
598 if (IDVal == ".objc_symbols")
599 return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
600 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
601 if (IDVal == ".objc_category")
602 return ParseDirectiveSectionSwitch("__OBJC", "__category",
603 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
604 if (IDVal == ".objc_class_vars")
605 return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
606 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
607 if (IDVal == ".objc_instance_vars")
608 return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
609 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
610 if (IDVal == ".objc_module_info")
611 return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
612 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
613 if (IDVal == ".objc_class_names")
614 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
615 MCSectionMachO::S_CSTRING_LITERALS);
616 if (IDVal == ".objc_meth_var_types")
617 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
618 MCSectionMachO::S_CSTRING_LITERALS);
619 if (IDVal == ".objc_meth_var_names")
620 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
621 MCSectionMachO::S_CSTRING_LITERALS);
622 if (IDVal == ".objc_selector_strs")
623 return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
624 MCSectionMachO::S_CSTRING_LITERALS);
626 if (IDVal == ".tdata")
627 return ParseDirectiveSectionSwitch("__DATA", "__thread_data",
628 MCSectionMachO::S_THREAD_LOCAL_REGULAR);
630 return ParseDirectiveSectionSwitch("__DATA", "__thread_vars",
631 MCSectionMachO::S_THREAD_LOCAL_VARIABLES);
632 if (IDVal == ".thread_init_func")
633 return ParseDirectiveSectionSwitch("__DATA", "__thread_init",
634 MCSectionMachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS);
636 // Assembler features
638 return ParseDirectiveSet();
642 if (IDVal == ".ascii")
643 return ParseDirectiveAscii(false);
644 if (IDVal == ".asciz")
645 return ParseDirectiveAscii(true);
647 if (IDVal == ".byte")
648 return ParseDirectiveValue(1);
649 if (IDVal == ".short")
650 return ParseDirectiveValue(2);
651 if (IDVal == ".long")
652 return ParseDirectiveValue(4);
653 if (IDVal == ".quad")
654 return ParseDirectiveValue(8);
656 // FIXME: Target hooks for IsPow2.
657 if (IDVal == ".align")
658 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
659 if (IDVal == ".align32")
660 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
661 if (IDVal == ".balign")
662 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
663 if (IDVal == ".balignw")
664 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
665 if (IDVal == ".balignl")
666 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
667 if (IDVal == ".p2align")
668 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
669 if (IDVal == ".p2alignw")
670 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
671 if (IDVal == ".p2alignl")
672 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
675 return ParseDirectiveOrg();
677 if (IDVal == ".fill")
678 return ParseDirectiveFill();
679 if (IDVal == ".space")
680 return ParseDirectiveSpace();
682 // Symbol attribute directives
684 if (IDVal == ".globl" || IDVal == ".global")
685 return ParseDirectiveSymbolAttribute(MCSA_Global);
686 if (IDVal == ".hidden")
687 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
688 if (IDVal == ".indirect_symbol")
689 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
690 if (IDVal == ".internal")
691 return ParseDirectiveSymbolAttribute(MCSA_Internal);
692 if (IDVal == ".lazy_reference")
693 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
694 if (IDVal == ".no_dead_strip")
695 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
696 if (IDVal == ".private_extern")
697 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
698 if (IDVal == ".protected")
699 return ParseDirectiveSymbolAttribute(MCSA_Protected);
700 if (IDVal == ".reference")
701 return ParseDirectiveSymbolAttribute(MCSA_Reference);
702 if (IDVal == ".weak")
703 return ParseDirectiveSymbolAttribute(MCSA_Weak);
704 if (IDVal == ".weak_definition")
705 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
706 if (IDVal == ".weak_reference")
707 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
709 if (IDVal == ".comm")
710 return ParseDirectiveComm(/*IsLocal=*/false);
711 if (IDVal == ".lcomm")
712 return ParseDirectiveComm(/*IsLocal=*/true);
713 if (IDVal == ".zerofill")
714 return ParseDirectiveDarwinZerofill();
715 if (IDVal == ".desc")
716 return ParseDirectiveDarwinSymbolDesc();
717 if (IDVal == ".lsym")
718 return ParseDirectiveDarwinLsym();
719 if (IDVal == ".tbss")
720 return ParseDirectiveDarwinTBSS();
722 if (IDVal == ".subsections_via_symbols")
723 return ParseDirectiveDarwinSubsectionsViaSymbols();
724 if (IDVal == ".abort")
725 return ParseDirectiveAbort();
726 if (IDVal == ".include")
727 return ParseDirectiveInclude();
728 if (IDVal == ".dump")
729 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
730 if (IDVal == ".load")
731 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
733 // Look up the handler in the handler table,
734 bool(AsmParser::*Handler)(StringRef, SMLoc) = DirectiveMap[IDVal];
736 return (this->*Handler)(IDVal, IDLoc);
738 // Target hook for parsing target specific directives.
739 if (!getTargetParser().ParseDirective(ID))
742 Warning(IDLoc, "ignoring directive for now");
743 EatToEndOfStatement();
747 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
748 bool HadError = getTargetParser().ParseInstruction(IDVal, IDLoc,
750 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
751 HadError = TokError("unexpected token in argument list");
753 // If parsing succeeded, match the instruction.
756 if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
757 // Emit the instruction on success.
758 Out.EmitInstruction(Inst);
760 // Otherwise emit a diagnostic about the match failure and set the error
763 // FIXME: We should give nicer diagnostics about the exact failure.
764 Error(IDLoc, "unrecognized instruction");
769 // If there was no error, consume the end-of-statement token. Otherwise this
770 // will be done by our caller.
774 // Free any parsed operands.
775 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
776 delete ParsedOperands[i];
781 bool AsmParser::ParseAssignment(const StringRef &Name) {
782 // FIXME: Use better location, we should use proper tokens.
783 SMLoc EqualLoc = Lexer.getLoc();
786 SMLoc StartLoc = Lexer.getLoc();
787 if (ParseExpression(Value))
790 if (Lexer.isNot(AsmToken::EndOfStatement))
791 return TokError("unexpected token in assignment");
793 // Eat the end of statement marker.
796 // Validate that the LHS is allowed to be a variable (either it has not been
797 // used as a symbol, or it is an absolute symbol).
798 MCSymbol *Sym = getContext().LookupSymbol(Name);
800 // Diagnose assignment to a label.
802 // FIXME: Diagnostics. Note the location of the definition as a label.
803 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
804 if (Sym->isUndefined() && !Sym->isUsedInExpr())
805 ; // Allow redefinitions of undefined symbols only used in directives.
806 else if (!Sym->isUndefined() && !Sym->isAbsolute())
807 return Error(EqualLoc, "redefinition of '" + Name + "'");
808 else if (!Sym->isVariable())
809 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
810 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
811 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
814 Sym = CreateSymbol(Name);
816 // FIXME: Handle '.'.
818 Sym->setUsedInExpr(true);
820 // Do the assignment.
821 Out.EmitAssignment(Sym, Value);
829 bool AsmParser::ParseIdentifier(StringRef &Res) {
830 if (Lexer.isNot(AsmToken::Identifier) &&
831 Lexer.isNot(AsmToken::String))
834 Res = getTok().getIdentifier();
836 Lex(); // Consume the identifier token.
841 /// ParseDirectiveSet:
842 /// ::= .set identifier ',' expression
843 bool AsmParser::ParseDirectiveSet() {
846 if (ParseIdentifier(Name))
847 return TokError("expected identifier after '.set' directive");
849 if (Lexer.isNot(AsmToken::Comma))
850 return TokError("unexpected token in '.set'");
853 return ParseAssignment(Name);
856 /// ParseDirectiveSection:
857 /// ::= .section identifier (',' identifier)*
858 /// FIXME: This should actually parse out the segment, section, attributes and
859 /// sizeof_stub fields.
860 bool AsmParser::ParseDirectiveDarwinSection() {
861 SMLoc Loc = Lexer.getLoc();
863 StringRef SectionName;
864 if (ParseIdentifier(SectionName))
865 return Error(Loc, "expected identifier after '.section' directive");
867 // Verify there is a following comma.
868 if (!Lexer.is(AsmToken::Comma))
869 return TokError("unexpected token in '.section' directive");
871 std::string SectionSpec = SectionName;
874 // Add all the tokens until the end of the line, ParseSectionSpecifier will
876 StringRef EOL = Lexer.LexUntilEndOfStatement();
877 SectionSpec.append(EOL.begin(), EOL.end());
880 if (Lexer.isNot(AsmToken::EndOfStatement))
881 return TokError("unexpected token in '.section' directive");
885 StringRef Segment, Section;
886 unsigned TAA, StubSize;
887 std::string ErrorStr =
888 MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
891 if (!ErrorStr.empty())
892 return Error(Loc, ErrorStr.c_str());
894 // FIXME: Arch specific.
895 bool isText = Segment == "__TEXT"; // FIXME: Hack.
896 Out.SwitchSection(Ctx.getMachOSection(Segment, Section, TAA, StubSize,
897 isText ? SectionKind::getText()
898 : SectionKind::getDataRel()));
902 /// ParseDirectiveSectionSwitch -
903 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
905 unsigned TAA, unsigned Align,
907 if (Lexer.isNot(AsmToken::EndOfStatement))
908 return TokError("unexpected token in section switching directive");
911 // FIXME: Arch specific.
912 bool isText = StringRef(Segment) == "__TEXT"; // FIXME: Hack.
913 Out.SwitchSection(Ctx.getMachOSection(Segment, Section, TAA, StubSize,
914 isText ? SectionKind::getText()
915 : SectionKind::getDataRel()));
917 // Set the implicit alignment, if any.
919 // FIXME: This isn't really what 'as' does; I think it just uses the implicit
920 // alignment on the section (e.g., if one manually inserts bytes into the
921 // section, then just issueing the section switch directive will not realign
922 // the section. However, this is arguably more reasonable behavior, and there
923 // is no good reason for someone to intentionally emit incorrectly sized
924 // values into the implicitly aligned sections.
926 Out.EmitValueToAlignment(Align, 0, 1, 0);
931 bool AsmParser::ParseEscapedString(std::string &Data) {
932 assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
935 StringRef Str = getTok().getStringContents();
936 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
937 if (Str[i] != '\\') {
942 // Recognize escaped characters. Note that this escape semantics currently
943 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
946 return TokError("unexpected backslash at end of string");
948 // Recognize octal sequences.
949 if ((unsigned) (Str[i] - '0') <= 7) {
950 // Consume up to three octal characters.
951 unsigned Value = Str[i] - '0';
953 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
955 Value = Value * 8 + (Str[i] - '0');
957 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
959 Value = Value * 8 + (Str[i] - '0');
964 return TokError("invalid octal escape sequence (out of range)");
966 Data += (unsigned char) Value;
970 // Otherwise recognize individual escapes.
973 // Just reject invalid escape sequences for now.
974 return TokError("invalid escape sequence (unrecognized character)");
976 case 'b': Data += '\b'; break;
977 case 'f': Data += '\f'; break;
978 case 'n': Data += '\n'; break;
979 case 'r': Data += '\r'; break;
980 case 't': Data += '\t'; break;
981 case '"': Data += '"'; break;
982 case '\\': Data += '\\'; break;
989 /// ParseDirectiveAscii:
990 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
991 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
992 if (Lexer.isNot(AsmToken::EndOfStatement)) {
994 if (Lexer.isNot(AsmToken::String))
995 return TokError("expected string in '.ascii' or '.asciz' directive");
998 if (ParseEscapedString(Data))
1001 Out.EmitBytes(Data, DEFAULT_ADDRSPACE);
1003 Out.EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1007 if (Lexer.is(AsmToken::EndOfStatement))
1010 if (Lexer.isNot(AsmToken::Comma))
1011 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1020 /// ParseDirectiveValue
1021 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1022 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1023 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1025 const MCExpr *Value;
1026 SMLoc ATTRIBUTE_UNUSED StartLoc = Lexer.getLoc();
1027 if (ParseExpression(Value))
1030 Out.EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1032 if (Lexer.is(AsmToken::EndOfStatement))
1035 // FIXME: Improve diagnostic.
1036 if (Lexer.isNot(AsmToken::Comma))
1037 return TokError("unexpected token in directive");
1046 /// ParseDirectiveSpace
1047 /// ::= .space expression [ , expression ]
1048 bool AsmParser::ParseDirectiveSpace() {
1050 if (ParseAbsoluteExpression(NumBytes))
1053 int64_t FillExpr = 0;
1054 bool HasFillExpr = false;
1055 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1056 if (Lexer.isNot(AsmToken::Comma))
1057 return TokError("unexpected token in '.space' directive");
1060 if (ParseAbsoluteExpression(FillExpr))
1065 if (Lexer.isNot(AsmToken::EndOfStatement))
1066 return TokError("unexpected token in '.space' directive");
1072 return TokError("invalid number of bytes in '.space' directive");
1074 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1075 Out.EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1080 /// ParseDirectiveFill
1081 /// ::= .fill expression , expression , expression
1082 bool AsmParser::ParseDirectiveFill() {
1084 if (ParseAbsoluteExpression(NumValues))
1087 if (Lexer.isNot(AsmToken::Comma))
1088 return TokError("unexpected token in '.fill' directive");
1092 if (ParseAbsoluteExpression(FillSize))
1095 if (Lexer.isNot(AsmToken::Comma))
1096 return TokError("unexpected token in '.fill' directive");
1100 if (ParseAbsoluteExpression(FillExpr))
1103 if (Lexer.isNot(AsmToken::EndOfStatement))
1104 return TokError("unexpected token in '.fill' directive");
1108 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1109 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1111 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1112 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), FillSize,
1118 /// ParseDirectiveOrg
1119 /// ::= .org expression [ , expression ]
1120 bool AsmParser::ParseDirectiveOrg() {
1121 const MCExpr *Offset;
1122 SMLoc StartLoc = Lexer.getLoc();
1123 if (ParseExpression(Offset))
1126 // Parse optional fill expression.
1127 int64_t FillExpr = 0;
1128 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1129 if (Lexer.isNot(AsmToken::Comma))
1130 return TokError("unexpected token in '.org' directive");
1133 if (ParseAbsoluteExpression(FillExpr))
1136 if (Lexer.isNot(AsmToken::EndOfStatement))
1137 return TokError("unexpected token in '.org' directive");
1142 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1143 // has to be relative to the current section.
1144 Out.EmitValueToOffset(Offset, FillExpr);
1149 /// ParseDirectiveAlign
1150 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1151 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1152 SMLoc AlignmentLoc = Lexer.getLoc();
1154 if (ParseAbsoluteExpression(Alignment))
1158 bool HasFillExpr = false;
1159 int64_t FillExpr = 0;
1160 int64_t MaxBytesToFill = 0;
1161 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1162 if (Lexer.isNot(AsmToken::Comma))
1163 return TokError("unexpected token in directive");
1166 // The fill expression can be omitted while specifying a maximum number of
1167 // alignment bytes, e.g:
1169 if (Lexer.isNot(AsmToken::Comma)) {
1171 if (ParseAbsoluteExpression(FillExpr))
1175 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1176 if (Lexer.isNot(AsmToken::Comma))
1177 return TokError("unexpected token in directive");
1180 MaxBytesLoc = Lexer.getLoc();
1181 if (ParseAbsoluteExpression(MaxBytesToFill))
1184 if (Lexer.isNot(AsmToken::EndOfStatement))
1185 return TokError("unexpected token in directive");
1194 // Compute alignment in bytes.
1196 // FIXME: Diagnose overflow.
1197 if (Alignment >= 32) {
1198 Error(AlignmentLoc, "invalid alignment value");
1202 Alignment = 1ULL << Alignment;
1205 // Diagnose non-sensical max bytes to align.
1206 if (MaxBytesLoc.isValid()) {
1207 if (MaxBytesToFill < 1) {
1208 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1209 "many bytes, ignoring maximum bytes expression");
1213 if (MaxBytesToFill >= Alignment) {
1214 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1220 // Check whether we should use optimal code alignment for this .align
1223 // FIXME: This should be using a target hook.
1224 bool UseCodeAlign = false;
1225 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1226 Out.getCurrentSection()))
1227 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1228 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1229 ValueSize == 1 && UseCodeAlign) {
1230 Out.EmitCodeAlignment(Alignment, MaxBytesToFill);
1232 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1233 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1239 /// ParseDirectiveSymbolAttribute
1240 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1241 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1242 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1246 if (ParseIdentifier(Name))
1247 return TokError("expected identifier in directive");
1249 MCSymbol *Sym = CreateSymbol(Name);
1251 Out.EmitSymbolAttribute(Sym, Attr);
1253 if (Lexer.is(AsmToken::EndOfStatement))
1256 if (Lexer.isNot(AsmToken::Comma))
1257 return TokError("unexpected token in directive");
1266 /// ParseDirectiveDarwinSymbolDesc
1267 /// ::= .desc identifier , expression
1268 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1270 if (ParseIdentifier(Name))
1271 return TokError("expected identifier in directive");
1273 // Handle the identifier as the key symbol.
1274 MCSymbol *Sym = CreateSymbol(Name);
1276 if (Lexer.isNot(AsmToken::Comma))
1277 return TokError("unexpected token in '.desc' directive");
1280 SMLoc DescLoc = Lexer.getLoc();
1282 if (ParseAbsoluteExpression(DescValue))
1285 if (Lexer.isNot(AsmToken::EndOfStatement))
1286 return TokError("unexpected token in '.desc' directive");
1290 // Set the n_desc field of this Symbol to this DescValue
1291 Out.EmitSymbolDesc(Sym, DescValue);
1296 /// ParseDirectiveComm
1297 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1298 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1299 SMLoc IDLoc = Lexer.getLoc();
1301 if (ParseIdentifier(Name))
1302 return TokError("expected identifier in directive");
1304 // Handle the identifier as the key symbol.
1305 MCSymbol *Sym = CreateSymbol(Name);
1307 if (Lexer.isNot(AsmToken::Comma))
1308 return TokError("unexpected token in directive");
1312 SMLoc SizeLoc = Lexer.getLoc();
1313 if (ParseAbsoluteExpression(Size))
1316 int64_t Pow2Alignment = 0;
1317 SMLoc Pow2AlignmentLoc;
1318 if (Lexer.is(AsmToken::Comma)) {
1320 Pow2AlignmentLoc = Lexer.getLoc();
1321 if (ParseAbsoluteExpression(Pow2Alignment))
1324 // If this target takes alignments in bytes (not log) validate and convert.
1325 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1326 if (!isPowerOf2_64(Pow2Alignment))
1327 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1328 Pow2Alignment = Log2_64(Pow2Alignment);
1332 if (Lexer.isNot(AsmToken::EndOfStatement))
1333 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1337 // NOTE: a size of zero for a .comm should create a undefined symbol
1338 // but a size of .lcomm creates a bss symbol of size zero.
1340 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1341 "be less than zero");
1343 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1344 // may internally end up wanting an alignment in bytes.
1345 // FIXME: Diagnose overflow.
1346 if (Pow2Alignment < 0)
1347 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1348 "alignment, can't be less than zero");
1350 if (!Sym->isUndefined())
1351 return Error(IDLoc, "invalid symbol redefinition");
1353 // '.lcomm' is equivalent to '.zerofill'.
1354 // Create the Symbol as a common or local common with Size and Pow2Alignment
1356 Out.EmitZerofill(Ctx.getMachOSection("__DATA", "__bss",
1357 MCSectionMachO::S_ZEROFILL, 0,
1358 SectionKind::getBSS()),
1359 Sym, Size, 1 << Pow2Alignment);
1363 Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1367 /// ParseDirectiveDarwinZerofill
1368 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1369 /// , align_expression ]]
1370 bool AsmParser::ParseDirectiveDarwinZerofill() {
1372 if (ParseIdentifier(Segment))
1373 return TokError("expected segment name after '.zerofill' directive");
1375 if (Lexer.isNot(AsmToken::Comma))
1376 return TokError("unexpected token in directive");
1380 if (ParseIdentifier(Section))
1381 return TokError("expected section name after comma in '.zerofill' "
1384 // If this is the end of the line all that was wanted was to create the
1385 // the section but with no symbol.
1386 if (Lexer.is(AsmToken::EndOfStatement)) {
1387 // Create the zerofill section but no symbol
1388 Out.EmitZerofill(Ctx.getMachOSection(Segment, Section,
1389 MCSectionMachO::S_ZEROFILL, 0,
1390 SectionKind::getBSS()));
1394 if (Lexer.isNot(AsmToken::Comma))
1395 return TokError("unexpected token in directive");
1398 SMLoc IDLoc = Lexer.getLoc();
1400 if (ParseIdentifier(IDStr))
1401 return TokError("expected identifier in directive");
1403 // handle the identifier as the key symbol.
1404 MCSymbol *Sym = CreateSymbol(IDStr);
1406 if (Lexer.isNot(AsmToken::Comma))
1407 return TokError("unexpected token in directive");
1411 SMLoc SizeLoc = Lexer.getLoc();
1412 if (ParseAbsoluteExpression(Size))
1415 int64_t Pow2Alignment = 0;
1416 SMLoc Pow2AlignmentLoc;
1417 if (Lexer.is(AsmToken::Comma)) {
1419 Pow2AlignmentLoc = Lexer.getLoc();
1420 if (ParseAbsoluteExpression(Pow2Alignment))
1424 if (Lexer.isNot(AsmToken::EndOfStatement))
1425 return TokError("unexpected token in '.zerofill' directive");
1430 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1433 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1434 // may internally end up wanting an alignment in bytes.
1435 // FIXME: Diagnose overflow.
1436 if (Pow2Alignment < 0)
1437 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1438 "can't be less than zero");
1440 if (!Sym->isUndefined())
1441 return Error(IDLoc, "invalid symbol redefinition");
1443 // Create the zerofill Symbol with Size and Pow2Alignment
1445 // FIXME: Arch specific.
1446 Out.EmitZerofill(Ctx.getMachOSection(Segment, Section,
1447 MCSectionMachO::S_ZEROFILL, 0,
1448 SectionKind::getBSS()),
1449 Sym, Size, 1 << Pow2Alignment);
1454 /// ParseDirectiveDarwinTBSS
1455 /// ::= .tbss identifier, size, align
1456 bool AsmParser::ParseDirectiveDarwinTBSS() {
1457 SMLoc IDLoc = Lexer.getLoc();
1459 if (ParseIdentifier(Name))
1460 return TokError("expected identifier in directive");
1462 // Handle the identifier as the key symbol.
1463 MCSymbol *Sym = CreateSymbol(Name);
1465 if (Lexer.isNot(AsmToken::Comma))
1466 return TokError("unexpected token in directive");
1470 SMLoc SizeLoc = Lexer.getLoc();
1471 if (ParseAbsoluteExpression(Size))
1474 int64_t Pow2Alignment = 0;
1475 SMLoc Pow2AlignmentLoc;
1476 if (Lexer.is(AsmToken::Comma)) {
1478 Pow2AlignmentLoc = Lexer.getLoc();
1479 if (ParseAbsoluteExpression(Pow2Alignment))
1483 if (Lexer.isNot(AsmToken::EndOfStatement))
1484 return TokError("unexpected token in '.tbss' directive");
1489 return Error(SizeLoc, "invalid '.tbss' directive size, can't be less than"
1492 // FIXME: Diagnose overflow.
1493 if (Pow2Alignment < 0)
1494 return Error(Pow2AlignmentLoc, "invalid '.tbss' alignment, can't be less"
1497 if (!Sym->isUndefined())
1498 return Error(IDLoc, "invalid symbol redefinition");
1500 Out.EmitTBSSSymbol(Sym, Size, Pow2Alignment ? 1 << Pow2Alignment : 0);
1505 /// ParseDirectiveDarwinSubsectionsViaSymbols
1506 /// ::= .subsections_via_symbols
1507 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1508 if (Lexer.isNot(AsmToken::EndOfStatement))
1509 return TokError("unexpected token in '.subsections_via_symbols' directive");
1513 Out.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1518 /// ParseDirectiveAbort
1519 /// ::= .abort [ "abort_string" ]
1520 bool AsmParser::ParseDirectiveAbort() {
1521 // FIXME: Use loc from directive.
1522 SMLoc Loc = Lexer.getLoc();
1525 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1526 if (Lexer.isNot(AsmToken::String))
1527 return TokError("expected string in '.abort' directive");
1529 Str = getTok().getString();
1534 if (Lexer.isNot(AsmToken::EndOfStatement))
1535 return TokError("unexpected token in '.abort' directive");
1539 // FIXME: Handle here.
1541 Error(Loc, ".abort detected. Assembly stopping.");
1543 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1548 /// ParseDirectiveLsym
1549 /// ::= .lsym identifier , expression
1550 bool AsmParser::ParseDirectiveDarwinLsym() {
1552 if (ParseIdentifier(Name))
1553 return TokError("expected identifier in directive");
1555 // Handle the identifier as the key symbol.
1556 MCSymbol *Sym = CreateSymbol(Name);
1558 if (Lexer.isNot(AsmToken::Comma))
1559 return TokError("unexpected token in '.lsym' directive");
1562 const MCExpr *Value;
1563 SMLoc StartLoc = Lexer.getLoc();
1564 if (ParseExpression(Value))
1567 if (Lexer.isNot(AsmToken::EndOfStatement))
1568 return TokError("unexpected token in '.lsym' directive");
1572 // We don't currently support this directive.
1574 // FIXME: Diagnostic location!
1576 return TokError("directive '.lsym' is unsupported");
1579 /// ParseDirectiveInclude
1580 /// ::= .include "filename"
1581 bool AsmParser::ParseDirectiveInclude() {
1582 if (Lexer.isNot(AsmToken::String))
1583 return TokError("expected string in '.include' directive");
1585 std::string Filename = getTok().getString();
1586 SMLoc IncludeLoc = Lexer.getLoc();
1589 if (Lexer.isNot(AsmToken::EndOfStatement))
1590 return TokError("unexpected token in '.include' directive");
1592 // Strip the quotes.
1593 Filename = Filename.substr(1, Filename.size()-2);
1595 // Attempt to switch the lexer to the included file before consuming the end
1596 // of statement to avoid losing it when we switch.
1597 if (EnterIncludeFile(Filename)) {
1598 PrintMessage(IncludeLoc,
1599 "Could not find include file '" + Filename + "'",
1607 /// ParseDirectiveDarwinDumpOrLoad
1608 /// ::= ( .dump | .load ) "filename"
1609 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1610 if (Lexer.isNot(AsmToken::String))
1611 return TokError("expected string in '.dump' or '.load' directive");
1615 if (Lexer.isNot(AsmToken::EndOfStatement))
1616 return TokError("unexpected token in '.dump' or '.load' directive");
1620 // FIXME: If/when .dump and .load are implemented they will be done in the
1621 // the assembly parser and not have any need for an MCStreamer API.
1623 Warning(IDLoc, "ignoring directive .dump for now");
1625 Warning(IDLoc, "ignoring directive .load for now");
1630 /// ParseDirectiveIf
1631 /// ::= .if expression
1632 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1633 TheCondStack.push_back(TheCondState);
1634 TheCondState.TheCond = AsmCond::IfCond;
1635 if(TheCondState.Ignore) {
1636 EatToEndOfStatement();
1640 if (ParseAbsoluteExpression(ExprValue))
1643 if (Lexer.isNot(AsmToken::EndOfStatement))
1644 return TokError("unexpected token in '.if' directive");
1648 TheCondState.CondMet = ExprValue;
1649 TheCondState.Ignore = !TheCondState.CondMet;
1655 /// ParseDirectiveElseIf
1656 /// ::= .elseif expression
1657 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1658 if (TheCondState.TheCond != AsmCond::IfCond &&
1659 TheCondState.TheCond != AsmCond::ElseIfCond)
1660 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1662 TheCondState.TheCond = AsmCond::ElseIfCond;
1664 bool LastIgnoreState = false;
1665 if (!TheCondStack.empty())
1666 LastIgnoreState = TheCondStack.back().Ignore;
1667 if (LastIgnoreState || TheCondState.CondMet) {
1668 TheCondState.Ignore = true;
1669 EatToEndOfStatement();
1673 if (ParseAbsoluteExpression(ExprValue))
1676 if (Lexer.isNot(AsmToken::EndOfStatement))
1677 return TokError("unexpected token in '.elseif' directive");
1680 TheCondState.CondMet = ExprValue;
1681 TheCondState.Ignore = !TheCondState.CondMet;
1687 /// ParseDirectiveElse
1689 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1690 if (Lexer.isNot(AsmToken::EndOfStatement))
1691 return TokError("unexpected token in '.else' directive");
1695 if (TheCondState.TheCond != AsmCond::IfCond &&
1696 TheCondState.TheCond != AsmCond::ElseIfCond)
1697 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1699 TheCondState.TheCond = AsmCond::ElseCond;
1700 bool LastIgnoreState = false;
1701 if (!TheCondStack.empty())
1702 LastIgnoreState = TheCondStack.back().Ignore;
1703 if (LastIgnoreState || TheCondState.CondMet)
1704 TheCondState.Ignore = true;
1706 TheCondState.Ignore = false;
1711 /// ParseDirectiveEndIf
1713 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1714 if (Lexer.isNot(AsmToken::EndOfStatement))
1715 return TokError("unexpected token in '.endif' directive");
1719 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1720 TheCondStack.empty())
1721 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1723 if (!TheCondStack.empty()) {
1724 TheCondState = TheCondStack.back();
1725 TheCondStack.pop_back();
1731 /// ParseDirectiveFile
1732 /// ::= .file [number] string
1733 bool AsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1734 // FIXME: I'm not sure what this is.
1735 int64_t FileNumber = -1;
1736 if (Lexer.is(AsmToken::Integer)) {
1737 FileNumber = getTok().getIntVal();
1741 return TokError("file number less than one");
1744 if (Lexer.isNot(AsmToken::String))
1745 return TokError("unexpected token in '.file' directive");
1747 StringRef Filename = getTok().getString();
1748 Filename = Filename.substr(1, Filename.size()-2);
1751 if (Lexer.isNot(AsmToken::EndOfStatement))
1752 return TokError("unexpected token in '.file' directive");
1754 if (FileNumber == -1)
1755 Out.EmitFileDirective(Filename);
1757 Out.EmitDwarfFileDirective(FileNumber, Filename);
1762 /// ParseDirectiveLine
1763 /// ::= .line [number]
1764 bool AsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1765 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1766 if (Lexer.isNot(AsmToken::Integer))
1767 return TokError("unexpected token in '.line' directive");
1769 int64_t LineNumber = getTok().getIntVal();
1773 // FIXME: Do something with the .line.
1776 if (Lexer.isNot(AsmToken::EndOfStatement))
1777 return TokError("unexpected token in '.file' directive");
1783 /// ParseDirectiveLoc
1784 /// ::= .loc number [number [number]]
1785 bool AsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1786 if (Lexer.isNot(AsmToken::Integer))
1787 return TokError("unexpected token in '.loc' directive");
1789 // FIXME: What are these fields?
1790 int64_t FileNumber = getTok().getIntVal();
1792 // FIXME: Validate file.
1795 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1796 if (Lexer.isNot(AsmToken::Integer))
1797 return TokError("unexpected token in '.loc' directive");
1799 int64_t Param2 = getTok().getIntVal();
1803 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1804 if (Lexer.isNot(AsmToken::Integer))
1805 return TokError("unexpected token in '.loc' directive");
1807 int64_t Param3 = getTok().getIntVal();
1811 // FIXME: Do something with the .loc.
1815 if (Lexer.isNot(AsmToken::EndOfStatement))
1816 return TokError("unexpected token in '.file' directive");