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 SMLoc Loc = getTok().getLoc();
219 int64_t IntVal = getTok().getIntVal();
220 Res = MCConstantExpr::Create(IntVal, getContext());
221 EndLoc = Lexer.getLoc();
223 // Look for 'b' or 'f' following an Integer as a directional label
224 if (Lexer.getKind() == AsmToken::Identifier) {
225 StringRef IDVal = getTok().getString();
226 if (IDVal == "f" || IDVal == "b"){
227 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
228 IDVal == "f" ? 1 : 0);
229 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
231 if(IDVal == "b" && Sym->isUndefined())
232 return Error(Loc, "invalid reference to undefined symbol");
233 EndLoc = Lexer.getLoc();
234 Lex(); // Eat identifier.
239 case AsmToken::Dot: {
240 // This is a '.' reference, which references the current PC. Emit a
241 // temporary label to the streamer and refer to it.
242 MCSymbol *Sym = Ctx.CreateTempSymbol();
244 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
245 EndLoc = Lexer.getLoc();
246 Lex(); // Eat identifier.
250 case AsmToken::LParen:
251 Lex(); // Eat the '('.
252 return ParseParenExpr(Res, EndLoc);
253 case AsmToken::Minus:
254 Lex(); // Eat the operator.
255 if (ParsePrimaryExpr(Res, EndLoc))
257 Res = MCUnaryExpr::CreateMinus(Res, getContext());
260 Lex(); // Eat the operator.
261 if (ParsePrimaryExpr(Res, EndLoc))
263 Res = MCUnaryExpr::CreatePlus(Res, getContext());
265 case AsmToken::Tilde:
266 Lex(); // Eat the operator.
267 if (ParsePrimaryExpr(Res, EndLoc))
269 Res = MCUnaryExpr::CreateNot(Res, getContext());
274 bool AsmParser::ParseExpression(const MCExpr *&Res) {
276 return ParseExpression(Res, EndLoc);
279 /// ParseExpression - Parse an expression and return it.
281 /// expr ::= expr +,- expr -> lowest.
282 /// expr ::= expr |,^,&,! expr -> middle.
283 /// expr ::= expr *,/,%,<<,>> expr -> highest.
284 /// expr ::= primaryexpr
286 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
287 // Parse the expression.
289 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
292 // Try to constant fold it up front, if possible.
294 if (Res->EvaluateAsAbsolute(Value))
295 Res = MCConstantExpr::Create(Value, getContext());
300 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
302 return ParseParenExpr(Res, EndLoc) ||
303 ParseBinOpRHS(1, Res, EndLoc);
306 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
309 SMLoc StartLoc = Lexer.getLoc();
310 if (ParseExpression(Expr))
313 if (!Expr->EvaluateAsAbsolute(Res))
314 return Error(StartLoc, "expected absolute expression");
319 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
320 MCBinaryExpr::Opcode &Kind) {
323 return 0; // not a binop.
325 // Lowest Precedence: &&, ||
326 case AsmToken::AmpAmp:
327 Kind = MCBinaryExpr::LAnd;
329 case AsmToken::PipePipe:
330 Kind = MCBinaryExpr::LOr;
333 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
335 Kind = MCBinaryExpr::Add;
337 case AsmToken::Minus:
338 Kind = MCBinaryExpr::Sub;
340 case AsmToken::EqualEqual:
341 Kind = MCBinaryExpr::EQ;
343 case AsmToken::ExclaimEqual:
344 case AsmToken::LessGreater:
345 Kind = MCBinaryExpr::NE;
348 Kind = MCBinaryExpr::LT;
350 case AsmToken::LessEqual:
351 Kind = MCBinaryExpr::LTE;
353 case AsmToken::Greater:
354 Kind = MCBinaryExpr::GT;
356 case AsmToken::GreaterEqual:
357 Kind = MCBinaryExpr::GTE;
360 // Intermediate Precedence: |, &, ^
362 // FIXME: gas seems to support '!' as an infix operator?
364 Kind = MCBinaryExpr::Or;
366 case AsmToken::Caret:
367 Kind = MCBinaryExpr::Xor;
370 Kind = MCBinaryExpr::And;
373 // Highest Precedence: *, /, %, <<, >>
375 Kind = MCBinaryExpr::Mul;
377 case AsmToken::Slash:
378 Kind = MCBinaryExpr::Div;
380 case AsmToken::Percent:
381 Kind = MCBinaryExpr::Mod;
383 case AsmToken::LessLess:
384 Kind = MCBinaryExpr::Shl;
386 case AsmToken::GreaterGreater:
387 Kind = MCBinaryExpr::Shr;
393 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
394 /// Res contains the LHS of the expression on input.
395 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
398 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
399 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
401 // If the next token is lower precedence than we are allowed to eat, return
402 // successfully with what we ate already.
403 if (TokPrec < Precedence)
408 // Eat the next primary expression.
410 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
412 // If BinOp binds less tightly with RHS than the operator after RHS, let
413 // the pending operator take RHS as its LHS.
414 MCBinaryExpr::Opcode Dummy;
415 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
416 if (TokPrec < NextTokPrec) {
417 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
420 // Merge LHS and RHS according to operator.
421 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
429 /// ::= EndOfStatement
430 /// ::= Label* Directive ...Operands... EndOfStatement
431 /// ::= Label* Identifier OperandList* EndOfStatement
432 bool AsmParser::ParseStatement() {
433 if (Lexer.is(AsmToken::EndOfStatement)) {
438 // Statements always start with an identifier.
439 AsmToken ID = getTok();
440 SMLoc IDLoc = ID.getLoc();
442 int64_t LocalLabelVal = -1;
443 // GUESS allow an integer followed by a ':' as a directional local label
444 if (Lexer.is(AsmToken::Integer)) {
445 LocalLabelVal = getTok().getIntVal();
446 if (LocalLabelVal < 0) {
447 if (!TheCondState.Ignore)
448 return TokError("unexpected token at start of statement");
452 IDVal = getTok().getString();
453 Lex(); // Consume the integer token to be used as an identifier token.
454 if (Lexer.getKind() != AsmToken::Colon) {
455 if (!TheCondState.Ignore)
456 return TokError("unexpected token at start of statement");
460 else if (ParseIdentifier(IDVal)) {
461 if (!TheCondState.Ignore)
462 return TokError("unexpected token at start of statement");
466 // Handle conditional assembly here before checking for skipping. We
467 // have to do this so that .endif isn't skipped in a ".if 0" block for
470 return ParseDirectiveIf(IDLoc);
471 if (IDVal == ".elseif")
472 return ParseDirectiveElseIf(IDLoc);
473 if (IDVal == ".else")
474 return ParseDirectiveElse(IDLoc);
475 if (IDVal == ".endif")
476 return ParseDirectiveEndIf(IDLoc);
478 // If we are in a ".if 0" block, ignore this statement.
479 if (TheCondState.Ignore) {
480 EatToEndOfStatement();
484 // FIXME: Recurse on local labels?
486 // See what kind of statement we have.
487 switch (Lexer.getKind()) {
488 case AsmToken::Colon: {
489 // identifier ':' -> Label.
492 // Diagnose attempt to use a variable as a label.
494 // FIXME: Diagnostics. Note the location of the definition as a label.
495 // FIXME: This doesn't diagnose assignment to a symbol which has been
496 // implicitly marked as external.
498 if (LocalLabelVal == -1)
499 Sym = CreateSymbol(IDVal);
501 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
502 if (!Sym->isUndefined() || Sym->isVariable())
503 return Error(IDLoc, "invalid symbol redefinition");
508 return ParseStatement();
511 case AsmToken::Equal:
512 // identifier '=' ... -> assignment statement
515 return ParseAssignment(IDVal);
517 default: // Normal instruction or directive.
521 // Otherwise, we have a normal instruction or directive.
522 if (IDVal[0] == '.') {
523 // FIXME: This should be driven based on a hash lookup and callback.
524 if (IDVal == ".section")
525 return ParseDirectiveDarwinSection();
526 if (IDVal == ".text")
527 // FIXME: This changes behavior based on the -static flag to the
529 return ParseDirectiveSectionSwitch("__TEXT", "__text",
530 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
531 if (IDVal == ".const")
532 return ParseDirectiveSectionSwitch("__TEXT", "__const");
533 if (IDVal == ".static_const")
534 return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
535 if (IDVal == ".cstring")
536 return ParseDirectiveSectionSwitch("__TEXT","__cstring",
537 MCSectionMachO::S_CSTRING_LITERALS);
538 if (IDVal == ".literal4")
539 return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
540 MCSectionMachO::S_4BYTE_LITERALS,
542 if (IDVal == ".literal8")
543 return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
544 MCSectionMachO::S_8BYTE_LITERALS,
546 if (IDVal == ".literal16")
547 return ParseDirectiveSectionSwitch("__TEXT","__literal16",
548 MCSectionMachO::S_16BYTE_LITERALS,
550 if (IDVal == ".constructor")
551 return ParseDirectiveSectionSwitch("__TEXT","__constructor");
552 if (IDVal == ".destructor")
553 return ParseDirectiveSectionSwitch("__TEXT","__destructor");
554 if (IDVal == ".fvmlib_init0")
555 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
556 if (IDVal == ".fvmlib_init1")
557 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
559 // FIXME: The assembler manual claims that this has the self modify code
560 // flag, at least on x86-32, but that does not appear to be correct.
561 if (IDVal == ".symbol_stub")
562 return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
563 MCSectionMachO::S_SYMBOL_STUBS |
564 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
565 // FIXME: Different on PPC and ARM.
567 // FIXME: PowerPC only?
568 if (IDVal == ".picsymbol_stub")
569 return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
570 MCSectionMachO::S_SYMBOL_STUBS |
571 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
573 if (IDVal == ".data")
574 return ParseDirectiveSectionSwitch("__DATA", "__data");
575 if (IDVal == ".static_data")
576 return ParseDirectiveSectionSwitch("__DATA", "__static_data");
578 // FIXME: The section names of these two are misspelled in the assembler
580 if (IDVal == ".non_lazy_symbol_pointer")
581 return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
582 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
584 if (IDVal == ".lazy_symbol_pointer")
585 return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
586 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
589 if (IDVal == ".dyld")
590 return ParseDirectiveSectionSwitch("__DATA", "__dyld");
591 if (IDVal == ".mod_init_func")
592 return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
593 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
595 if (IDVal == ".mod_term_func")
596 return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
597 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
599 if (IDVal == ".const_data")
600 return ParseDirectiveSectionSwitch("__DATA", "__const");
603 if (IDVal == ".objc_class")
604 return ParseDirectiveSectionSwitch("__OBJC", "__class",
605 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
606 if (IDVal == ".objc_meta_class")
607 return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
608 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
609 if (IDVal == ".objc_cat_cls_meth")
610 return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
611 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
612 if (IDVal == ".objc_cat_inst_meth")
613 return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
614 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
615 if (IDVal == ".objc_protocol")
616 return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
617 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
618 if (IDVal == ".objc_string_object")
619 return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
620 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
621 if (IDVal == ".objc_cls_meth")
622 return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
623 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
624 if (IDVal == ".objc_inst_meth")
625 return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
626 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
627 if (IDVal == ".objc_cls_refs")
628 return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
629 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
630 MCSectionMachO::S_LITERAL_POINTERS,
632 if (IDVal == ".objc_message_refs")
633 return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
634 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
635 MCSectionMachO::S_LITERAL_POINTERS,
637 if (IDVal == ".objc_symbols")
638 return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
639 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
640 if (IDVal == ".objc_category")
641 return ParseDirectiveSectionSwitch("__OBJC", "__category",
642 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
643 if (IDVal == ".objc_class_vars")
644 return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
645 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
646 if (IDVal == ".objc_instance_vars")
647 return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
648 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
649 if (IDVal == ".objc_module_info")
650 return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
651 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
652 if (IDVal == ".objc_class_names")
653 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
654 MCSectionMachO::S_CSTRING_LITERALS);
655 if (IDVal == ".objc_meth_var_types")
656 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
657 MCSectionMachO::S_CSTRING_LITERALS);
658 if (IDVal == ".objc_meth_var_names")
659 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
660 MCSectionMachO::S_CSTRING_LITERALS);
661 if (IDVal == ".objc_selector_strs")
662 return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
663 MCSectionMachO::S_CSTRING_LITERALS);
665 if (IDVal == ".tdata")
666 return ParseDirectiveSectionSwitch("__DATA", "__thread_data",
667 MCSectionMachO::S_THREAD_LOCAL_REGULAR);
669 return ParseDirectiveSectionSwitch("__DATA", "__thread_vars",
670 MCSectionMachO::S_THREAD_LOCAL_VARIABLES);
671 if (IDVal == ".thread_init_func")
672 return ParseDirectiveSectionSwitch("__DATA", "__thread_init",
673 MCSectionMachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS);
675 // Assembler features
677 return ParseDirectiveSet();
681 if (IDVal == ".ascii")
682 return ParseDirectiveAscii(false);
683 if (IDVal == ".asciz")
684 return ParseDirectiveAscii(true);
686 if (IDVal == ".byte")
687 return ParseDirectiveValue(1);
688 if (IDVal == ".short")
689 return ParseDirectiveValue(2);
690 if (IDVal == ".long")
691 return ParseDirectiveValue(4);
692 if (IDVal == ".quad")
693 return ParseDirectiveValue(8);
695 // FIXME: Target hooks for IsPow2.
696 if (IDVal == ".align")
697 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
698 if (IDVal == ".align32")
699 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
700 if (IDVal == ".balign")
701 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
702 if (IDVal == ".balignw")
703 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
704 if (IDVal == ".balignl")
705 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
706 if (IDVal == ".p2align")
707 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
708 if (IDVal == ".p2alignw")
709 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
710 if (IDVal == ".p2alignl")
711 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
714 return ParseDirectiveOrg();
716 if (IDVal == ".fill")
717 return ParseDirectiveFill();
718 if (IDVal == ".space")
719 return ParseDirectiveSpace();
721 // Symbol attribute directives
723 if (IDVal == ".globl" || IDVal == ".global")
724 return ParseDirectiveSymbolAttribute(MCSA_Global);
725 if (IDVal == ".hidden")
726 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
727 if (IDVal == ".indirect_symbol")
728 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
729 if (IDVal == ".internal")
730 return ParseDirectiveSymbolAttribute(MCSA_Internal);
731 if (IDVal == ".lazy_reference")
732 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
733 if (IDVal == ".no_dead_strip")
734 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
735 if (IDVal == ".private_extern")
736 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
737 if (IDVal == ".protected")
738 return ParseDirectiveSymbolAttribute(MCSA_Protected);
739 if (IDVal == ".reference")
740 return ParseDirectiveSymbolAttribute(MCSA_Reference);
741 if (IDVal == ".weak")
742 return ParseDirectiveSymbolAttribute(MCSA_Weak);
743 if (IDVal == ".weak_definition")
744 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
745 if (IDVal == ".weak_reference")
746 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
748 if (IDVal == ".comm")
749 return ParseDirectiveComm(/*IsLocal=*/false);
750 if (IDVal == ".lcomm")
751 return ParseDirectiveComm(/*IsLocal=*/true);
752 if (IDVal == ".zerofill")
753 return ParseDirectiveDarwinZerofill();
754 if (IDVal == ".desc")
755 return ParseDirectiveDarwinSymbolDesc();
756 if (IDVal == ".lsym")
757 return ParseDirectiveDarwinLsym();
758 if (IDVal == ".tbss")
759 return ParseDirectiveDarwinTBSS();
761 if (IDVal == ".subsections_via_symbols")
762 return ParseDirectiveDarwinSubsectionsViaSymbols();
763 if (IDVal == ".abort")
764 return ParseDirectiveAbort();
765 if (IDVal == ".include")
766 return ParseDirectiveInclude();
767 if (IDVal == ".dump")
768 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
769 if (IDVal == ".load")
770 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
772 // Look up the handler in the handler table,
773 bool(AsmParser::*Handler)(StringRef, SMLoc) = DirectiveMap[IDVal];
775 return (this->*Handler)(IDVal, IDLoc);
777 // Target hook for parsing target specific directives.
778 if (!getTargetParser().ParseDirective(ID))
781 Warning(IDLoc, "ignoring directive for now");
782 EatToEndOfStatement();
786 // Canonicalize the opcode to lower case.
787 SmallString<128> Opcode;
788 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
789 Opcode.push_back(tolower(IDVal[i]));
791 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
792 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
794 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
795 HadError = TokError("unexpected token in argument list");
797 // If parsing succeeded, match the instruction.
800 if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
801 // Emit the instruction on success.
802 Out.EmitInstruction(Inst);
804 // Otherwise emit a diagnostic about the match failure and set the error
807 // FIXME: We should give nicer diagnostics about the exact failure.
808 Error(IDLoc, "unrecognized instruction");
813 // If there was no error, consume the end-of-statement token. Otherwise this
814 // will be done by our caller.
818 // Free any parsed operands.
819 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
820 delete ParsedOperands[i];
825 bool AsmParser::ParseAssignment(const StringRef &Name) {
826 // FIXME: Use better location, we should use proper tokens.
827 SMLoc EqualLoc = Lexer.getLoc();
830 SMLoc StartLoc = Lexer.getLoc();
831 if (ParseExpression(Value))
834 if (Lexer.isNot(AsmToken::EndOfStatement))
835 return TokError("unexpected token in assignment");
837 // Eat the end of statement marker.
840 // Validate that the LHS is allowed to be a variable (either it has not been
841 // used as a symbol, or it is an absolute symbol).
842 MCSymbol *Sym = getContext().LookupSymbol(Name);
844 // Diagnose assignment to a label.
846 // FIXME: Diagnostics. Note the location of the definition as a label.
847 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
848 if (Sym->isUndefined() && !Sym->isUsedInExpr())
849 ; // Allow redefinitions of undefined symbols only used in directives.
850 else if (!Sym->isUndefined() && !Sym->isAbsolute())
851 return Error(EqualLoc, "redefinition of '" + Name + "'");
852 else if (!Sym->isVariable())
853 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
854 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
855 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
858 Sym = CreateSymbol(Name);
860 // FIXME: Handle '.'.
862 Sym->setUsedInExpr(true);
864 // Do the assignment.
865 Out.EmitAssignment(Sym, Value);
873 bool AsmParser::ParseIdentifier(StringRef &Res) {
874 if (Lexer.isNot(AsmToken::Identifier) &&
875 Lexer.isNot(AsmToken::String))
878 Res = getTok().getIdentifier();
880 Lex(); // Consume the identifier token.
885 /// ParseDirectiveSet:
886 /// ::= .set identifier ',' expression
887 bool AsmParser::ParseDirectiveSet() {
890 if (ParseIdentifier(Name))
891 return TokError("expected identifier after '.set' directive");
893 if (Lexer.isNot(AsmToken::Comma))
894 return TokError("unexpected token in '.set'");
897 return ParseAssignment(Name);
900 /// ParseDirectiveSection:
901 /// ::= .section identifier (',' identifier)*
902 /// FIXME: This should actually parse out the segment, section, attributes and
903 /// sizeof_stub fields.
904 bool AsmParser::ParseDirectiveDarwinSection() {
905 SMLoc Loc = Lexer.getLoc();
907 StringRef SectionName;
908 if (ParseIdentifier(SectionName))
909 return Error(Loc, "expected identifier after '.section' directive");
911 // Verify there is a following comma.
912 if (!Lexer.is(AsmToken::Comma))
913 return TokError("unexpected token in '.section' directive");
915 std::string SectionSpec = SectionName;
918 // Add all the tokens until the end of the line, ParseSectionSpecifier will
920 StringRef EOL = Lexer.LexUntilEndOfStatement();
921 SectionSpec.append(EOL.begin(), EOL.end());
924 if (Lexer.isNot(AsmToken::EndOfStatement))
925 return TokError("unexpected token in '.section' directive");
929 StringRef Segment, Section;
930 unsigned TAA, StubSize;
931 std::string ErrorStr =
932 MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
935 if (!ErrorStr.empty())
936 return Error(Loc, ErrorStr.c_str());
938 // FIXME: Arch specific.
939 bool isText = Segment == "__TEXT"; // FIXME: Hack.
940 Out.SwitchSection(Ctx.getMachOSection(Segment, Section, TAA, StubSize,
941 isText ? SectionKind::getText()
942 : SectionKind::getDataRel()));
946 /// ParseDirectiveSectionSwitch -
947 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
949 unsigned TAA, unsigned Align,
951 if (Lexer.isNot(AsmToken::EndOfStatement))
952 return TokError("unexpected token in section switching directive");
955 // FIXME: Arch specific.
956 bool isText = StringRef(Segment) == "__TEXT"; // FIXME: Hack.
957 Out.SwitchSection(Ctx.getMachOSection(Segment, Section, TAA, StubSize,
958 isText ? SectionKind::getText()
959 : SectionKind::getDataRel()));
961 // Set the implicit alignment, if any.
963 // FIXME: This isn't really what 'as' does; I think it just uses the implicit
964 // alignment on the section (e.g., if one manually inserts bytes into the
965 // section, then just issueing the section switch directive will not realign
966 // the section. However, this is arguably more reasonable behavior, and there
967 // is no good reason for someone to intentionally emit incorrectly sized
968 // values into the implicitly aligned sections.
970 Out.EmitValueToAlignment(Align, 0, 1, 0);
975 bool AsmParser::ParseEscapedString(std::string &Data) {
976 assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
979 StringRef Str = getTok().getStringContents();
980 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
981 if (Str[i] != '\\') {
986 // Recognize escaped characters. Note that this escape semantics currently
987 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
990 return TokError("unexpected backslash at end of string");
992 // Recognize octal sequences.
993 if ((unsigned) (Str[i] - '0') <= 7) {
994 // Consume up to three octal characters.
995 unsigned Value = Str[i] - '0';
997 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
999 Value = Value * 8 + (Str[i] - '0');
1001 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1003 Value = Value * 8 + (Str[i] - '0');
1008 return TokError("invalid octal escape sequence (out of range)");
1010 Data += (unsigned char) Value;
1014 // Otherwise recognize individual escapes.
1017 // Just reject invalid escape sequences for now.
1018 return TokError("invalid escape sequence (unrecognized character)");
1020 case 'b': Data += '\b'; break;
1021 case 'f': Data += '\f'; break;
1022 case 'n': Data += '\n'; break;
1023 case 'r': Data += '\r'; break;
1024 case 't': Data += '\t'; break;
1025 case '"': Data += '"'; break;
1026 case '\\': Data += '\\'; break;
1033 /// ParseDirectiveAscii:
1034 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1035 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1036 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1038 if (Lexer.isNot(AsmToken::String))
1039 return TokError("expected string in '.ascii' or '.asciz' directive");
1042 if (ParseEscapedString(Data))
1045 Out.EmitBytes(Data, DEFAULT_ADDRSPACE);
1047 Out.EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1051 if (Lexer.is(AsmToken::EndOfStatement))
1054 if (Lexer.isNot(AsmToken::Comma))
1055 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1064 /// ParseDirectiveValue
1065 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1066 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1067 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1069 const MCExpr *Value;
1070 SMLoc ATTRIBUTE_UNUSED StartLoc = Lexer.getLoc();
1071 if (ParseExpression(Value))
1074 Out.EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1076 if (Lexer.is(AsmToken::EndOfStatement))
1079 // FIXME: Improve diagnostic.
1080 if (Lexer.isNot(AsmToken::Comma))
1081 return TokError("unexpected token in directive");
1090 /// ParseDirectiveSpace
1091 /// ::= .space expression [ , expression ]
1092 bool AsmParser::ParseDirectiveSpace() {
1094 if (ParseAbsoluteExpression(NumBytes))
1097 int64_t FillExpr = 0;
1098 bool HasFillExpr = false;
1099 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1100 if (Lexer.isNot(AsmToken::Comma))
1101 return TokError("unexpected token in '.space' directive");
1104 if (ParseAbsoluteExpression(FillExpr))
1109 if (Lexer.isNot(AsmToken::EndOfStatement))
1110 return TokError("unexpected token in '.space' directive");
1116 return TokError("invalid number of bytes in '.space' directive");
1118 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1119 Out.EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1124 /// ParseDirectiveFill
1125 /// ::= .fill expression , expression , expression
1126 bool AsmParser::ParseDirectiveFill() {
1128 if (ParseAbsoluteExpression(NumValues))
1131 if (Lexer.isNot(AsmToken::Comma))
1132 return TokError("unexpected token in '.fill' directive");
1136 if (ParseAbsoluteExpression(FillSize))
1139 if (Lexer.isNot(AsmToken::Comma))
1140 return TokError("unexpected token in '.fill' directive");
1144 if (ParseAbsoluteExpression(FillExpr))
1147 if (Lexer.isNot(AsmToken::EndOfStatement))
1148 return TokError("unexpected token in '.fill' directive");
1152 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1153 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1155 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1156 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), FillSize,
1162 /// ParseDirectiveOrg
1163 /// ::= .org expression [ , expression ]
1164 bool AsmParser::ParseDirectiveOrg() {
1165 const MCExpr *Offset;
1166 SMLoc StartLoc = Lexer.getLoc();
1167 if (ParseExpression(Offset))
1170 // Parse optional fill expression.
1171 int64_t FillExpr = 0;
1172 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1173 if (Lexer.isNot(AsmToken::Comma))
1174 return TokError("unexpected token in '.org' directive");
1177 if (ParseAbsoluteExpression(FillExpr))
1180 if (Lexer.isNot(AsmToken::EndOfStatement))
1181 return TokError("unexpected token in '.org' directive");
1186 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1187 // has to be relative to the current section.
1188 Out.EmitValueToOffset(Offset, FillExpr);
1193 /// ParseDirectiveAlign
1194 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1195 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1196 SMLoc AlignmentLoc = Lexer.getLoc();
1198 if (ParseAbsoluteExpression(Alignment))
1202 bool HasFillExpr = false;
1203 int64_t FillExpr = 0;
1204 int64_t MaxBytesToFill = 0;
1205 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1206 if (Lexer.isNot(AsmToken::Comma))
1207 return TokError("unexpected token in directive");
1210 // The fill expression can be omitted while specifying a maximum number of
1211 // alignment bytes, e.g:
1213 if (Lexer.isNot(AsmToken::Comma)) {
1215 if (ParseAbsoluteExpression(FillExpr))
1219 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1220 if (Lexer.isNot(AsmToken::Comma))
1221 return TokError("unexpected token in directive");
1224 MaxBytesLoc = Lexer.getLoc();
1225 if (ParseAbsoluteExpression(MaxBytesToFill))
1228 if (Lexer.isNot(AsmToken::EndOfStatement))
1229 return TokError("unexpected token in directive");
1238 // Compute alignment in bytes.
1240 // FIXME: Diagnose overflow.
1241 if (Alignment >= 32) {
1242 Error(AlignmentLoc, "invalid alignment value");
1246 Alignment = 1ULL << Alignment;
1249 // Diagnose non-sensical max bytes to align.
1250 if (MaxBytesLoc.isValid()) {
1251 if (MaxBytesToFill < 1) {
1252 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1253 "many bytes, ignoring maximum bytes expression");
1257 if (MaxBytesToFill >= Alignment) {
1258 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1264 // Check whether we should use optimal code alignment for this .align
1267 // FIXME: This should be using a target hook.
1268 bool UseCodeAlign = false;
1269 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1270 Out.getCurrentSection()))
1271 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1272 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1273 ValueSize == 1 && UseCodeAlign) {
1274 Out.EmitCodeAlignment(Alignment, MaxBytesToFill);
1276 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1277 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1283 /// ParseDirectiveSymbolAttribute
1284 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1285 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1286 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1290 if (ParseIdentifier(Name))
1291 return TokError("expected identifier in directive");
1293 MCSymbol *Sym = CreateSymbol(Name);
1295 Out.EmitSymbolAttribute(Sym, Attr);
1297 if (Lexer.is(AsmToken::EndOfStatement))
1300 if (Lexer.isNot(AsmToken::Comma))
1301 return TokError("unexpected token in directive");
1310 /// ParseDirectiveDarwinSymbolDesc
1311 /// ::= .desc identifier , expression
1312 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1314 if (ParseIdentifier(Name))
1315 return TokError("expected identifier in directive");
1317 // Handle the identifier as the key symbol.
1318 MCSymbol *Sym = CreateSymbol(Name);
1320 if (Lexer.isNot(AsmToken::Comma))
1321 return TokError("unexpected token in '.desc' directive");
1324 SMLoc DescLoc = Lexer.getLoc();
1326 if (ParseAbsoluteExpression(DescValue))
1329 if (Lexer.isNot(AsmToken::EndOfStatement))
1330 return TokError("unexpected token in '.desc' directive");
1334 // Set the n_desc field of this Symbol to this DescValue
1335 Out.EmitSymbolDesc(Sym, DescValue);
1340 /// ParseDirectiveComm
1341 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1342 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1343 SMLoc IDLoc = Lexer.getLoc();
1345 if (ParseIdentifier(Name))
1346 return TokError("expected identifier in directive");
1348 // Handle the identifier as the key symbol.
1349 MCSymbol *Sym = CreateSymbol(Name);
1351 if (Lexer.isNot(AsmToken::Comma))
1352 return TokError("unexpected token in directive");
1356 SMLoc SizeLoc = Lexer.getLoc();
1357 if (ParseAbsoluteExpression(Size))
1360 int64_t Pow2Alignment = 0;
1361 SMLoc Pow2AlignmentLoc;
1362 if (Lexer.is(AsmToken::Comma)) {
1364 Pow2AlignmentLoc = Lexer.getLoc();
1365 if (ParseAbsoluteExpression(Pow2Alignment))
1368 // If this target takes alignments in bytes (not log) validate and convert.
1369 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1370 if (!isPowerOf2_64(Pow2Alignment))
1371 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1372 Pow2Alignment = Log2_64(Pow2Alignment);
1376 if (Lexer.isNot(AsmToken::EndOfStatement))
1377 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1381 // NOTE: a size of zero for a .comm should create a undefined symbol
1382 // but a size of .lcomm creates a bss symbol of size zero.
1384 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1385 "be less than zero");
1387 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1388 // may internally end up wanting an alignment in bytes.
1389 // FIXME: Diagnose overflow.
1390 if (Pow2Alignment < 0)
1391 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1392 "alignment, can't be less than zero");
1394 if (!Sym->isUndefined())
1395 return Error(IDLoc, "invalid symbol redefinition");
1397 // '.lcomm' is equivalent to '.zerofill'.
1398 // Create the Symbol as a common or local common with Size and Pow2Alignment
1400 Out.EmitZerofill(Ctx.getMachOSection("__DATA", "__bss",
1401 MCSectionMachO::S_ZEROFILL, 0,
1402 SectionKind::getBSS()),
1403 Sym, Size, 1 << Pow2Alignment);
1407 Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1411 /// ParseDirectiveDarwinZerofill
1412 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1413 /// , align_expression ]]
1414 bool AsmParser::ParseDirectiveDarwinZerofill() {
1416 if (ParseIdentifier(Segment))
1417 return TokError("expected segment name after '.zerofill' directive");
1419 if (Lexer.isNot(AsmToken::Comma))
1420 return TokError("unexpected token in directive");
1424 if (ParseIdentifier(Section))
1425 return TokError("expected section name after comma in '.zerofill' "
1428 // If this is the end of the line all that was wanted was to create the
1429 // the section but with no symbol.
1430 if (Lexer.is(AsmToken::EndOfStatement)) {
1431 // Create the zerofill section but no symbol
1432 Out.EmitZerofill(Ctx.getMachOSection(Segment, Section,
1433 MCSectionMachO::S_ZEROFILL, 0,
1434 SectionKind::getBSS()));
1438 if (Lexer.isNot(AsmToken::Comma))
1439 return TokError("unexpected token in directive");
1442 SMLoc IDLoc = Lexer.getLoc();
1444 if (ParseIdentifier(IDStr))
1445 return TokError("expected identifier in directive");
1447 // handle the identifier as the key symbol.
1448 MCSymbol *Sym = CreateSymbol(IDStr);
1450 if (Lexer.isNot(AsmToken::Comma))
1451 return TokError("unexpected token in directive");
1455 SMLoc SizeLoc = Lexer.getLoc();
1456 if (ParseAbsoluteExpression(Size))
1459 int64_t Pow2Alignment = 0;
1460 SMLoc Pow2AlignmentLoc;
1461 if (Lexer.is(AsmToken::Comma)) {
1463 Pow2AlignmentLoc = Lexer.getLoc();
1464 if (ParseAbsoluteExpression(Pow2Alignment))
1468 if (Lexer.isNot(AsmToken::EndOfStatement))
1469 return TokError("unexpected token in '.zerofill' directive");
1474 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1477 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1478 // may internally end up wanting an alignment in bytes.
1479 // FIXME: Diagnose overflow.
1480 if (Pow2Alignment < 0)
1481 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1482 "can't be less than zero");
1484 if (!Sym->isUndefined())
1485 return Error(IDLoc, "invalid symbol redefinition");
1487 // Create the zerofill Symbol with Size and Pow2Alignment
1489 // FIXME: Arch specific.
1490 Out.EmitZerofill(Ctx.getMachOSection(Segment, Section,
1491 MCSectionMachO::S_ZEROFILL, 0,
1492 SectionKind::getBSS()),
1493 Sym, Size, 1 << Pow2Alignment);
1498 /// ParseDirectiveDarwinTBSS
1499 /// ::= .tbss identifier, size, align
1500 bool AsmParser::ParseDirectiveDarwinTBSS() {
1501 SMLoc IDLoc = Lexer.getLoc();
1503 if (ParseIdentifier(Name))
1504 return TokError("expected identifier in directive");
1506 // Handle the identifier as the key symbol.
1507 MCSymbol *Sym = CreateSymbol(Name);
1509 if (Lexer.isNot(AsmToken::Comma))
1510 return TokError("unexpected token in directive");
1514 SMLoc SizeLoc = Lexer.getLoc();
1515 if (ParseAbsoluteExpression(Size))
1518 int64_t Pow2Alignment = 0;
1519 SMLoc Pow2AlignmentLoc;
1520 if (Lexer.is(AsmToken::Comma)) {
1522 Pow2AlignmentLoc = Lexer.getLoc();
1523 if (ParseAbsoluteExpression(Pow2Alignment))
1527 if (Lexer.isNot(AsmToken::EndOfStatement))
1528 return TokError("unexpected token in '.tbss' directive");
1533 return Error(SizeLoc, "invalid '.tbss' directive size, can't be less than"
1536 // FIXME: Diagnose overflow.
1537 if (Pow2Alignment < 0)
1538 return Error(Pow2AlignmentLoc, "invalid '.tbss' alignment, can't be less"
1541 if (!Sym->isUndefined())
1542 return Error(IDLoc, "invalid symbol redefinition");
1544 Out.EmitTBSSSymbol(Ctx.getMachOSection("__DATA", "__thread_bss",
1545 MCSectionMachO::S_THREAD_LOCAL_ZEROFILL,
1546 0, SectionKind::getThreadBSS()),
1547 Sym, Size, 1 << Pow2Alignment);
1552 /// ParseDirectiveDarwinSubsectionsViaSymbols
1553 /// ::= .subsections_via_symbols
1554 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1555 if (Lexer.isNot(AsmToken::EndOfStatement))
1556 return TokError("unexpected token in '.subsections_via_symbols' directive");
1560 Out.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1565 /// ParseDirectiveAbort
1566 /// ::= .abort [ "abort_string" ]
1567 bool AsmParser::ParseDirectiveAbort() {
1568 // FIXME: Use loc from directive.
1569 SMLoc Loc = Lexer.getLoc();
1572 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1573 if (Lexer.isNot(AsmToken::String))
1574 return TokError("expected string in '.abort' directive");
1576 Str = getTok().getString();
1581 if (Lexer.isNot(AsmToken::EndOfStatement))
1582 return TokError("unexpected token in '.abort' directive");
1586 // FIXME: Handle here.
1588 Error(Loc, ".abort detected. Assembly stopping.");
1590 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1595 /// ParseDirectiveLsym
1596 /// ::= .lsym identifier , expression
1597 bool AsmParser::ParseDirectiveDarwinLsym() {
1599 if (ParseIdentifier(Name))
1600 return TokError("expected identifier in directive");
1602 // Handle the identifier as the key symbol.
1603 MCSymbol *Sym = CreateSymbol(Name);
1605 if (Lexer.isNot(AsmToken::Comma))
1606 return TokError("unexpected token in '.lsym' directive");
1609 const MCExpr *Value;
1610 SMLoc StartLoc = Lexer.getLoc();
1611 if (ParseExpression(Value))
1614 if (Lexer.isNot(AsmToken::EndOfStatement))
1615 return TokError("unexpected token in '.lsym' directive");
1619 // We don't currently support this directive.
1621 // FIXME: Diagnostic location!
1623 return TokError("directive '.lsym' is unsupported");
1626 /// ParseDirectiveInclude
1627 /// ::= .include "filename"
1628 bool AsmParser::ParseDirectiveInclude() {
1629 if (Lexer.isNot(AsmToken::String))
1630 return TokError("expected string in '.include' directive");
1632 std::string Filename = getTok().getString();
1633 SMLoc IncludeLoc = Lexer.getLoc();
1636 if (Lexer.isNot(AsmToken::EndOfStatement))
1637 return TokError("unexpected token in '.include' directive");
1639 // Strip the quotes.
1640 Filename = Filename.substr(1, Filename.size()-2);
1642 // Attempt to switch the lexer to the included file before consuming the end
1643 // of statement to avoid losing it when we switch.
1644 if (EnterIncludeFile(Filename)) {
1645 PrintMessage(IncludeLoc,
1646 "Could not find include file '" + Filename + "'",
1654 /// ParseDirectiveDarwinDumpOrLoad
1655 /// ::= ( .dump | .load ) "filename"
1656 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1657 if (Lexer.isNot(AsmToken::String))
1658 return TokError("expected string in '.dump' or '.load' directive");
1662 if (Lexer.isNot(AsmToken::EndOfStatement))
1663 return TokError("unexpected token in '.dump' or '.load' directive");
1667 // FIXME: If/when .dump and .load are implemented they will be done in the
1668 // the assembly parser and not have any need for an MCStreamer API.
1670 Warning(IDLoc, "ignoring directive .dump for now");
1672 Warning(IDLoc, "ignoring directive .load for now");
1677 /// ParseDirectiveIf
1678 /// ::= .if expression
1679 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1680 TheCondStack.push_back(TheCondState);
1681 TheCondState.TheCond = AsmCond::IfCond;
1682 if(TheCondState.Ignore) {
1683 EatToEndOfStatement();
1687 if (ParseAbsoluteExpression(ExprValue))
1690 if (Lexer.isNot(AsmToken::EndOfStatement))
1691 return TokError("unexpected token in '.if' directive");
1695 TheCondState.CondMet = ExprValue;
1696 TheCondState.Ignore = !TheCondState.CondMet;
1702 /// ParseDirectiveElseIf
1703 /// ::= .elseif expression
1704 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1705 if (TheCondState.TheCond != AsmCond::IfCond &&
1706 TheCondState.TheCond != AsmCond::ElseIfCond)
1707 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1709 TheCondState.TheCond = AsmCond::ElseIfCond;
1711 bool LastIgnoreState = false;
1712 if (!TheCondStack.empty())
1713 LastIgnoreState = TheCondStack.back().Ignore;
1714 if (LastIgnoreState || TheCondState.CondMet) {
1715 TheCondState.Ignore = true;
1716 EatToEndOfStatement();
1720 if (ParseAbsoluteExpression(ExprValue))
1723 if (Lexer.isNot(AsmToken::EndOfStatement))
1724 return TokError("unexpected token in '.elseif' directive");
1727 TheCondState.CondMet = ExprValue;
1728 TheCondState.Ignore = !TheCondState.CondMet;
1734 /// ParseDirectiveElse
1736 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1737 if (Lexer.isNot(AsmToken::EndOfStatement))
1738 return TokError("unexpected token in '.else' directive");
1742 if (TheCondState.TheCond != AsmCond::IfCond &&
1743 TheCondState.TheCond != AsmCond::ElseIfCond)
1744 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1746 TheCondState.TheCond = AsmCond::ElseCond;
1747 bool LastIgnoreState = false;
1748 if (!TheCondStack.empty())
1749 LastIgnoreState = TheCondStack.back().Ignore;
1750 if (LastIgnoreState || TheCondState.CondMet)
1751 TheCondState.Ignore = true;
1753 TheCondState.Ignore = false;
1758 /// ParseDirectiveEndIf
1760 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1761 if (Lexer.isNot(AsmToken::EndOfStatement))
1762 return TokError("unexpected token in '.endif' directive");
1766 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1767 TheCondStack.empty())
1768 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1770 if (!TheCondStack.empty()) {
1771 TheCondState = TheCondStack.back();
1772 TheCondStack.pop_back();
1778 /// ParseDirectiveFile
1779 /// ::= .file [number] string
1780 bool AsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1781 // FIXME: I'm not sure what this is.
1782 int64_t FileNumber = -1;
1783 if (Lexer.is(AsmToken::Integer)) {
1784 FileNumber = getTok().getIntVal();
1788 return TokError("file number less than one");
1791 if (Lexer.isNot(AsmToken::String))
1792 return TokError("unexpected token in '.file' directive");
1794 StringRef Filename = getTok().getString();
1795 Filename = Filename.substr(1, Filename.size()-2);
1798 if (Lexer.isNot(AsmToken::EndOfStatement))
1799 return TokError("unexpected token in '.file' directive");
1801 if (FileNumber == -1)
1802 Out.EmitFileDirective(Filename);
1804 Out.EmitDwarfFileDirective(FileNumber, Filename);
1809 /// ParseDirectiveLine
1810 /// ::= .line [number]
1811 bool AsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1812 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1813 if (Lexer.isNot(AsmToken::Integer))
1814 return TokError("unexpected token in '.line' directive");
1816 int64_t LineNumber = getTok().getIntVal();
1820 // FIXME: Do something with the .line.
1823 if (Lexer.isNot(AsmToken::EndOfStatement))
1824 return TokError("unexpected token in '.file' directive");
1830 /// ParseDirectiveLoc
1831 /// ::= .loc number [number [number]]
1832 bool AsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1833 if (Lexer.isNot(AsmToken::Integer))
1834 return TokError("unexpected token in '.loc' directive");
1836 // FIXME: What are these fields?
1837 int64_t FileNumber = getTok().getIntVal();
1839 // FIXME: Validate file.
1842 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1843 if (Lexer.isNot(AsmToken::Integer))
1844 return TokError("unexpected token in '.loc' directive");
1846 int64_t Param2 = getTok().getIntVal();
1850 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1851 if (Lexer.isNot(AsmToken::Integer))
1852 return TokError("unexpected token in '.loc' directive");
1854 int64_t Param3 = getTok().getIntVal();
1858 // FIXME: Do something with the .loc.
1862 if (Lexer.isNot(AsmToken::EndOfStatement))
1863 return TokError("unexpected token in '.file' directive");