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/StringSwitch.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetAsmParser.h"
32 enum { DEFAULT_ADDRSPACE = 0 };
34 AsmParser::AsmParser(SourceMgr &_SM, MCContext &_Ctx, MCStreamer &_Out,
35 const MCAsmInfo &_MAI)
36 : Lexer(_MAI), Ctx(_Ctx), Out(_Out), SrcMgr(_SM), TargetParser(0),
38 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
40 // Debugging directives.
41 AddDirectiveHandler(".file", &AsmParser::ParseDirectiveFile);
42 AddDirectiveHandler(".line", &AsmParser::ParseDirectiveLine);
43 AddDirectiveHandler(".loc", &AsmParser::ParseDirectiveLoc);
48 AsmParser::~AsmParser() {
51 void AsmParser::Warning(SMLoc L, const Twine &Msg) {
52 PrintMessage(L, Msg.str(), "warning");
55 bool AsmParser::Error(SMLoc L, const Twine &Msg) {
56 PrintMessage(L, Msg.str(), "error");
60 bool AsmParser::TokError(const char *Msg) {
61 PrintMessage(Lexer.getLoc(), Msg, "error");
65 void AsmParser::PrintMessage(SMLoc Loc, const std::string &Msg,
66 const char *Type) const {
67 SrcMgr.PrintMessage(Loc, Msg, Type);
70 bool AsmParser::EnterIncludeFile(const std::string &Filename) {
71 int NewBuf = SrcMgr.AddIncludeFile(Filename, Lexer.getLoc());
77 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer));
82 const AsmToken &AsmParser::Lex() {
83 const AsmToken *tok = &Lexer.Lex();
85 if (tok->is(AsmToken::Eof)) {
86 // If this is the end of an included file, pop the parent file off the
88 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
89 if (ParentIncludeLoc != SMLoc()) {
90 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
91 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer),
92 ParentIncludeLoc.getPointer());
97 if (tok->is(AsmToken::Error))
98 PrintMessage(Lexer.getErrLoc(), Lexer.getErr(), "error");
103 bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
104 // Create the initial section, if requested.
106 // FIXME: Target hook & command line option for initial section.
107 if (!NoInitialTextSection)
108 Out.SwitchSection(Ctx.getMachOSection("__TEXT", "__text",
109 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
110 0, SectionKind::getText()));
115 bool HadError = false;
117 AsmCond StartingCondState = TheCondState;
119 // While we have input, parse each statement.
120 while (Lexer.isNot(AsmToken::Eof)) {
121 if (!ParseStatement()) continue;
123 // We had an error, remember it and recover by skipping to the next line.
125 EatToEndOfStatement();
128 if (TheCondState.TheCond != StartingCondState.TheCond ||
129 TheCondState.Ignore != StartingCondState.Ignore)
130 return TokError("unmatched .ifs or .elses");
132 // Finalize the output stream if there are no errors and if the client wants
134 if (!HadError && !NoFinalize)
140 /// EatToEndOfStatement - Throw away the rest of the line for testing purposes.
141 void AsmParser::EatToEndOfStatement() {
142 while (Lexer.isNot(AsmToken::EndOfStatement) &&
143 Lexer.isNot(AsmToken::Eof))
147 if (Lexer.is(AsmToken::EndOfStatement))
152 /// ParseParenExpr - Parse a paren expression and return it.
153 /// NOTE: This assumes the leading '(' has already been consumed.
155 /// parenexpr ::= expr)
157 bool AsmParser::ParseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
158 if (ParseExpression(Res)) return true;
159 if (Lexer.isNot(AsmToken::RParen))
160 return TokError("expected ')' in parentheses expression");
161 EndLoc = Lexer.getLoc();
166 MCSymbol *AsmParser::CreateSymbol(StringRef Name) {
167 // FIXME: Inline into callers.
168 return Ctx.GetOrCreateSymbol(Name);
171 /// ParsePrimaryExpr - Parse a primary expression and return it.
172 /// primaryexpr ::= (parenexpr
173 /// primaryexpr ::= symbol
174 /// primaryexpr ::= number
175 /// primaryexpr ::= '.'
176 /// primaryexpr ::= ~,+,- primaryexpr
177 bool AsmParser::ParsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
178 switch (Lexer.getKind()) {
180 return TokError("unknown token in expression");
181 case AsmToken::Exclaim:
182 Lex(); // Eat the operator.
183 if (ParsePrimaryExpr(Res, EndLoc))
185 Res = MCUnaryExpr::CreateLNot(Res, getContext());
187 case AsmToken::String:
188 case AsmToken::Identifier: {
189 // This is a symbol reference.
190 std::pair<StringRef, StringRef> Split = getTok().getIdentifier().split('@');
191 MCSymbol *Sym = CreateSymbol(Split.first);
193 // Mark the symbol as used in an expression.
194 Sym->setUsedInExpr(true);
196 // Lookup the symbol variant if used.
197 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
198 if (Split.first.size() != getTok().getIdentifier().size())
199 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
201 EndLoc = Lexer.getLoc();
202 Lex(); // Eat identifier.
204 // If this is an absolute variable reference, substitute it now to preserve
205 // semantics in the face of reassignment.
206 if (Sym->isVariable() && isa<MCConstantExpr>(Sym->getVariableValue())) {
208 return Error(EndLoc, "unexpected modified on variable reference");
210 Res = Sym->getVariableValue();
214 // Otherwise create a symbol ref.
215 Res = MCSymbolRefExpr::Create(Sym, Variant, getContext());
218 case AsmToken::Integer: {
219 SMLoc Loc = getTok().getLoc();
220 int64_t IntVal = getTok().getIntVal();
221 Res = MCConstantExpr::Create(IntVal, getContext());
222 EndLoc = Lexer.getLoc();
224 // Look for 'b' or 'f' following an Integer as a directional label
225 if (Lexer.getKind() == AsmToken::Identifier) {
226 StringRef IDVal = getTok().getString();
227 if (IDVal == "f" || IDVal == "b"){
228 MCSymbol *Sym = Ctx.GetDirectionalLocalSymbol(IntVal,
229 IDVal == "f" ? 1 : 0);
230 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None,
232 if(IDVal == "b" && Sym->isUndefined())
233 return Error(Loc, "invalid reference to undefined symbol");
234 EndLoc = Lexer.getLoc();
235 Lex(); // Eat identifier.
240 case AsmToken::Dot: {
241 // This is a '.' reference, which references the current PC. Emit a
242 // temporary label to the streamer and refer to it.
243 MCSymbol *Sym = Ctx.CreateTempSymbol();
245 Res = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, getContext());
246 EndLoc = Lexer.getLoc();
247 Lex(); // Eat identifier.
251 case AsmToken::LParen:
252 Lex(); // Eat the '('.
253 return ParseParenExpr(Res, EndLoc);
254 case AsmToken::Minus:
255 Lex(); // Eat the operator.
256 if (ParsePrimaryExpr(Res, EndLoc))
258 Res = MCUnaryExpr::CreateMinus(Res, getContext());
261 Lex(); // Eat the operator.
262 if (ParsePrimaryExpr(Res, EndLoc))
264 Res = MCUnaryExpr::CreatePlus(Res, getContext());
266 case AsmToken::Tilde:
267 Lex(); // Eat the operator.
268 if (ParsePrimaryExpr(Res, EndLoc))
270 Res = MCUnaryExpr::CreateNot(Res, getContext());
275 bool AsmParser::ParseExpression(const MCExpr *&Res) {
277 return ParseExpression(Res, EndLoc);
280 /// ParseExpression - Parse an expression and return it.
282 /// expr ::= expr +,- expr -> lowest.
283 /// expr ::= expr |,^,&,! expr -> middle.
284 /// expr ::= expr *,/,%,<<,>> expr -> highest.
285 /// expr ::= primaryexpr
287 bool AsmParser::ParseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
288 // Parse the expression.
290 if (ParsePrimaryExpr(Res, EndLoc) || ParseBinOpRHS(1, Res, EndLoc))
293 // Try to constant fold it up front, if possible.
295 if (Res->EvaluateAsAbsolute(Value))
296 Res = MCConstantExpr::Create(Value, getContext());
301 bool AsmParser::ParseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
303 return ParseParenExpr(Res, EndLoc) ||
304 ParseBinOpRHS(1, Res, EndLoc);
307 bool AsmParser::ParseAbsoluteExpression(int64_t &Res) {
310 SMLoc StartLoc = Lexer.getLoc();
311 if (ParseExpression(Expr))
314 if (!Expr->EvaluateAsAbsolute(Res))
315 return Error(StartLoc, "expected absolute expression");
320 static unsigned getBinOpPrecedence(AsmToken::TokenKind K,
321 MCBinaryExpr::Opcode &Kind) {
324 return 0; // not a binop.
326 // Lowest Precedence: &&, ||
327 case AsmToken::AmpAmp:
328 Kind = MCBinaryExpr::LAnd;
330 case AsmToken::PipePipe:
331 Kind = MCBinaryExpr::LOr;
334 // Low Precedence: +, -, ==, !=, <>, <, <=, >, >=
336 Kind = MCBinaryExpr::Add;
338 case AsmToken::Minus:
339 Kind = MCBinaryExpr::Sub;
341 case AsmToken::EqualEqual:
342 Kind = MCBinaryExpr::EQ;
344 case AsmToken::ExclaimEqual:
345 case AsmToken::LessGreater:
346 Kind = MCBinaryExpr::NE;
349 Kind = MCBinaryExpr::LT;
351 case AsmToken::LessEqual:
352 Kind = MCBinaryExpr::LTE;
354 case AsmToken::Greater:
355 Kind = MCBinaryExpr::GT;
357 case AsmToken::GreaterEqual:
358 Kind = MCBinaryExpr::GTE;
361 // Intermediate Precedence: |, &, ^
363 // FIXME: gas seems to support '!' as an infix operator?
365 Kind = MCBinaryExpr::Or;
367 case AsmToken::Caret:
368 Kind = MCBinaryExpr::Xor;
371 Kind = MCBinaryExpr::And;
374 // Highest Precedence: *, /, %, <<, >>
376 Kind = MCBinaryExpr::Mul;
378 case AsmToken::Slash:
379 Kind = MCBinaryExpr::Div;
381 case AsmToken::Percent:
382 Kind = MCBinaryExpr::Mod;
384 case AsmToken::LessLess:
385 Kind = MCBinaryExpr::Shl;
387 case AsmToken::GreaterGreater:
388 Kind = MCBinaryExpr::Shr;
394 /// ParseBinOpRHS - Parse all binary operators with precedence >= 'Precedence'.
395 /// Res contains the LHS of the expression on input.
396 bool AsmParser::ParseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
399 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
400 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
402 // If the next token is lower precedence than we are allowed to eat, return
403 // successfully with what we ate already.
404 if (TokPrec < Precedence)
409 // Eat the next primary expression.
411 if (ParsePrimaryExpr(RHS, EndLoc)) return true;
413 // If BinOp binds less tightly with RHS than the operator after RHS, let
414 // the pending operator take RHS as its LHS.
415 MCBinaryExpr::Opcode Dummy;
416 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
417 if (TokPrec < NextTokPrec) {
418 if (ParseBinOpRHS(Precedence+1, RHS, EndLoc)) return true;
421 // Merge LHS and RHS according to operator.
422 Res = MCBinaryExpr::Create(Kind, Res, RHS, getContext());
430 /// ::= EndOfStatement
431 /// ::= Label* Directive ...Operands... EndOfStatement
432 /// ::= Label* Identifier OperandList* EndOfStatement
433 bool AsmParser::ParseStatement() {
434 if (Lexer.is(AsmToken::EndOfStatement)) {
439 // Statements always start with an identifier.
440 AsmToken ID = getTok();
441 SMLoc IDLoc = ID.getLoc();
443 int64_t LocalLabelVal = -1;
444 // GUESS allow an integer followed by a ':' as a directional local label
445 if (Lexer.is(AsmToken::Integer)) {
446 LocalLabelVal = getTok().getIntVal();
447 if (LocalLabelVal < 0) {
448 if (!TheCondState.Ignore)
449 return TokError("unexpected token at start of statement");
453 IDVal = getTok().getString();
454 Lex(); // Consume the integer token to be used as an identifier token.
455 if (Lexer.getKind() != AsmToken::Colon) {
456 if (!TheCondState.Ignore)
457 return TokError("unexpected token at start of statement");
461 else if (ParseIdentifier(IDVal)) {
462 if (!TheCondState.Ignore)
463 return TokError("unexpected token at start of statement");
467 // Handle conditional assembly here before checking for skipping. We
468 // have to do this so that .endif isn't skipped in a ".if 0" block for
471 return ParseDirectiveIf(IDLoc);
472 if (IDVal == ".elseif")
473 return ParseDirectiveElseIf(IDLoc);
474 if (IDVal == ".else")
475 return ParseDirectiveElse(IDLoc);
476 if (IDVal == ".endif")
477 return ParseDirectiveEndIf(IDLoc);
479 // If we are in a ".if 0" block, ignore this statement.
480 if (TheCondState.Ignore) {
481 EatToEndOfStatement();
485 // FIXME: Recurse on local labels?
487 // See what kind of statement we have.
488 switch (Lexer.getKind()) {
489 case AsmToken::Colon: {
490 // identifier ':' -> Label.
493 // Diagnose attempt to use a variable as a label.
495 // FIXME: Diagnostics. Note the location of the definition as a label.
496 // FIXME: This doesn't diagnose assignment to a symbol which has been
497 // implicitly marked as external.
499 if (LocalLabelVal == -1)
500 Sym = CreateSymbol(IDVal);
502 Sym = Ctx.CreateDirectionalLocalSymbol(LocalLabelVal);
503 if (!Sym->isUndefined() || Sym->isVariable())
504 return Error(IDLoc, "invalid symbol redefinition");
509 return ParseStatement();
512 case AsmToken::Equal:
513 // identifier '=' ... -> assignment statement
516 return ParseAssignment(IDVal);
518 default: // Normal instruction or directive.
522 // Otherwise, we have a normal instruction or directive.
523 if (IDVal[0] == '.') {
524 // FIXME: This should be driven based on a hash lookup and callback.
525 if (IDVal == ".section")
526 return ParseDirectiveDarwinSection();
527 if (IDVal == ".text")
528 // FIXME: This changes behavior based on the -static flag to the
530 return ParseDirectiveSectionSwitch("__TEXT", "__text",
531 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
532 if (IDVal == ".const")
533 return ParseDirectiveSectionSwitch("__TEXT", "__const");
534 if (IDVal == ".static_const")
535 return ParseDirectiveSectionSwitch("__TEXT", "__static_const");
536 if (IDVal == ".cstring")
537 return ParseDirectiveSectionSwitch("__TEXT","__cstring",
538 MCSectionMachO::S_CSTRING_LITERALS);
539 if (IDVal == ".literal4")
540 return ParseDirectiveSectionSwitch("__TEXT", "__literal4",
541 MCSectionMachO::S_4BYTE_LITERALS,
543 if (IDVal == ".literal8")
544 return ParseDirectiveSectionSwitch("__TEXT", "__literal8",
545 MCSectionMachO::S_8BYTE_LITERALS,
547 if (IDVal == ".literal16")
548 return ParseDirectiveSectionSwitch("__TEXT","__literal16",
549 MCSectionMachO::S_16BYTE_LITERALS,
551 if (IDVal == ".constructor")
552 return ParseDirectiveSectionSwitch("__TEXT","__constructor");
553 if (IDVal == ".destructor")
554 return ParseDirectiveSectionSwitch("__TEXT","__destructor");
555 if (IDVal == ".fvmlib_init0")
556 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init0");
557 if (IDVal == ".fvmlib_init1")
558 return ParseDirectiveSectionSwitch("__TEXT","__fvmlib_init1");
560 // FIXME: The assembler manual claims that this has the self modify code
561 // flag, at least on x86-32, but that does not appear to be correct.
562 if (IDVal == ".symbol_stub")
563 return ParseDirectiveSectionSwitch("__TEXT","__symbol_stub",
564 MCSectionMachO::S_SYMBOL_STUBS |
565 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
566 // FIXME: Different on PPC and ARM.
568 // FIXME: PowerPC only?
569 if (IDVal == ".picsymbol_stub")
570 return ParseDirectiveSectionSwitch("__TEXT","__picsymbol_stub",
571 MCSectionMachO::S_SYMBOL_STUBS |
572 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
574 if (IDVal == ".data")
575 return ParseDirectiveSectionSwitch("__DATA", "__data");
576 if (IDVal == ".static_data")
577 return ParseDirectiveSectionSwitch("__DATA", "__static_data");
579 // FIXME: The section names of these two are misspelled in the assembler
581 if (IDVal == ".non_lazy_symbol_pointer")
582 return ParseDirectiveSectionSwitch("__DATA", "__nl_symbol_ptr",
583 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
585 if (IDVal == ".lazy_symbol_pointer")
586 return ParseDirectiveSectionSwitch("__DATA", "__la_symbol_ptr",
587 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
590 if (IDVal == ".dyld")
591 return ParseDirectiveSectionSwitch("__DATA", "__dyld");
592 if (IDVal == ".mod_init_func")
593 return ParseDirectiveSectionSwitch("__DATA", "__mod_init_func",
594 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
596 if (IDVal == ".mod_term_func")
597 return ParseDirectiveSectionSwitch("__DATA", "__mod_term_func",
598 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
600 if (IDVal == ".const_data")
601 return ParseDirectiveSectionSwitch("__DATA", "__const");
604 if (IDVal == ".objc_class")
605 return ParseDirectiveSectionSwitch("__OBJC", "__class",
606 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
607 if (IDVal == ".objc_meta_class")
608 return ParseDirectiveSectionSwitch("__OBJC", "__meta_class",
609 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
610 if (IDVal == ".objc_cat_cls_meth")
611 return ParseDirectiveSectionSwitch("__OBJC", "__cat_cls_meth",
612 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
613 if (IDVal == ".objc_cat_inst_meth")
614 return ParseDirectiveSectionSwitch("__OBJC", "__cat_inst_meth",
615 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
616 if (IDVal == ".objc_protocol")
617 return ParseDirectiveSectionSwitch("__OBJC", "__protocol",
618 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
619 if (IDVal == ".objc_string_object")
620 return ParseDirectiveSectionSwitch("__OBJC", "__string_object",
621 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
622 if (IDVal == ".objc_cls_meth")
623 return ParseDirectiveSectionSwitch("__OBJC", "__cls_meth",
624 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
625 if (IDVal == ".objc_inst_meth")
626 return ParseDirectiveSectionSwitch("__OBJC", "__inst_meth",
627 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
628 if (IDVal == ".objc_cls_refs")
629 return ParseDirectiveSectionSwitch("__OBJC", "__cls_refs",
630 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
631 MCSectionMachO::S_LITERAL_POINTERS,
633 if (IDVal == ".objc_message_refs")
634 return ParseDirectiveSectionSwitch("__OBJC", "__message_refs",
635 MCSectionMachO::S_ATTR_NO_DEAD_STRIP |
636 MCSectionMachO::S_LITERAL_POINTERS,
638 if (IDVal == ".objc_symbols")
639 return ParseDirectiveSectionSwitch("__OBJC", "__symbols",
640 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
641 if (IDVal == ".objc_category")
642 return ParseDirectiveSectionSwitch("__OBJC", "__category",
643 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
644 if (IDVal == ".objc_class_vars")
645 return ParseDirectiveSectionSwitch("__OBJC", "__class_vars",
646 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
647 if (IDVal == ".objc_instance_vars")
648 return ParseDirectiveSectionSwitch("__OBJC", "__instance_vars",
649 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
650 if (IDVal == ".objc_module_info")
651 return ParseDirectiveSectionSwitch("__OBJC", "__module_info",
652 MCSectionMachO::S_ATTR_NO_DEAD_STRIP);
653 if (IDVal == ".objc_class_names")
654 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
655 MCSectionMachO::S_CSTRING_LITERALS);
656 if (IDVal == ".objc_meth_var_types")
657 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
658 MCSectionMachO::S_CSTRING_LITERALS);
659 if (IDVal == ".objc_meth_var_names")
660 return ParseDirectiveSectionSwitch("__TEXT", "__cstring",
661 MCSectionMachO::S_CSTRING_LITERALS);
662 if (IDVal == ".objc_selector_strs")
663 return ParseDirectiveSectionSwitch("__OBJC", "__selector_strs",
664 MCSectionMachO::S_CSTRING_LITERALS);
666 if (IDVal == ".tdata")
667 return ParseDirectiveSectionSwitch("__DATA", "__thread_data",
668 MCSectionMachO::S_THREAD_LOCAL_REGULAR);
670 return ParseDirectiveSectionSwitch("__DATA", "__thread_vars",
671 MCSectionMachO::S_THREAD_LOCAL_VARIABLES);
672 if (IDVal == ".thread_init_func")
673 return ParseDirectiveSectionSwitch("__DATA", "__thread_init",
674 MCSectionMachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS);
676 // Assembler features
678 return ParseDirectiveSet();
682 if (IDVal == ".ascii")
683 return ParseDirectiveAscii(false);
684 if (IDVal == ".asciz")
685 return ParseDirectiveAscii(true);
687 if (IDVal == ".byte")
688 return ParseDirectiveValue(1);
689 if (IDVal == ".short")
690 return ParseDirectiveValue(2);
691 if (IDVal == ".long")
692 return ParseDirectiveValue(4);
693 if (IDVal == ".quad")
694 return ParseDirectiveValue(8);
696 // FIXME: Target hooks for IsPow2.
697 if (IDVal == ".align")
698 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
699 if (IDVal == ".align32")
700 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
701 if (IDVal == ".balign")
702 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
703 if (IDVal == ".balignw")
704 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
705 if (IDVal == ".balignl")
706 return ParseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
707 if (IDVal == ".p2align")
708 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
709 if (IDVal == ".p2alignw")
710 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
711 if (IDVal == ".p2alignl")
712 return ParseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
715 return ParseDirectiveOrg();
717 if (IDVal == ".fill")
718 return ParseDirectiveFill();
719 if (IDVal == ".space")
720 return ParseDirectiveSpace();
722 // Symbol attribute directives
724 if (IDVal == ".globl" || IDVal == ".global")
725 return ParseDirectiveSymbolAttribute(MCSA_Global);
726 if (IDVal == ".hidden")
727 return ParseDirectiveSymbolAttribute(MCSA_Hidden);
728 if (IDVal == ".indirect_symbol")
729 return ParseDirectiveSymbolAttribute(MCSA_IndirectSymbol);
730 if (IDVal == ".internal")
731 return ParseDirectiveSymbolAttribute(MCSA_Internal);
732 if (IDVal == ".lazy_reference")
733 return ParseDirectiveSymbolAttribute(MCSA_LazyReference);
734 if (IDVal == ".no_dead_strip")
735 return ParseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
736 if (IDVal == ".private_extern")
737 return ParseDirectiveSymbolAttribute(MCSA_PrivateExtern);
738 if (IDVal == ".protected")
739 return ParseDirectiveSymbolAttribute(MCSA_Protected);
740 if (IDVal == ".reference")
741 return ParseDirectiveSymbolAttribute(MCSA_Reference);
742 if (IDVal == ".type")
743 return ParseDirectiveELFType();
744 if (IDVal == ".weak")
745 return ParseDirectiveSymbolAttribute(MCSA_Weak);
746 if (IDVal == ".weak_definition")
747 return ParseDirectiveSymbolAttribute(MCSA_WeakDefinition);
748 if (IDVal == ".weak_reference")
749 return ParseDirectiveSymbolAttribute(MCSA_WeakReference);
751 if (IDVal == ".comm")
752 return ParseDirectiveComm(/*IsLocal=*/false);
753 if (IDVal == ".lcomm")
754 return ParseDirectiveComm(/*IsLocal=*/true);
755 if (IDVal == ".zerofill")
756 return ParseDirectiveDarwinZerofill();
757 if (IDVal == ".desc")
758 return ParseDirectiveDarwinSymbolDesc();
759 if (IDVal == ".lsym")
760 return ParseDirectiveDarwinLsym();
761 if (IDVal == ".tbss")
762 return ParseDirectiveDarwinTBSS();
764 if (IDVal == ".subsections_via_symbols")
765 return ParseDirectiveDarwinSubsectionsViaSymbols();
766 if (IDVal == ".abort")
767 return ParseDirectiveAbort();
768 if (IDVal == ".include")
769 return ParseDirectiveInclude();
770 if (IDVal == ".dump")
771 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsDump=*/true);
772 if (IDVal == ".load")
773 return ParseDirectiveDarwinDumpOrLoad(IDLoc, /*IsLoad=*/false);
775 // Look up the handler in the handler table,
776 bool(AsmParser::*Handler)(StringRef, SMLoc) = DirectiveMap[IDVal];
778 return (this->*Handler)(IDVal, IDLoc);
780 // Target hook for parsing target specific directives.
781 if (!getTargetParser().ParseDirective(ID))
784 Warning(IDLoc, "ignoring directive for now");
785 EatToEndOfStatement();
789 // Canonicalize the opcode to lower case.
790 SmallString<128> Opcode;
791 for (unsigned i = 0, e = IDVal.size(); i != e; ++i)
792 Opcode.push_back(tolower(IDVal[i]));
794 SmallVector<MCParsedAsmOperand*, 8> ParsedOperands;
795 bool HadError = getTargetParser().ParseInstruction(Opcode.str(), IDLoc,
797 if (!HadError && Lexer.isNot(AsmToken::EndOfStatement))
798 HadError = TokError("unexpected token in argument list");
800 // If parsing succeeded, match the instruction.
803 if (!getTargetParser().MatchInstruction(ParsedOperands, Inst)) {
804 // Emit the instruction on success.
805 Out.EmitInstruction(Inst);
807 // Otherwise emit a diagnostic about the match failure and set the error
810 // FIXME: We should give nicer diagnostics about the exact failure.
811 Error(IDLoc, "unrecognized instruction");
816 // If there was no error, consume the end-of-statement token. Otherwise this
817 // will be done by our caller.
821 // Free any parsed operands.
822 for (unsigned i = 0, e = ParsedOperands.size(); i != e; ++i)
823 delete ParsedOperands[i];
828 bool AsmParser::ParseAssignment(const StringRef &Name) {
829 // FIXME: Use better location, we should use proper tokens.
830 SMLoc EqualLoc = Lexer.getLoc();
833 SMLoc StartLoc = Lexer.getLoc();
834 if (ParseExpression(Value))
837 if (Lexer.isNot(AsmToken::EndOfStatement))
838 return TokError("unexpected token in assignment");
840 // Eat the end of statement marker.
843 // Validate that the LHS is allowed to be a variable (either it has not been
844 // used as a symbol, or it is an absolute symbol).
845 MCSymbol *Sym = getContext().LookupSymbol(Name);
847 // Diagnose assignment to a label.
849 // FIXME: Diagnostics. Note the location of the definition as a label.
850 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
851 if (Sym->isUndefined() && !Sym->isUsedInExpr())
852 ; // Allow redefinitions of undefined symbols only used in directives.
853 else if (!Sym->isUndefined() && !Sym->isAbsolute())
854 return Error(EqualLoc, "redefinition of '" + Name + "'");
855 else if (!Sym->isVariable())
856 return Error(EqualLoc, "invalid assignment to '" + Name + "'");
857 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
858 return Error(EqualLoc, "invalid reassignment of non-absolute variable '" +
861 Sym = CreateSymbol(Name);
863 // FIXME: Handle '.'.
865 Sym->setUsedInExpr(true);
867 // Do the assignment.
868 Out.EmitAssignment(Sym, Value);
876 bool AsmParser::ParseIdentifier(StringRef &Res) {
877 if (Lexer.isNot(AsmToken::Identifier) &&
878 Lexer.isNot(AsmToken::String))
881 Res = getTok().getIdentifier();
883 Lex(); // Consume the identifier token.
888 /// ParseDirectiveSet:
889 /// ::= .set identifier ',' expression
890 bool AsmParser::ParseDirectiveSet() {
893 if (ParseIdentifier(Name))
894 return TokError("expected identifier after '.set' directive");
896 if (Lexer.isNot(AsmToken::Comma))
897 return TokError("unexpected token in '.set'");
900 return ParseAssignment(Name);
903 /// ParseDirectiveSection:
904 /// ::= .section identifier (',' identifier)*
905 /// FIXME: This should actually parse out the segment, section, attributes and
906 /// sizeof_stub fields.
907 bool AsmParser::ParseDirectiveDarwinSection() {
908 SMLoc Loc = Lexer.getLoc();
910 StringRef SectionName;
911 if (ParseIdentifier(SectionName))
912 return Error(Loc, "expected identifier after '.section' directive");
914 // Verify there is a following comma.
915 if (!Lexer.is(AsmToken::Comma))
916 return TokError("unexpected token in '.section' directive");
918 std::string SectionSpec = SectionName;
921 // Add all the tokens until the end of the line, ParseSectionSpecifier will
923 StringRef EOL = Lexer.LexUntilEndOfStatement();
924 SectionSpec.append(EOL.begin(), EOL.end());
927 if (Lexer.isNot(AsmToken::EndOfStatement))
928 return TokError("unexpected token in '.section' directive");
932 StringRef Segment, Section;
933 unsigned TAA, StubSize;
934 std::string ErrorStr =
935 MCSectionMachO::ParseSectionSpecifier(SectionSpec, Segment, Section,
938 if (!ErrorStr.empty())
939 return Error(Loc, ErrorStr.c_str());
941 // FIXME: Arch specific.
942 bool isText = Segment == "__TEXT"; // FIXME: Hack.
943 Out.SwitchSection(Ctx.getMachOSection(Segment, Section, TAA, StubSize,
944 isText ? SectionKind::getText()
945 : SectionKind::getDataRel()));
949 /// ParseDirectiveSectionSwitch -
950 bool AsmParser::ParseDirectiveSectionSwitch(const char *Segment,
952 unsigned TAA, unsigned Align,
954 if (Lexer.isNot(AsmToken::EndOfStatement))
955 return TokError("unexpected token in section switching directive");
958 // FIXME: Arch specific.
959 bool isText = StringRef(Segment) == "__TEXT"; // FIXME: Hack.
960 Out.SwitchSection(Ctx.getMachOSection(Segment, Section, TAA, StubSize,
961 isText ? SectionKind::getText()
962 : SectionKind::getDataRel()));
964 // Set the implicit alignment, if any.
966 // FIXME: This isn't really what 'as' does; I think it just uses the implicit
967 // alignment on the section (e.g., if one manually inserts bytes into the
968 // section, then just issueing the section switch directive will not realign
969 // the section. However, this is arguably more reasonable behavior, and there
970 // is no good reason for someone to intentionally emit incorrectly sized
971 // values into the implicitly aligned sections.
973 Out.EmitValueToAlignment(Align, 0, 1, 0);
978 bool AsmParser::ParseEscapedString(std::string &Data) {
979 assert(Lexer.is(AsmToken::String) && "Unexpected current token!");
982 StringRef Str = getTok().getStringContents();
983 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
984 if (Str[i] != '\\') {
989 // Recognize escaped characters. Note that this escape semantics currently
990 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
993 return TokError("unexpected backslash at end of string");
995 // Recognize octal sequences.
996 if ((unsigned) (Str[i] - '0') <= 7) {
997 // Consume up to three octal characters.
998 unsigned Value = Str[i] - '0';
1000 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1002 Value = Value * 8 + (Str[i] - '0');
1004 if (i + 1 != e && ((unsigned) (Str[i + 1] - '0')) <= 7) {
1006 Value = Value * 8 + (Str[i] - '0');
1011 return TokError("invalid octal escape sequence (out of range)");
1013 Data += (unsigned char) Value;
1017 // Otherwise recognize individual escapes.
1020 // Just reject invalid escape sequences for now.
1021 return TokError("invalid escape sequence (unrecognized character)");
1023 case 'b': Data += '\b'; break;
1024 case 'f': Data += '\f'; break;
1025 case 'n': Data += '\n'; break;
1026 case 'r': Data += '\r'; break;
1027 case 't': Data += '\t'; break;
1028 case '"': Data += '"'; break;
1029 case '\\': Data += '\\'; break;
1036 /// ParseDirectiveAscii:
1037 /// ::= ( .ascii | .asciz ) [ "string" ( , "string" )* ]
1038 bool AsmParser::ParseDirectiveAscii(bool ZeroTerminated) {
1039 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1041 if (Lexer.isNot(AsmToken::String))
1042 return TokError("expected string in '.ascii' or '.asciz' directive");
1045 if (ParseEscapedString(Data))
1048 Out.EmitBytes(Data, DEFAULT_ADDRSPACE);
1050 Out.EmitBytes(StringRef("\0", 1), DEFAULT_ADDRSPACE);
1054 if (Lexer.is(AsmToken::EndOfStatement))
1057 if (Lexer.isNot(AsmToken::Comma))
1058 return TokError("unexpected token in '.ascii' or '.asciz' directive");
1067 /// ParseDirectiveValue
1068 /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
1069 bool AsmParser::ParseDirectiveValue(unsigned Size) {
1070 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1072 const MCExpr *Value;
1073 SMLoc ATTRIBUTE_UNUSED StartLoc = Lexer.getLoc();
1074 if (ParseExpression(Value))
1077 Out.EmitValue(Value, Size, DEFAULT_ADDRSPACE);
1079 if (Lexer.is(AsmToken::EndOfStatement))
1082 // FIXME: Improve diagnostic.
1083 if (Lexer.isNot(AsmToken::Comma))
1084 return TokError("unexpected token in directive");
1093 /// ParseDirectiveSpace
1094 /// ::= .space expression [ , expression ]
1095 bool AsmParser::ParseDirectiveSpace() {
1097 if (ParseAbsoluteExpression(NumBytes))
1100 int64_t FillExpr = 0;
1101 bool HasFillExpr = false;
1102 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1103 if (Lexer.isNot(AsmToken::Comma))
1104 return TokError("unexpected token in '.space' directive");
1107 if (ParseAbsoluteExpression(FillExpr))
1112 if (Lexer.isNot(AsmToken::EndOfStatement))
1113 return TokError("unexpected token in '.space' directive");
1119 return TokError("invalid number of bytes in '.space' directive");
1121 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
1122 Out.EmitFill(NumBytes, FillExpr, DEFAULT_ADDRSPACE);
1127 /// ParseDirectiveFill
1128 /// ::= .fill expression , expression , expression
1129 bool AsmParser::ParseDirectiveFill() {
1131 if (ParseAbsoluteExpression(NumValues))
1134 if (Lexer.isNot(AsmToken::Comma))
1135 return TokError("unexpected token in '.fill' directive");
1139 if (ParseAbsoluteExpression(FillSize))
1142 if (Lexer.isNot(AsmToken::Comma))
1143 return TokError("unexpected token in '.fill' directive");
1147 if (ParseAbsoluteExpression(FillExpr))
1150 if (Lexer.isNot(AsmToken::EndOfStatement))
1151 return TokError("unexpected token in '.fill' directive");
1155 if (FillSize != 1 && FillSize != 2 && FillSize != 4 && FillSize != 8)
1156 return TokError("invalid '.fill' size, expected 1, 2, 4, or 8");
1158 for (uint64_t i = 0, e = NumValues; i != e; ++i)
1159 Out.EmitValue(MCConstantExpr::Create(FillExpr, getContext()), FillSize,
1165 /// ParseDirectiveOrg
1166 /// ::= .org expression [ , expression ]
1167 bool AsmParser::ParseDirectiveOrg() {
1168 const MCExpr *Offset;
1169 SMLoc StartLoc = Lexer.getLoc();
1170 if (ParseExpression(Offset))
1173 // Parse optional fill expression.
1174 int64_t FillExpr = 0;
1175 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1176 if (Lexer.isNot(AsmToken::Comma))
1177 return TokError("unexpected token in '.org' directive");
1180 if (ParseAbsoluteExpression(FillExpr))
1183 if (Lexer.isNot(AsmToken::EndOfStatement))
1184 return TokError("unexpected token in '.org' directive");
1189 // FIXME: Only limited forms of relocatable expressions are accepted here, it
1190 // has to be relative to the current section.
1191 Out.EmitValueToOffset(Offset, FillExpr);
1196 /// ParseDirectiveAlign
1197 /// ::= {.align, ...} expression [ , expression [ , expression ]]
1198 bool AsmParser::ParseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
1199 SMLoc AlignmentLoc = Lexer.getLoc();
1201 if (ParseAbsoluteExpression(Alignment))
1205 bool HasFillExpr = false;
1206 int64_t FillExpr = 0;
1207 int64_t MaxBytesToFill = 0;
1208 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1209 if (Lexer.isNot(AsmToken::Comma))
1210 return TokError("unexpected token in directive");
1213 // The fill expression can be omitted while specifying a maximum number of
1214 // alignment bytes, e.g:
1216 if (Lexer.isNot(AsmToken::Comma)) {
1218 if (ParseAbsoluteExpression(FillExpr))
1222 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1223 if (Lexer.isNot(AsmToken::Comma))
1224 return TokError("unexpected token in directive");
1227 MaxBytesLoc = Lexer.getLoc();
1228 if (ParseAbsoluteExpression(MaxBytesToFill))
1231 if (Lexer.isNot(AsmToken::EndOfStatement))
1232 return TokError("unexpected token in directive");
1241 // Compute alignment in bytes.
1243 // FIXME: Diagnose overflow.
1244 if (Alignment >= 32) {
1245 Error(AlignmentLoc, "invalid alignment value");
1249 Alignment = 1ULL << Alignment;
1252 // Diagnose non-sensical max bytes to align.
1253 if (MaxBytesLoc.isValid()) {
1254 if (MaxBytesToFill < 1) {
1255 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
1256 "many bytes, ignoring maximum bytes expression");
1260 if (MaxBytesToFill >= Alignment) {
1261 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
1267 // Check whether we should use optimal code alignment for this .align
1270 // FIXME: This should be using a target hook.
1271 bool UseCodeAlign = false;
1272 if (const MCSectionMachO *S = dyn_cast<MCSectionMachO>(
1273 Out.getCurrentSection()))
1274 UseCodeAlign = S->hasAttribute(MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS);
1275 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
1276 ValueSize == 1 && UseCodeAlign) {
1277 Out.EmitCodeAlignment(Alignment, MaxBytesToFill);
1279 // FIXME: Target specific behavior about how the "extra" bytes are filled.
1280 Out.EmitValueToAlignment(Alignment, FillExpr, ValueSize, MaxBytesToFill);
1286 /// ParseDirectiveSymbolAttribute
1287 /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
1288 bool AsmParser::ParseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
1289 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1293 if (ParseIdentifier(Name))
1294 return TokError("expected identifier in directive");
1296 MCSymbol *Sym = CreateSymbol(Name);
1298 Out.EmitSymbolAttribute(Sym, Attr);
1300 if (Lexer.is(AsmToken::EndOfStatement))
1303 if (Lexer.isNot(AsmToken::Comma))
1304 return TokError("unexpected token in directive");
1313 /// ParseDirectiveELFType
1314 /// ::= .type identifier , @attribute
1315 bool AsmParser::ParseDirectiveELFType() {
1317 if (ParseIdentifier(Name))
1318 return TokError("expected identifier in directive");
1320 // Handle the identifier as the key symbol.
1321 MCSymbol *Sym = CreateSymbol(Name);
1323 if (Lexer.isNot(AsmToken::Comma))
1324 return TokError("unexpected token in '.type' directive");
1327 if (Lexer.isNot(AsmToken::At))
1328 return TokError("expected '@' before type");
1334 TypeLoc = Lexer.getLoc();
1335 if (ParseIdentifier(Type))
1336 return TokError("expected symbol type in directive");
1338 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
1339 .Case("function", MCSA_ELF_TypeFunction)
1340 .Case("object", MCSA_ELF_TypeObject)
1341 .Case("tls_object", MCSA_ELF_TypeTLS)
1342 .Case("common", MCSA_ELF_TypeCommon)
1343 .Case("notype", MCSA_ELF_TypeNoType)
1344 .Default(MCSA_Invalid);
1346 if (Attr == MCSA_Invalid)
1347 return Error(TypeLoc, "unsupported attribute in '.type' directive");
1349 if (Lexer.isNot(AsmToken::EndOfStatement))
1350 return TokError("unexpected token in '.type' directive");
1354 Out.EmitSymbolAttribute(Sym, Attr);
1359 /// ParseDirectiveDarwinSymbolDesc
1360 /// ::= .desc identifier , expression
1361 bool AsmParser::ParseDirectiveDarwinSymbolDesc() {
1363 if (ParseIdentifier(Name))
1364 return TokError("expected identifier in directive");
1366 // Handle the identifier as the key symbol.
1367 MCSymbol *Sym = CreateSymbol(Name);
1369 if (Lexer.isNot(AsmToken::Comma))
1370 return TokError("unexpected token in '.desc' directive");
1373 SMLoc DescLoc = Lexer.getLoc();
1375 if (ParseAbsoluteExpression(DescValue))
1378 if (Lexer.isNot(AsmToken::EndOfStatement))
1379 return TokError("unexpected token in '.desc' directive");
1383 // Set the n_desc field of this Symbol to this DescValue
1384 Out.EmitSymbolDesc(Sym, DescValue);
1389 /// ParseDirectiveComm
1390 /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
1391 bool AsmParser::ParseDirectiveComm(bool IsLocal) {
1392 SMLoc IDLoc = Lexer.getLoc();
1394 if (ParseIdentifier(Name))
1395 return TokError("expected identifier in directive");
1397 // Handle the identifier as the key symbol.
1398 MCSymbol *Sym = CreateSymbol(Name);
1400 if (Lexer.isNot(AsmToken::Comma))
1401 return TokError("unexpected token in directive");
1405 SMLoc SizeLoc = Lexer.getLoc();
1406 if (ParseAbsoluteExpression(Size))
1409 int64_t Pow2Alignment = 0;
1410 SMLoc Pow2AlignmentLoc;
1411 if (Lexer.is(AsmToken::Comma)) {
1413 Pow2AlignmentLoc = Lexer.getLoc();
1414 if (ParseAbsoluteExpression(Pow2Alignment))
1417 // If this target takes alignments in bytes (not log) validate and convert.
1418 if (Lexer.getMAI().getAlignmentIsInBytes()) {
1419 if (!isPowerOf2_64(Pow2Alignment))
1420 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
1421 Pow2Alignment = Log2_64(Pow2Alignment);
1425 if (Lexer.isNot(AsmToken::EndOfStatement))
1426 return TokError("unexpected token in '.comm' or '.lcomm' directive");
1430 // NOTE: a size of zero for a .comm should create a undefined symbol
1431 // but a size of .lcomm creates a bss symbol of size zero.
1433 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
1434 "be less than zero");
1436 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1437 // may internally end up wanting an alignment in bytes.
1438 // FIXME: Diagnose overflow.
1439 if (Pow2Alignment < 0)
1440 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
1441 "alignment, can't be less than zero");
1443 if (!Sym->isUndefined())
1444 return Error(IDLoc, "invalid symbol redefinition");
1446 // '.lcomm' is equivalent to '.zerofill'.
1447 // Create the Symbol as a common or local common with Size and Pow2Alignment
1449 Out.EmitZerofill(Ctx.getMachOSection("__DATA", "__bss",
1450 MCSectionMachO::S_ZEROFILL, 0,
1451 SectionKind::getBSS()),
1452 Sym, Size, 1 << Pow2Alignment);
1456 Out.EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
1460 /// ParseDirectiveDarwinZerofill
1461 /// ::= .zerofill segname , sectname [, identifier , size_expression [
1462 /// , align_expression ]]
1463 bool AsmParser::ParseDirectiveDarwinZerofill() {
1465 if (ParseIdentifier(Segment))
1466 return TokError("expected segment name after '.zerofill' directive");
1468 if (Lexer.isNot(AsmToken::Comma))
1469 return TokError("unexpected token in directive");
1473 if (ParseIdentifier(Section))
1474 return TokError("expected section name after comma in '.zerofill' "
1477 // If this is the end of the line all that was wanted was to create the
1478 // the section but with no symbol.
1479 if (Lexer.is(AsmToken::EndOfStatement)) {
1480 // Create the zerofill section but no symbol
1481 Out.EmitZerofill(Ctx.getMachOSection(Segment, Section,
1482 MCSectionMachO::S_ZEROFILL, 0,
1483 SectionKind::getBSS()));
1487 if (Lexer.isNot(AsmToken::Comma))
1488 return TokError("unexpected token in directive");
1491 SMLoc IDLoc = Lexer.getLoc();
1493 if (ParseIdentifier(IDStr))
1494 return TokError("expected identifier in directive");
1496 // handle the identifier as the key symbol.
1497 MCSymbol *Sym = CreateSymbol(IDStr);
1499 if (Lexer.isNot(AsmToken::Comma))
1500 return TokError("unexpected token in directive");
1504 SMLoc SizeLoc = Lexer.getLoc();
1505 if (ParseAbsoluteExpression(Size))
1508 int64_t Pow2Alignment = 0;
1509 SMLoc Pow2AlignmentLoc;
1510 if (Lexer.is(AsmToken::Comma)) {
1512 Pow2AlignmentLoc = Lexer.getLoc();
1513 if (ParseAbsoluteExpression(Pow2Alignment))
1517 if (Lexer.isNot(AsmToken::EndOfStatement))
1518 return TokError("unexpected token in '.zerofill' directive");
1523 return Error(SizeLoc, "invalid '.zerofill' directive size, can't be less "
1526 // NOTE: The alignment in the directive is a power of 2 value, the assembler
1527 // may internally end up wanting an alignment in bytes.
1528 // FIXME: Diagnose overflow.
1529 if (Pow2Alignment < 0)
1530 return Error(Pow2AlignmentLoc, "invalid '.zerofill' directive alignment, "
1531 "can't be less than zero");
1533 if (!Sym->isUndefined())
1534 return Error(IDLoc, "invalid symbol redefinition");
1536 // Create the zerofill Symbol with Size and Pow2Alignment
1538 // FIXME: Arch specific.
1539 Out.EmitZerofill(Ctx.getMachOSection(Segment, Section,
1540 MCSectionMachO::S_ZEROFILL, 0,
1541 SectionKind::getBSS()),
1542 Sym, Size, 1 << Pow2Alignment);
1547 /// ParseDirectiveDarwinTBSS
1548 /// ::= .tbss identifier, size, align
1549 bool AsmParser::ParseDirectiveDarwinTBSS() {
1550 SMLoc IDLoc = Lexer.getLoc();
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 directive");
1563 SMLoc SizeLoc = Lexer.getLoc();
1564 if (ParseAbsoluteExpression(Size))
1567 int64_t Pow2Alignment = 0;
1568 SMLoc Pow2AlignmentLoc;
1569 if (Lexer.is(AsmToken::Comma)) {
1571 Pow2AlignmentLoc = Lexer.getLoc();
1572 if (ParseAbsoluteExpression(Pow2Alignment))
1576 if (Lexer.isNot(AsmToken::EndOfStatement))
1577 return TokError("unexpected token in '.tbss' directive");
1582 return Error(SizeLoc, "invalid '.tbss' directive size, can't be less than"
1585 // FIXME: Diagnose overflow.
1586 if (Pow2Alignment < 0)
1587 return Error(Pow2AlignmentLoc, "invalid '.tbss' alignment, can't be less"
1590 if (!Sym->isUndefined())
1591 return Error(IDLoc, "invalid symbol redefinition");
1593 Out.EmitTBSSSymbol(Ctx.getMachOSection("__DATA", "__thread_bss",
1594 MCSectionMachO::S_THREAD_LOCAL_ZEROFILL,
1595 0, SectionKind::getThreadBSS()),
1596 Sym, Size, 1 << Pow2Alignment);
1601 /// ParseDirectiveDarwinSubsectionsViaSymbols
1602 /// ::= .subsections_via_symbols
1603 bool AsmParser::ParseDirectiveDarwinSubsectionsViaSymbols() {
1604 if (Lexer.isNot(AsmToken::EndOfStatement))
1605 return TokError("unexpected token in '.subsections_via_symbols' directive");
1609 Out.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1614 /// ParseDirectiveAbort
1615 /// ::= .abort [ "abort_string" ]
1616 bool AsmParser::ParseDirectiveAbort() {
1617 // FIXME: Use loc from directive.
1618 SMLoc Loc = Lexer.getLoc();
1621 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1622 if (Lexer.isNot(AsmToken::String))
1623 return TokError("expected string in '.abort' directive");
1625 Str = getTok().getString();
1630 if (Lexer.isNot(AsmToken::EndOfStatement))
1631 return TokError("unexpected token in '.abort' directive");
1635 // FIXME: Handle here.
1637 Error(Loc, ".abort detected. Assembly stopping.");
1639 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
1644 /// ParseDirectiveLsym
1645 /// ::= .lsym identifier , expression
1646 bool AsmParser::ParseDirectiveDarwinLsym() {
1648 if (ParseIdentifier(Name))
1649 return TokError("expected identifier in directive");
1651 // Handle the identifier as the key symbol.
1652 MCSymbol *Sym = CreateSymbol(Name);
1654 if (Lexer.isNot(AsmToken::Comma))
1655 return TokError("unexpected token in '.lsym' directive");
1658 const MCExpr *Value;
1659 SMLoc StartLoc = Lexer.getLoc();
1660 if (ParseExpression(Value))
1663 if (Lexer.isNot(AsmToken::EndOfStatement))
1664 return TokError("unexpected token in '.lsym' directive");
1668 // We don't currently support this directive.
1670 // FIXME: Diagnostic location!
1672 return TokError("directive '.lsym' is unsupported");
1675 /// ParseDirectiveInclude
1676 /// ::= .include "filename"
1677 bool AsmParser::ParseDirectiveInclude() {
1678 if (Lexer.isNot(AsmToken::String))
1679 return TokError("expected string in '.include' directive");
1681 std::string Filename = getTok().getString();
1682 SMLoc IncludeLoc = Lexer.getLoc();
1685 if (Lexer.isNot(AsmToken::EndOfStatement))
1686 return TokError("unexpected token in '.include' directive");
1688 // Strip the quotes.
1689 Filename = Filename.substr(1, Filename.size()-2);
1691 // Attempt to switch the lexer to the included file before consuming the end
1692 // of statement to avoid losing it when we switch.
1693 if (EnterIncludeFile(Filename)) {
1694 PrintMessage(IncludeLoc,
1695 "Could not find include file '" + Filename + "'",
1703 /// ParseDirectiveDarwinDumpOrLoad
1704 /// ::= ( .dump | .load ) "filename"
1705 bool AsmParser::ParseDirectiveDarwinDumpOrLoad(SMLoc IDLoc, bool IsDump) {
1706 if (Lexer.isNot(AsmToken::String))
1707 return TokError("expected string in '.dump' or '.load' directive");
1711 if (Lexer.isNot(AsmToken::EndOfStatement))
1712 return TokError("unexpected token in '.dump' or '.load' directive");
1716 // FIXME: If/when .dump and .load are implemented they will be done in the
1717 // the assembly parser and not have any need for an MCStreamer API.
1719 Warning(IDLoc, "ignoring directive .dump for now");
1721 Warning(IDLoc, "ignoring directive .load for now");
1726 /// ParseDirectiveIf
1727 /// ::= .if expression
1728 bool AsmParser::ParseDirectiveIf(SMLoc DirectiveLoc) {
1729 TheCondStack.push_back(TheCondState);
1730 TheCondState.TheCond = AsmCond::IfCond;
1731 if(TheCondState.Ignore) {
1732 EatToEndOfStatement();
1736 if (ParseAbsoluteExpression(ExprValue))
1739 if (Lexer.isNot(AsmToken::EndOfStatement))
1740 return TokError("unexpected token in '.if' directive");
1744 TheCondState.CondMet = ExprValue;
1745 TheCondState.Ignore = !TheCondState.CondMet;
1751 /// ParseDirectiveElseIf
1752 /// ::= .elseif expression
1753 bool AsmParser::ParseDirectiveElseIf(SMLoc DirectiveLoc) {
1754 if (TheCondState.TheCond != AsmCond::IfCond &&
1755 TheCondState.TheCond != AsmCond::ElseIfCond)
1756 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
1758 TheCondState.TheCond = AsmCond::ElseIfCond;
1760 bool LastIgnoreState = false;
1761 if (!TheCondStack.empty())
1762 LastIgnoreState = TheCondStack.back().Ignore;
1763 if (LastIgnoreState || TheCondState.CondMet) {
1764 TheCondState.Ignore = true;
1765 EatToEndOfStatement();
1769 if (ParseAbsoluteExpression(ExprValue))
1772 if (Lexer.isNot(AsmToken::EndOfStatement))
1773 return TokError("unexpected token in '.elseif' directive");
1776 TheCondState.CondMet = ExprValue;
1777 TheCondState.Ignore = !TheCondState.CondMet;
1783 /// ParseDirectiveElse
1785 bool AsmParser::ParseDirectiveElse(SMLoc DirectiveLoc) {
1786 if (Lexer.isNot(AsmToken::EndOfStatement))
1787 return TokError("unexpected token in '.else' directive");
1791 if (TheCondState.TheCond != AsmCond::IfCond &&
1792 TheCondState.TheCond != AsmCond::ElseIfCond)
1793 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
1795 TheCondState.TheCond = AsmCond::ElseCond;
1796 bool LastIgnoreState = false;
1797 if (!TheCondStack.empty())
1798 LastIgnoreState = TheCondStack.back().Ignore;
1799 if (LastIgnoreState || TheCondState.CondMet)
1800 TheCondState.Ignore = true;
1802 TheCondState.Ignore = false;
1807 /// ParseDirectiveEndIf
1809 bool AsmParser::ParseDirectiveEndIf(SMLoc DirectiveLoc) {
1810 if (Lexer.isNot(AsmToken::EndOfStatement))
1811 return TokError("unexpected token in '.endif' directive");
1815 if ((TheCondState.TheCond == AsmCond::NoCond) ||
1816 TheCondStack.empty())
1817 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
1819 if (!TheCondStack.empty()) {
1820 TheCondState = TheCondStack.back();
1821 TheCondStack.pop_back();
1827 /// ParseDirectiveFile
1828 /// ::= .file [number] string
1829 bool AsmParser::ParseDirectiveFile(StringRef, SMLoc DirectiveLoc) {
1830 // FIXME: I'm not sure what this is.
1831 int64_t FileNumber = -1;
1832 if (Lexer.is(AsmToken::Integer)) {
1833 FileNumber = getTok().getIntVal();
1837 return TokError("file number less than one");
1840 if (Lexer.isNot(AsmToken::String))
1841 return TokError("unexpected token in '.file' directive");
1843 StringRef Filename = getTok().getString();
1844 Filename = Filename.substr(1, Filename.size()-2);
1847 if (Lexer.isNot(AsmToken::EndOfStatement))
1848 return TokError("unexpected token in '.file' directive");
1850 if (FileNumber == -1)
1851 Out.EmitFileDirective(Filename);
1853 Out.EmitDwarfFileDirective(FileNumber, Filename);
1858 /// ParseDirectiveLine
1859 /// ::= .line [number]
1860 bool AsmParser::ParseDirectiveLine(StringRef, SMLoc DirectiveLoc) {
1861 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1862 if (Lexer.isNot(AsmToken::Integer))
1863 return TokError("unexpected token in '.line' directive");
1865 int64_t LineNumber = getTok().getIntVal();
1869 // FIXME: Do something with the .line.
1872 if (Lexer.isNot(AsmToken::EndOfStatement))
1873 return TokError("unexpected token in '.file' directive");
1879 /// ParseDirectiveLoc
1880 /// ::= .loc number [number [number]]
1881 bool AsmParser::ParseDirectiveLoc(StringRef, SMLoc DirectiveLoc) {
1882 if (Lexer.isNot(AsmToken::Integer))
1883 return TokError("unexpected token in '.loc' directive");
1885 // FIXME: What are these fields?
1886 int64_t FileNumber = getTok().getIntVal();
1888 // FIXME: Validate file.
1891 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1892 if (Lexer.isNot(AsmToken::Integer))
1893 return TokError("unexpected token in '.loc' directive");
1895 int64_t Param2 = getTok().getIntVal();
1899 if (Lexer.isNot(AsmToken::EndOfStatement)) {
1900 if (Lexer.isNot(AsmToken::Integer))
1901 return TokError("unexpected token in '.loc' directive");
1903 int64_t Param3 = getTok().getIntVal();
1907 // FIXME: Do something with the .loc.
1911 if (Lexer.isNot(AsmToken::EndOfStatement))
1912 return TokError("unexpected token in '.file' directive");