1 //===-- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions ------===//
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 //===----------------------------------------------------------------------===//
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmLexer.h"
14 #include "llvm/MC/MCAsmParser.h"
15 #include "llvm/MC/MCParsedAsmOperand.h"
16 #include "llvm/MC/MCStreamer.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/SourceMgr.h"
21 #include "llvm/Target/TargetRegistry.h"
22 #include "llvm/Target/TargetAsmParser.h"
28 // The shift types for register controlled shifts in arm memory addressing
37 class ARMAsmParser : public TargetAsmParser {
41 MCAsmParser &getParser() const { return Parser; }
43 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
45 void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
47 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
49 bool MaybeParseRegister(ARMOperand &Op, bool ParseWriteBack);
51 bool ParseRegisterList(ARMOperand &Op);
53 bool ParseMemory(ARMOperand &Op);
55 bool ParseMemoryOffsetReg(bool &Negative,
56 bool &OffsetRegShifted,
57 enum ShiftType &ShiftType,
58 const MCExpr *&ShiftAmount,
59 const MCExpr *&Offset,
63 bool ParseShift(enum ShiftType &St, const MCExpr *&ShiftAmount);
65 bool ParseOperand(ARMOperand &Op);
67 bool ParseDirectiveWord(unsigned Size, SMLoc L);
69 bool ParseDirectiveThumb(SMLoc L);
71 bool ParseDirectiveThumbFunc(SMLoc L);
73 bool ParseDirectiveCode(SMLoc L);
75 bool ParseDirectiveSyntax(SMLoc L);
77 // TODO - For now hacked versions of the next two are in here in this file to
78 // allow some parser testing until the table gen versions are implemented.
80 /// @name Auto-generated Match Functions
82 bool MatchInstruction(const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
85 /// MatchRegisterName - Match the given string to a register name and return
86 /// its register number, or -1 if there is no match. To allow return values
87 /// to be used directly in register lists, arm registers have values between
89 int MatchRegisterName(const StringRef &Name);
95 ARMAsmParser(const Target &T, MCAsmParser &_Parser)
96 : TargetAsmParser(T), Parser(_Parser) {}
98 virtual bool ParseInstruction(const StringRef &Name, SMLoc NameLoc,
99 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
101 virtual bool ParseDirective(AsmToken DirectiveID);
104 /// ARMOperand - Instances of this class represent a parsed ARM machine
106 struct ARMOperand : public MCParsedAsmOperand {
130 // This is for all forms of ARM address expressions
133 unsigned OffsetRegNum; // used when OffsetIsReg is true
134 const MCExpr *Offset; // used when OffsetIsReg is false
135 const MCExpr *ShiftAmount; // used when OffsetRegShifted is true
136 enum ShiftType ShiftType; // used when OffsetRegShifted is true
138 OffsetRegShifted : 1, // only used when OffsetIsReg is true
142 Negative : 1, // only used when OffsetIsReg is true
148 StringRef getToken() const {
149 assert(Kind == Token && "Invalid access!");
150 return StringRef(Tok.Data, Tok.Length);
153 unsigned getReg() const {
154 assert(Kind == Register && "Invalid access!");
158 const MCExpr *getImm() const {
159 assert(Kind == Immediate && "Invalid access!");
163 bool isToken() const {return Kind == Token; }
165 bool isReg() const { return Kind == Register; }
167 void addRegOperands(MCInst &Inst, unsigned N) const {
168 assert(N == 1 && "Invalid number of operands!");
169 Inst.addOperand(MCOperand::CreateReg(getReg()));
172 static ARMOperand CreateToken(StringRef Str) {
175 Res.Tok.Data = Str.data();
176 Res.Tok.Length = Str.size();
180 static ARMOperand CreateReg(unsigned RegNum, bool Writeback) {
183 Res.Reg.RegNum = RegNum;
184 Res.Reg.Writeback = Writeback;
188 static ARMOperand CreateImm(const MCExpr *Val) {
190 Res.Kind = Immediate;
195 static ARMOperand CreateMem(unsigned BaseRegNum, bool OffsetIsReg,
196 const MCExpr *Offset, unsigned OffsetRegNum,
197 bool OffsetRegShifted, enum ShiftType ShiftType,
198 const MCExpr *ShiftAmount, bool Preindexed,
199 bool Postindexed, bool Negative, bool Writeback) {
202 Res.Mem.BaseRegNum = BaseRegNum;
203 Res.Mem.OffsetIsReg = OffsetIsReg;
204 Res.Mem.Offset = Offset;
205 Res.Mem.OffsetRegNum = OffsetRegNum;
206 Res.Mem.OffsetRegShifted = OffsetRegShifted;
207 Res.Mem.ShiftType = ShiftType;
208 Res.Mem.ShiftAmount = ShiftAmount;
209 Res.Mem.Preindexed = Preindexed;
210 Res.Mem.Postindexed = Postindexed;
211 Res.Mem.Negative = Negative;
212 Res.Mem.Writeback = Writeback;
217 } // end anonymous namespace.
219 /// Try to parse a register name. The token must be an Identifier when called,
220 /// and if it is a register name a Reg operand is created, the token is eaten
221 /// and false is returned. Else true is returned and no token is eaten.
222 /// TODO this is likely to change to allow different register types and or to
223 /// parse for a specific register type.
224 bool ARMAsmParser::MaybeParseRegister(ARMOperand &Op, bool ParseWriteBack) {
225 const AsmToken &Tok = getLexer().getTok();
226 assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
228 // FIXME: Validate register for the current architecture; we have to do
229 // validation later, so maybe there is no need for this here.
232 RegNum = MatchRegisterName(Tok.getString());
235 getLexer().Lex(); // Eat identifier token.
237 bool Writeback = false;
238 if (ParseWriteBack) {
239 const AsmToken &ExclaimTok = getLexer().getTok();
240 if (ExclaimTok.is(AsmToken::Exclaim)) {
242 getLexer().Lex(); // Eat exclaim token
246 Op = ARMOperand::CreateReg(RegNum, Writeback);
251 /// Parse a register list, return false if successful else return true or an
252 /// error. The first token must be a '{' when called.
253 bool ARMAsmParser::ParseRegisterList(ARMOperand &Op) {
254 assert(getLexer().getTok().is(AsmToken::LCurly) &&
255 "Token is not an Left Curly Brace");
256 getLexer().Lex(); // Eat left curly brace token.
258 const AsmToken &RegTok = getLexer().getTok();
259 SMLoc RegLoc = RegTok.getLoc();
260 if (RegTok.isNot(AsmToken::Identifier))
261 return Error(RegLoc, "register expected");
262 int RegNum = MatchRegisterName(RegTok.getString());
264 return Error(RegLoc, "register expected");
265 getLexer().Lex(); // Eat identifier token.
266 unsigned RegList = 1 << RegNum;
268 int HighRegNum = RegNum;
269 // TODO ranges like "{Rn-Rm}"
270 while (getLexer().getTok().is(AsmToken::Comma)) {
271 getLexer().Lex(); // Eat comma token.
273 const AsmToken &RegTok = getLexer().getTok();
274 SMLoc RegLoc = RegTok.getLoc();
275 if (RegTok.isNot(AsmToken::Identifier))
276 return Error(RegLoc, "register expected");
277 int RegNum = MatchRegisterName(RegTok.getString());
279 return Error(RegLoc, "register expected");
281 if (RegList & (1 << RegNum))
282 Warning(RegLoc, "register duplicated in register list");
283 else if (RegNum <= HighRegNum)
284 Warning(RegLoc, "register not in ascending order in register list");
285 RegList |= 1 << RegNum;
288 getLexer().Lex(); // Eat identifier token.
290 const AsmToken &RCurlyTok = getLexer().getTok();
291 if (RCurlyTok.isNot(AsmToken::RCurly))
292 return Error(RCurlyTok.getLoc(), "'}' expected");
293 getLexer().Lex(); // Eat left curly brace token.
298 /// Parse an arm memory expression, return false if successful else return true
299 /// or an error. The first token must be a '[' when called.
300 /// TODO Only preindexing and postindexing addressing are started, unindexed
301 /// with option, etc are still to do.
302 bool ARMAsmParser::ParseMemory(ARMOperand &Op) {
303 assert(getLexer().getTok().is(AsmToken::LBrac) &&
304 "Token is not an Left Bracket");
305 getLexer().Lex(); // Eat left bracket token.
307 const AsmToken &BaseRegTok = getLexer().getTok();
308 if (BaseRegTok.isNot(AsmToken::Identifier))
309 return Error(BaseRegTok.getLoc(), "register expected");
310 if (MaybeParseRegister(Op, false))
311 return Error(BaseRegTok.getLoc(), "register expected");
312 int BaseRegNum = Op.getReg();
314 bool Preindexed = false;
315 bool Postindexed = false;
316 bool OffsetIsReg = false;
317 bool Negative = false;
318 bool Writeback = false;
320 // First look for preindexed address forms, that is after the "[Rn" we now
321 // have to see if the next token is a comma.
322 const AsmToken &Tok = getLexer().getTok();
323 if (Tok.is(AsmToken::Comma)) {
325 getLexer().Lex(); // Eat comma token.
327 bool OffsetRegShifted;
328 enum ShiftType ShiftType;
329 const MCExpr *ShiftAmount;
330 const MCExpr *Offset;
331 if(ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
332 Offset, OffsetIsReg, OffsetRegNum))
334 const AsmToken &RBracTok = getLexer().getTok();
335 if (RBracTok.isNot(AsmToken::RBrac))
336 return Error(RBracTok.getLoc(), "']' expected");
337 getLexer().Lex(); // Eat right bracket token.
339 const AsmToken &ExclaimTok = getLexer().getTok();
340 if (ExclaimTok.is(AsmToken::Exclaim)) {
342 getLexer().Lex(); // Eat exclaim token
344 Op = ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset, OffsetRegNum,
345 OffsetRegShifted, ShiftType, ShiftAmount,
346 Preindexed, Postindexed, Negative, Writeback);
349 // The "[Rn" we have so far was not followed by a comma.
350 else if (Tok.is(AsmToken::RBrac)) {
351 // This is a post indexing addressing forms, that is a ']' follows after
355 getLexer().Lex(); // Eat right bracket token.
357 int OffsetRegNum = 0;
358 bool OffsetRegShifted = false;
359 enum ShiftType ShiftType;
360 const MCExpr *ShiftAmount;
361 const MCExpr *Offset;
363 const AsmToken &NextTok = getLexer().getTok();
364 if (NextTok.isNot(AsmToken::EndOfStatement)) {
365 if (NextTok.isNot(AsmToken::Comma))
366 return Error(NextTok.getLoc(), "',' expected");
367 getLexer().Lex(); // Eat comma token.
368 if(ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
369 ShiftAmount, Offset, OffsetIsReg, OffsetRegNum))
373 Op = ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset, OffsetRegNum,
374 OffsetRegShifted, ShiftType, ShiftAmount,
375 Preindexed, Postindexed, Negative, Writeback);
382 /// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
383 /// we will parse the following (were +/- means that a plus or minus is
388 /// we return false on success or an error otherwise.
389 bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative,
390 bool &OffsetRegShifted,
391 enum ShiftType &ShiftType,
392 const MCExpr *&ShiftAmount,
393 const MCExpr *&Offset,
398 OffsetRegShifted = false;
401 const AsmToken &NextTok = getLexer().getTok();
402 if (NextTok.is(AsmToken::Plus))
403 getLexer().Lex(); // Eat plus token.
404 else if (NextTok.is(AsmToken::Minus)) {
406 getLexer().Lex(); // Eat minus token
408 // See if there is a register following the "[Rn," or "[Rn]," we have so far.
409 const AsmToken &OffsetRegTok = getLexer().getTok();
410 if (OffsetRegTok.is(AsmToken::Identifier)) {
411 OffsetIsReg = !MaybeParseRegister(Op, false);
413 OffsetRegNum = Op.getReg();
415 // If we parsed a register as the offset then their can be a shift after that
416 if (OffsetRegNum != -1) {
417 // Look for a comma then a shift
418 const AsmToken &Tok = getLexer().getTok();
419 if (Tok.is(AsmToken::Comma)) {
420 getLexer().Lex(); // Eat comma token.
422 const AsmToken &Tok = getLexer().getTok();
423 if (ParseShift(ShiftType, ShiftAmount))
424 return Error(Tok.getLoc(), "shift expected");
425 OffsetRegShifted = true;
428 else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
429 // Look for #offset following the "[Rn," or "[Rn],"
430 const AsmToken &HashTok = getLexer().getTok();
431 if (HashTok.isNot(AsmToken::Hash))
432 return Error(HashTok.getLoc(), "'#' expected");
433 getLexer().Lex(); // Eat hash token.
435 if (getParser().ParseExpression(Offset))
441 /// ParseShift as one of these two:
442 /// ( lsl | lsr | asr | ror ) , # shift_amount
444 /// and returns true if it parses a shift otherwise it returns false.
445 bool ARMAsmParser::ParseShift(ShiftType &St, const MCExpr *&ShiftAmount) {
446 const AsmToken &Tok = getLexer().getTok();
447 if (Tok.isNot(AsmToken::Identifier))
449 const StringRef &ShiftName = Tok.getString();
450 if (ShiftName == "lsl" || ShiftName == "LSL")
452 else if (ShiftName == "lsr" || ShiftName == "LSR")
454 else if (ShiftName == "asr" || ShiftName == "ASR")
456 else if (ShiftName == "ror" || ShiftName == "ROR")
458 else if (ShiftName == "rrx" || ShiftName == "RRX")
462 getLexer().Lex(); // Eat shift type token.
468 // Otherwise, there must be a '#' and a shift amount.
469 const AsmToken &HashTok = getLexer().getTok();
470 if (HashTok.isNot(AsmToken::Hash))
471 return Error(HashTok.getLoc(), "'#' expected");
472 getLexer().Lex(); // Eat hash token.
474 if (getParser().ParseExpression(ShiftAmount))
480 /// A hack to allow some testing, to be replaced by a real table gen version.
481 int ARMAsmParser::MatchRegisterName(const StringRef &Name) {
482 if (Name == "r0" || Name == "R0")
484 else if (Name == "r1" || Name == "R1")
486 else if (Name == "r2" || Name == "R2")
488 else if (Name == "r3" || Name == "R3")
490 else if (Name == "r3" || Name == "R3")
492 else if (Name == "r4" || Name == "R4")
494 else if (Name == "r5" || Name == "R5")
496 else if (Name == "r6" || Name == "R6")
498 else if (Name == "r7" || Name == "R7")
500 else if (Name == "r8" || Name == "R8")
502 else if (Name == "r9" || Name == "R9")
504 else if (Name == "r10" || Name == "R10")
506 else if (Name == "r11" || Name == "R11" || Name == "fp")
508 else if (Name == "r12" || Name == "R12" || Name == "ip")
510 else if (Name == "r13" || Name == "R13" || Name == "sp")
512 else if (Name == "r14" || Name == "R14" || Name == "lr")
514 else if (Name == "r15" || Name == "R15" || Name == "pc")
519 /// A hack to allow some testing, to be replaced by a real table gen version.
521 MatchInstruction(const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
523 ARMOperand &Op0 = *(ARMOperand*)Operands[0];
524 assert(Op0.Kind == ARMOperand::Token && "First operand not a Token");
525 const StringRef &Mnemonic = Op0.getToken();
526 if (Mnemonic == "add" ||
527 Mnemonic == "stmfd" ||
529 Mnemonic == "ldmfd" ||
534 Mnemonic == "push" ||
537 // Hard-coded to a valid instruction, till we have a real matcher.
539 Inst.setOpcode(ARM::MOVr);
540 Inst.addOperand(MCOperand::CreateReg(2));
541 Inst.addOperand(MCOperand::CreateReg(2));
542 Inst.addOperand(MCOperand::CreateImm(0));
543 Inst.addOperand(MCOperand::CreateImm(0));
544 Inst.addOperand(MCOperand::CreateReg(0));
551 /// Parse a arm instruction operand. For now this parses the operand regardless
553 bool ARMAsmParser::ParseOperand(ARMOperand &Op) {
554 switch (getLexer().getKind()) {
555 case AsmToken::Identifier:
556 if (!MaybeParseRegister(Op, true))
558 // This was not a register so parse other operands that start with an
559 // identifier (like labels) as expressions and create them as immediates.
561 if (getParser().ParseExpression(IdVal))
563 Op = ARMOperand::CreateImm(IdVal);
565 case AsmToken::LBrac:
566 return ParseMemory(Op);
567 case AsmToken::LCurly:
568 return ParseRegisterList(Op);
571 // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
573 const MCExpr *ImmVal;
574 if (getParser().ParseExpression(ImmVal))
576 Op = ARMOperand::CreateImm(ImmVal);
579 return Error(getLexer().getTok().getLoc(), "unexpected token in operand");
583 /// Parse an arm instruction mnemonic followed by its operands.
584 bool ARMAsmParser::ParseInstruction(const StringRef &Name, SMLoc NameLoc,
585 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
586 Operands.push_back(new ARMOperand(ARMOperand::CreateToken(Name)));
588 SMLoc Loc = getLexer().getTok().getLoc();
589 if (getLexer().isNot(AsmToken::EndOfStatement)) {
591 // Read the first operand.
593 if (ParseOperand(Op)) return true;
594 Operands.push_back(new ARMOperand(Op));
596 while (getLexer().is(AsmToken::Comma)) {
597 getLexer().Lex(); // Eat the comma.
599 // Parse and remember the operand.
600 if (ParseOperand(Op)) return true;
601 Operands.push_back(new ARMOperand(Op));
607 /// ParseDirective parses the arm specific directives
608 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
609 StringRef IDVal = DirectiveID.getIdentifier();
610 if (IDVal == ".word")
611 return ParseDirectiveWord(4, DirectiveID.getLoc());
612 else if (IDVal == ".thumb")
613 return ParseDirectiveThumb(DirectiveID.getLoc());
614 else if (IDVal == ".thumb_func")
615 return ParseDirectiveThumbFunc(DirectiveID.getLoc());
616 else if (IDVal == ".code")
617 return ParseDirectiveCode(DirectiveID.getLoc());
618 else if (IDVal == ".syntax")
619 return ParseDirectiveSyntax(DirectiveID.getLoc());
623 /// ParseDirectiveWord
624 /// ::= .word [ expression (, expression)* ]
625 bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
626 if (getLexer().isNot(AsmToken::EndOfStatement)) {
629 if (getParser().ParseExpression(Value))
632 getParser().getStreamer().EmitValue(Value, Size);
634 if (getLexer().is(AsmToken::EndOfStatement))
637 // FIXME: Improve diagnostic.
638 if (getLexer().isNot(AsmToken::Comma))
639 return Error(L, "unexpected token in directive");
648 /// ParseDirectiveThumb
650 bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) {
651 if (getLexer().isNot(AsmToken::EndOfStatement))
652 return Error(L, "unexpected token in directive");
655 // TODO: set thumb mode
656 // TODO: tell the MC streamer the mode
657 // getParser().getStreamer().Emit???();
661 /// ParseDirectiveThumbFunc
662 /// ::= .thumbfunc symbol_name
663 bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) {
664 const AsmToken &Tok = getLexer().getTok();
665 if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
666 return Error(L, "unexpected token in .syntax directive");
667 StringRef ATTRIBUTE_UNUSED SymbolName = getLexer().getTok().getIdentifier();
668 getLexer().Lex(); // Consume the identifier token.
670 if (getLexer().isNot(AsmToken::EndOfStatement))
671 return Error(L, "unexpected token in directive");
674 // TODO: mark symbol as a thumb symbol
675 // getParser().getStreamer().Emit???();
679 /// ParseDirectiveSyntax
680 /// ::= .syntax unified | divided
681 bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) {
682 const AsmToken &Tok = getLexer().getTok();
683 if (Tok.isNot(AsmToken::Identifier))
684 return Error(L, "unexpected token in .syntax directive");
685 const StringRef &Mode = Tok.getString();
687 if (Mode == "unified" || Mode == "UNIFIED") {
689 unified_syntax = true;
691 else if (Mode == "divided" || Mode == "DIVIDED") {
693 unified_syntax = false;
696 return Error(L, "unrecognized syntax mode in .syntax directive");
698 if (getLexer().isNot(AsmToken::EndOfStatement))
699 return Error(getLexer().getTok().getLoc(), "unexpected token in directive");
702 // TODO tell the MC streamer the mode
703 // getParser().getStreamer().Emit???();
707 /// ParseDirectiveCode
708 /// ::= .code 16 | 32
709 bool ARMAsmParser::ParseDirectiveCode(SMLoc L) {
710 const AsmToken &Tok = getLexer().getTok();
711 if (Tok.isNot(AsmToken::Integer))
712 return Error(L, "unexpected token in .code directive");
713 int64_t Val = getLexer().getTok().getIntVal();
719 else if (Val == 32) {
724 return Error(L, "invalid operand to .code directive");
726 if (getLexer().isNot(AsmToken::EndOfStatement))
727 return Error(getLexer().getTok().getLoc(), "unexpected token in directive");
730 // TODO tell the MC streamer the mode
731 // getParser().getStreamer().Emit???();
735 /// Force static initialization.
736 extern "C" void LLVMInitializeARMAsmParser() {
737 RegisterAsmParser<ARMAsmParser> X(TheARMTarget);
738 RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget);