1 //===-- X86AsmParser.cpp - Parse X86 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 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
34 class X86AsmParser : public MCTargetAsmParser {
39 MCAsmParser &getParser() const { return Parser; }
41 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
43 bool Error(SMLoc L, const Twine &Msg,
44 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) {
45 return Parser.Error(L, Msg, Ranges);
48 X86Operand *ParseOperand();
49 X86Operand *ParseATTOperand();
50 X86Operand *ParseIntelOperand();
51 X86Operand *ParseIntelMemOperand(StringRef TokenString, unsigned Size);
52 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
54 bool ParseDirectiveWord(unsigned Size, SMLoc L);
55 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
57 bool MatchAndEmitInstruction(SMLoc IDLoc,
58 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
61 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
62 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
63 bool isSrcOp(X86Operand &Op);
65 /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
66 /// or %es:(%edi) in 32bit mode.
67 bool isDstOp(X86Operand &Op);
69 bool is64BitMode() const {
70 // FIXME: Can tablegen auto-generate this?
71 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
74 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
75 setAvailableFeatures(FB);
78 /// @name Auto-generated Matcher Functions
81 #define GET_ASSEMBLER_HEADER
82 #include "X86GenAsmMatcher.inc"
87 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
88 : MCTargetAsmParser(), STI(sti), Parser(parser) {
90 // Initialize the set of available features.
91 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
93 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
95 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
96 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
98 virtual bool ParseDirective(AsmToken DirectiveID);
100 } // end anonymous namespace
102 /// @name Auto-generated Match Functions
105 static unsigned MatchRegisterName(StringRef Name);
111 /// X86Operand - Instances of this class represent a parsed X86 machine
113 struct X86Operand : public MCParsedAsmOperand {
121 SMLoc StartLoc, EndLoc;
147 X86Operand(KindTy K, SMLoc Start, SMLoc End)
148 : Kind(K), StartLoc(Start), EndLoc(End) {}
150 /// getStartLoc - Get the location of the first token of this operand.
151 SMLoc getStartLoc() const { return StartLoc; }
152 /// getEndLoc - Get the location of the last token of this operand.
153 SMLoc getEndLoc() const { return EndLoc; }
155 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
157 virtual void print(raw_ostream &OS) const {}
159 StringRef getToken() const {
160 assert(Kind == Token && "Invalid access!");
161 return StringRef(Tok.Data, Tok.Length);
163 void setTokenValue(StringRef Value) {
164 assert(Kind == Token && "Invalid access!");
165 Tok.Data = Value.data();
166 Tok.Length = Value.size();
169 unsigned getReg() const {
170 assert(Kind == Register && "Invalid access!");
174 const MCExpr *getImm() const {
175 assert(Kind == Immediate && "Invalid access!");
179 const MCExpr *getMemDisp() const {
180 assert(Kind == Memory && "Invalid access!");
183 unsigned getMemSegReg() const {
184 assert(Kind == Memory && "Invalid access!");
187 unsigned getMemBaseReg() const {
188 assert(Kind == Memory && "Invalid access!");
191 unsigned getMemIndexReg() const {
192 assert(Kind == Memory && "Invalid access!");
195 unsigned getMemScale() const {
196 assert(Kind == Memory && "Invalid access!");
200 bool isToken() const {return Kind == Token; }
202 bool isImm() const { return Kind == Immediate; }
204 bool isImmSExti16i8() const {
208 // If this isn't a constant expr, just assume it fits and let relaxation
210 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
214 // Otherwise, check the value is in a range that makes sense for this
216 uint64_t Value = CE->getValue();
217 return (( Value <= 0x000000000000007FULL)||
218 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
219 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
221 bool isImmSExti32i8() const {
225 // If this isn't a constant expr, just assume it fits and let relaxation
227 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
231 // Otherwise, check the value is in a range that makes sense for this
233 uint64_t Value = CE->getValue();
234 return (( Value <= 0x000000000000007FULL)||
235 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
236 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
238 bool isImmZExtu32u8() const {
242 // If this isn't a constant expr, just assume it fits and let relaxation
244 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
248 // Otherwise, check the value is in a range that makes sense for this
250 uint64_t Value = CE->getValue();
251 return (Value <= 0x00000000000000FFULL);
253 bool isImmSExti64i8() const {
257 // If this isn't a constant expr, just assume it fits and let relaxation
259 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
263 // Otherwise, check the value is in a range that makes sense for this
265 uint64_t Value = CE->getValue();
266 return (( Value <= 0x000000000000007FULL)||
267 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
269 bool isImmSExti64i32() const {
273 // If this isn't a constant expr, just assume it fits and let relaxation
275 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
279 // Otherwise, check the value is in a range that makes sense for this
281 uint64_t Value = CE->getValue();
282 return (( Value <= 0x000000007FFFFFFFULL)||
283 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
286 bool isMem() const { return Kind == Memory; }
287 bool isMem8() const {
288 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
290 bool isMem16() const {
291 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
293 bool isMem32() const {
294 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
296 bool isMem64() const {
297 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
299 bool isMem80() const {
300 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
302 bool isMem128() const {
303 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
305 bool isMem256() const {
306 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
309 bool isAbsMem() const {
310 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
311 !getMemIndexReg() && getMemScale() == 1;
314 bool isReg() const { return Kind == Register; }
316 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
317 // Add as immediates when possible.
318 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
319 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
321 Inst.addOperand(MCOperand::CreateExpr(Expr));
324 void addRegOperands(MCInst &Inst, unsigned N) const {
325 assert(N == 1 && "Invalid number of operands!");
326 Inst.addOperand(MCOperand::CreateReg(getReg()));
329 void addImmOperands(MCInst &Inst, unsigned N) const {
330 assert(N == 1 && "Invalid number of operands!");
331 addExpr(Inst, getImm());
334 void addMem8Operands(MCInst &Inst, unsigned N) const {
335 addMemOperands(Inst, N);
337 void addMem16Operands(MCInst &Inst, unsigned N) const {
338 addMemOperands(Inst, N);
340 void addMem32Operands(MCInst &Inst, unsigned N) const {
341 addMemOperands(Inst, N);
343 void addMem64Operands(MCInst &Inst, unsigned N) const {
344 addMemOperands(Inst, N);
346 void addMem80Operands(MCInst &Inst, unsigned N) const {
347 addMemOperands(Inst, N);
349 void addMem128Operands(MCInst &Inst, unsigned N) const {
350 addMemOperands(Inst, N);
352 void addMem256Operands(MCInst &Inst, unsigned N) const {
353 addMemOperands(Inst, N);
356 void addMemOperands(MCInst &Inst, unsigned N) const {
357 assert((N == 5) && "Invalid number of operands!");
358 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
359 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
360 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
361 addExpr(Inst, getMemDisp());
362 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
365 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
366 assert((N == 1) && "Invalid number of operands!");
367 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
370 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
371 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
372 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
373 Res->Tok.Data = Str.data();
374 Res->Tok.Length = Str.size();
378 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
379 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
380 Res->Reg.RegNo = RegNo;
384 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
385 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
390 /// Create an absolute memory operand.
391 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
392 SMLoc EndLoc, unsigned Size = 0) {
393 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
395 Res->Mem.Disp = Disp;
396 Res->Mem.BaseReg = 0;
397 Res->Mem.IndexReg = 0;
399 Res->Mem.Size = Size;
403 /// Create a generalized memory operand.
404 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
405 unsigned BaseReg, unsigned IndexReg,
406 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
408 // We should never just have a displacement, that should be parsed as an
409 // absolute memory operand.
410 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
412 // The scale should always be one of {1,2,4,8}.
413 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
415 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
416 Res->Mem.SegReg = SegReg;
417 Res->Mem.Disp = Disp;
418 Res->Mem.BaseReg = BaseReg;
419 Res->Mem.IndexReg = IndexReg;
420 Res->Mem.Scale = Scale;
421 Res->Mem.Size = Size;
426 } // end anonymous namespace.
428 bool X86AsmParser::isSrcOp(X86Operand &Op) {
429 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
431 return (Op.isMem() &&
432 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
433 isa<MCConstantExpr>(Op.Mem.Disp) &&
434 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
435 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
438 bool X86AsmParser::isDstOp(X86Operand &Op) {
439 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
441 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
442 isa<MCConstantExpr>(Op.Mem.Disp) &&
443 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
444 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
447 bool X86AsmParser::ParseRegister(unsigned &RegNo,
448 SMLoc &StartLoc, SMLoc &EndLoc) {
450 const AsmToken &TokPercent = Parser.getTok();
451 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
452 StartLoc = TokPercent.getLoc();
453 Parser.Lex(); // Eat percent token.
455 const AsmToken &Tok = Parser.getTok();
456 if (Tok.isNot(AsmToken::Identifier))
457 return Error(StartLoc, "invalid register name",
458 SMRange(StartLoc, Tok.getEndLoc()));
460 RegNo = MatchRegisterName(Tok.getString());
462 // If the match failed, try the register name as lowercase.
464 RegNo = MatchRegisterName(Tok.getString().lower());
466 if (!is64BitMode()) {
467 // FIXME: This should be done using Requires<In32BitMode> and
468 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
470 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
472 if (RegNo == X86::RIZ ||
473 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
474 X86II::isX86_64NonExtLowByteReg(RegNo) ||
475 X86II::isX86_64ExtendedReg(RegNo))
476 return Error(StartLoc, "register %"
477 + Tok.getString() + " is only available in 64-bit mode",
478 SMRange(StartLoc, Tok.getEndLoc()));
481 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
482 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
484 EndLoc = Tok.getLoc();
485 Parser.Lex(); // Eat 'st'
487 // Check to see if we have '(4)' after %st.
488 if (getLexer().isNot(AsmToken::LParen))
493 const AsmToken &IntTok = Parser.getTok();
494 if (IntTok.isNot(AsmToken::Integer))
495 return Error(IntTok.getLoc(), "expected stack index");
496 switch (IntTok.getIntVal()) {
497 case 0: RegNo = X86::ST0; break;
498 case 1: RegNo = X86::ST1; break;
499 case 2: RegNo = X86::ST2; break;
500 case 3: RegNo = X86::ST3; break;
501 case 4: RegNo = X86::ST4; break;
502 case 5: RegNo = X86::ST5; break;
503 case 6: RegNo = X86::ST6; break;
504 case 7: RegNo = X86::ST7; break;
505 default: return Error(IntTok.getLoc(), "invalid stack index");
508 if (getParser().Lex().isNot(AsmToken::RParen))
509 return Error(Parser.getTok().getLoc(), "expected ')'");
511 EndLoc = Tok.getLoc();
512 Parser.Lex(); // Eat ')'
516 // If this is "db[0-7]", match it as an alias
518 if (RegNo == 0 && Tok.getString().size() == 3 &&
519 Tok.getString().startswith("db")) {
520 switch (Tok.getString()[2]) {
521 case '0': RegNo = X86::DR0; break;
522 case '1': RegNo = X86::DR1; break;
523 case '2': RegNo = X86::DR2; break;
524 case '3': RegNo = X86::DR3; break;
525 case '4': RegNo = X86::DR4; break;
526 case '5': RegNo = X86::DR5; break;
527 case '6': RegNo = X86::DR6; break;
528 case '7': RegNo = X86::DR7; break;
532 EndLoc = Tok.getLoc();
533 Parser.Lex(); // Eat it.
539 return Error(StartLoc, "invalid register name",
540 SMRange(StartLoc, Tok.getEndLoc()));
542 EndLoc = Tok.getEndLoc();
543 Parser.Lex(); // Eat identifier token.
547 X86Operand *X86AsmParser::ParseOperand() {
548 if (getParser().getAssemblerDialect())
549 return ParseIntelOperand();
550 return ParseATTOperand();
553 /// getIntelRegister - If this is an intel register operand
554 /// then return register number, otherwise return 0;
555 static unsigned getIntelRegisterOperand(StringRef Str) {
556 unsigned RegNo = MatchRegisterName(Str);
557 // If the match failed, try the register name as lowercase.
559 RegNo = MatchRegisterName(Str.lower());
563 /// isIntelMemOperand - If this is an intel memory operand
564 /// then return true.
565 static bool isIntelMemOperand(StringRef OpStr, unsigned &Size) {
567 if (OpStr == "BYTE") Size = 8;
568 if (OpStr == "WORD") Size = 16;
569 if (OpStr == "DWORD") Size = 32;
570 if (OpStr == "QWORD") Size = 64;
571 if (OpStr == "XWORD") Size = 80;
572 if (OpStr == "XMMWORD") Size = 128;
573 if (OpStr == "YMMWORD") Size = 256;
577 /// ParseIntelMemOperand - Parse intel style memory operand.
578 X86Operand *X86AsmParser::ParseIntelMemOperand(StringRef TokenString,
580 SMLoc Start = Parser.getTok().getLoc(), End;
581 unsigned SegReg = 0, BaseReg = 0, IndexReg = 0, Scale = 1;
583 if (TokenString == "PTR")
586 Error(Start, "unexpected token!");
590 if (TokenString == "[")
593 Error(Start, "unexpected token!");
597 SMLoc LParenLoc = Parser.getTok().getLoc();
598 BaseReg = getIntelRegisterOperand(TokenString);
600 Error(LParenLoc, "unexpected token!");
604 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
606 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
607 End = Parser.getTok().getLoc();
608 if (TokenString == "]")
611 Error(End, "unexpected token!");
614 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
618 X86Operand *X86AsmParser::ParseIntelOperand() {
620 StringRef TokenString = Parser.getTok().getString();
621 SMLoc Start = Parser.getTok().getLoc(), End;
624 if(unsigned RegNo = getIntelRegisterOperand(TokenString)) {
626 End = Parser.getTok().getLoc();
627 return X86Operand::CreateReg(RegNo, Start, End);
632 if (isIntelMemOperand(TokenString, Size))
633 ParseIntelMemOperand(TokenString, Size);
637 if (!getParser().ParseExpression(Val, End)) {
638 End = Parser.getTok().getLoc();
639 return X86Operand::CreateImm(Val, Start, End);
645 X86Operand *X86AsmParser::ParseATTOperand() {
646 switch (getLexer().getKind()) {
648 // Parse a memory operand with no segment register.
649 return ParseMemOperand(0, Parser.getTok().getLoc());
650 case AsmToken::Percent: {
651 // Read the register.
654 if (ParseRegister(RegNo, Start, End)) return 0;
655 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
656 Error(Start, "%eiz and %riz can only be used as index registers",
657 SMRange(Start, End));
661 // If this is a segment register followed by a ':', then this is the start
662 // of a memory reference, otherwise this is a normal register reference.
663 if (getLexer().isNot(AsmToken::Colon))
664 return X86Operand::CreateReg(RegNo, Start, End);
667 getParser().Lex(); // Eat the colon.
668 return ParseMemOperand(RegNo, Start);
670 case AsmToken::Dollar: {
672 SMLoc Start = Parser.getTok().getLoc(), End;
675 if (getParser().ParseExpression(Val, End))
677 return X86Operand::CreateImm(Val, Start, End);
682 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
683 /// has already been parsed if present.
684 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
686 // We have to disambiguate a parenthesized expression "(4+5)" from the start
687 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
688 // only way to do this without lookahead is to eat the '(' and see what is
690 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
691 if (getLexer().isNot(AsmToken::LParen)) {
693 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
695 // After parsing the base expression we could either have a parenthesized
696 // memory address or not. If not, return now. If so, eat the (.
697 if (getLexer().isNot(AsmToken::LParen)) {
698 // Unless we have a segment register, treat this as an immediate.
700 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
701 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
707 // Okay, we have a '('. We don't know if this is an expression or not, but
708 // so we have to eat the ( to see beyond it.
709 SMLoc LParenLoc = Parser.getTok().getLoc();
710 Parser.Lex(); // Eat the '('.
712 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
713 // Nothing to do here, fall into the code below with the '(' part of the
714 // memory operand consumed.
718 // It must be an parenthesized expression, parse it now.
719 if (getParser().ParseParenExpression(Disp, ExprEnd))
722 // After parsing the base expression we could either have a parenthesized
723 // memory address or not. If not, return now. If so, eat the (.
724 if (getLexer().isNot(AsmToken::LParen)) {
725 // Unless we have a segment register, treat this as an immediate.
727 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
728 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
736 // If we reached here, then we just ate the ( of the memory operand. Process
737 // the rest of the memory operand.
738 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
740 if (getLexer().is(AsmToken::Percent)) {
741 SMLoc StartLoc, EndLoc;
742 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
743 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
744 Error(StartLoc, "eiz and riz can only be used as index registers",
745 SMRange(StartLoc, EndLoc));
750 if (getLexer().is(AsmToken::Comma)) {
751 Parser.Lex(); // Eat the comma.
753 // Following the comma we should have either an index register, or a scale
754 // value. We don't support the later form, but we want to parse it
757 // Not that even though it would be completely consistent to support syntax
758 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
759 if (getLexer().is(AsmToken::Percent)) {
761 if (ParseRegister(IndexReg, L, L)) return 0;
763 if (getLexer().isNot(AsmToken::RParen)) {
764 // Parse the scale amount:
765 // ::= ',' [scale-expression]
766 if (getLexer().isNot(AsmToken::Comma)) {
767 Error(Parser.getTok().getLoc(),
768 "expected comma in scale expression");
771 Parser.Lex(); // Eat the comma.
773 if (getLexer().isNot(AsmToken::RParen)) {
774 SMLoc Loc = Parser.getTok().getLoc();
777 if (getParser().ParseAbsoluteExpression(ScaleVal))
780 // Validate the scale amount.
781 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
782 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
785 Scale = (unsigned)ScaleVal;
788 } else if (getLexer().isNot(AsmToken::RParen)) {
789 // A scale amount without an index is ignored.
791 SMLoc Loc = Parser.getTok().getLoc();
794 if (getParser().ParseAbsoluteExpression(Value))
798 Warning(Loc, "scale factor without index register is ignored");
803 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
804 if (getLexer().isNot(AsmToken::RParen)) {
805 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
808 SMLoc MemEnd = Parser.getTok().getLoc();
809 Parser.Lex(); // Eat the ')'.
811 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
816 ParseInstruction(StringRef Name, SMLoc NameLoc,
817 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
818 StringRef PatchedName = Name;
820 // FIXME: Hack to recognize setneb as setne.
821 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
822 PatchedName != "setb" && PatchedName != "setnb")
823 PatchedName = PatchedName.substr(0, Name.size()-1);
825 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
826 const MCExpr *ExtraImmOp = 0;
827 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
828 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
829 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
830 bool IsVCMP = PatchedName.startswith("vcmp");
831 unsigned SSECCIdx = IsVCMP ? 4 : 3;
832 unsigned SSEComparisonCode = StringSwitch<unsigned>(
833 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
846 .Case("neq_oq", 0x0C)
853 .Case("unord_s", 0x13)
854 .Case("neq_us", 0x14)
855 .Case("nlt_uq", 0x15)
856 .Case("nle_uq", 0x16)
859 .Case("nge_uq", 0x19)
860 .Case("ngt_uq", 0x1A)
861 .Case("false_os", 0x1B)
862 .Case("neq_os", 0x1C)
865 .Case("true_us", 0x1F)
867 if (SSEComparisonCode != ~0U) {
868 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
869 getParser().getContext());
870 if (PatchedName.endswith("ss")) {
871 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
872 } else if (PatchedName.endswith("sd")) {
873 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
874 } else if (PatchedName.endswith("ps")) {
875 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
877 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
878 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
883 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
886 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
889 // Determine whether this is an instruction prefix.
891 Name == "lock" || Name == "rep" ||
892 Name == "repe" || Name == "repz" ||
893 Name == "repne" || Name == "repnz" ||
894 Name == "rex64" || Name == "data16";
897 // This does the actual operand parsing. Don't parse any more if we have a
898 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
899 // just want to parse the "lock" as the first instruction and the "incl" as
901 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
903 // Parse '*' modifier.
904 if (getLexer().is(AsmToken::Star)) {
905 SMLoc Loc = Parser.getTok().getLoc();
906 Operands.push_back(X86Operand::CreateToken("*", Loc));
907 Parser.Lex(); // Eat the star.
910 // Read the first operand.
911 if (X86Operand *Op = ParseOperand())
912 Operands.push_back(Op);
914 Parser.EatToEndOfStatement();
918 while (getLexer().is(AsmToken::Comma)) {
919 Parser.Lex(); // Eat the comma.
921 // Parse and remember the operand.
922 if (X86Operand *Op = ParseOperand())
923 Operands.push_back(Op);
925 Parser.EatToEndOfStatement();
930 if (getLexer().isNot(AsmToken::EndOfStatement)) {
931 SMLoc Loc = getLexer().getLoc();
932 Parser.EatToEndOfStatement();
933 return Error(Loc, "unexpected token in argument list");
937 if (getLexer().is(AsmToken::EndOfStatement))
938 Parser.Lex(); // Consume the EndOfStatement
939 else if (isPrefix && getLexer().is(AsmToken::Slash))
940 Parser.Lex(); // Consume the prefix separator Slash
942 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
943 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
944 // documented form in various unofficial manuals, so a lot of code uses it.
945 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
946 Operands.size() == 3) {
947 X86Operand &Op = *(X86Operand*)Operands.back();
948 if (Op.isMem() && Op.Mem.SegReg == 0 &&
949 isa<MCConstantExpr>(Op.Mem.Disp) &&
950 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
951 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
952 SMLoc Loc = Op.getEndLoc();
953 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
957 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
958 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
959 Operands.size() == 3) {
960 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
961 if (Op.isMem() && Op.Mem.SegReg == 0 &&
962 isa<MCConstantExpr>(Op.Mem.Disp) &&
963 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
964 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
965 SMLoc Loc = Op.getEndLoc();
966 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
970 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
971 if (Name.startswith("ins") && Operands.size() == 3 &&
972 (Name == "insb" || Name == "insw" || Name == "insl")) {
973 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
974 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
975 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
983 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
984 if (Name.startswith("outs") && Operands.size() == 3 &&
985 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
986 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
987 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
988 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
996 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
997 if (Name.startswith("movs") && Operands.size() == 3 &&
998 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
999 (is64BitMode() && Name == "movsq"))) {
1000 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1001 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1002 if (isSrcOp(Op) && isDstOp(Op2)) {
1003 Operands.pop_back();
1004 Operands.pop_back();
1009 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1010 if (Name.startswith("lods") && Operands.size() == 3 &&
1011 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1012 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1013 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1014 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1015 if (isSrcOp(*Op1) && Op2->isReg()) {
1017 unsigned reg = Op2->getReg();
1018 bool isLods = Name == "lods";
1019 if (reg == X86::AL && (isLods || Name == "lodsb"))
1021 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1023 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1025 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1030 Operands.pop_back();
1031 Operands.pop_back();
1035 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1039 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1040 if (Name.startswith("stos") && Operands.size() == 3 &&
1041 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1042 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1043 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1044 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1045 if (isDstOp(*Op2) && Op1->isReg()) {
1047 unsigned reg = Op1->getReg();
1048 bool isStos = Name == "stos";
1049 if (reg == X86::AL && (isStos || Name == "stosb"))
1051 else if (reg == X86::AX && (isStos || Name == "stosw"))
1053 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1055 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1060 Operands.pop_back();
1061 Operands.pop_back();
1065 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1070 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1072 if ((Name.startswith("shr") || Name.startswith("sar") ||
1073 Name.startswith("shl") || Name.startswith("sal") ||
1074 Name.startswith("rcl") || Name.startswith("rcr") ||
1075 Name.startswith("rol") || Name.startswith("ror")) &&
1076 Operands.size() == 3) {
1077 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1078 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1079 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1081 Operands.erase(Operands.begin() + 1);
1085 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1086 // instalias with an immediate operand yet.
1087 if (Name == "int" && Operands.size() == 2) {
1088 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1089 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1090 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1092 Operands.erase(Operands.begin() + 1);
1093 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1101 MatchAndEmitInstruction(SMLoc IDLoc,
1102 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1104 assert(!Operands.empty() && "Unexpect empty operand list!");
1105 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1106 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1108 // First, handle aliases that expand to multiple instructions.
1109 // FIXME: This should be replaced with a real .td file alias mechanism.
1110 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1112 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1113 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1114 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1115 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1117 Inst.setOpcode(X86::WAIT);
1118 Out.EmitInstruction(Inst);
1121 StringSwitch<const char*>(Op->getToken())
1122 .Case("finit", "fninit")
1123 .Case("fsave", "fnsave")
1124 .Case("fstcw", "fnstcw")
1125 .Case("fstcww", "fnstcw")
1126 .Case("fstenv", "fnstenv")
1127 .Case("fstsw", "fnstsw")
1128 .Case("fstsww", "fnstsw")
1129 .Case("fclex", "fnclex")
1131 assert(Repl && "Unknown wait-prefixed instruction");
1133 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1136 bool WasOriginallyInvalidOperand = false;
1137 unsigned OrigErrorInfo;
1140 // First, try a direct match.
1141 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo,
1142 getParser().getAssemblerDialect())) {
1145 Out.EmitInstruction(Inst);
1147 case Match_MissingFeature:
1148 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1150 case Match_ConversionFail:
1151 return Error(IDLoc, "unable to convert operands to instruction");
1152 case Match_InvalidOperand:
1153 WasOriginallyInvalidOperand = true;
1155 case Match_MnemonicFail:
1159 // FIXME: Ideally, we would only attempt suffix matches for things which are
1160 // valid prefixes, and we could just infer the right unambiguous
1161 // type. However, that requires substantially more matcher support than the
1164 // Change the operand to point to a temporary token.
1165 StringRef Base = Op->getToken();
1166 SmallString<16> Tmp;
1169 Op->setTokenValue(Tmp.str());
1171 // If this instruction starts with an 'f', then it is a floating point stack
1172 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1173 // 80-bit floating point, which use the suffixes s,l,t respectively.
1175 // Otherwise, we assume that this may be an integer instruction, which comes
1176 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1177 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1179 // Check for the various suffix matches.
1180 Tmp[Base.size()] = Suffixes[0];
1181 unsigned ErrorInfoIgnore;
1182 unsigned Match1, Match2, Match3, Match4;
1184 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1185 Tmp[Base.size()] = Suffixes[1];
1186 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1187 Tmp[Base.size()] = Suffixes[2];
1188 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1189 Tmp[Base.size()] = Suffixes[3];
1190 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1192 // Restore the old token.
1193 Op->setTokenValue(Base);
1195 // If exactly one matched, then we treat that as a successful match (and the
1196 // instruction will already have been filled in correctly, since the failing
1197 // matches won't have modified it).
1198 unsigned NumSuccessfulMatches =
1199 (Match1 == Match_Success) + (Match2 == Match_Success) +
1200 (Match3 == Match_Success) + (Match4 == Match_Success);
1201 if (NumSuccessfulMatches == 1) {
1202 Out.EmitInstruction(Inst);
1206 // Otherwise, the match failed, try to produce a decent error message.
1208 // If we had multiple suffix matches, then identify this as an ambiguous
1210 if (NumSuccessfulMatches > 1) {
1212 unsigned NumMatches = 0;
1213 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1214 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1215 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1216 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1218 SmallString<126> Msg;
1219 raw_svector_ostream OS(Msg);
1220 OS << "ambiguous instructions require an explicit suffix (could be ";
1221 for (unsigned i = 0; i != NumMatches; ++i) {
1224 if (i + 1 == NumMatches)
1226 OS << "'" << Base << MatchChars[i] << "'";
1229 Error(IDLoc, OS.str());
1233 // Okay, we know that none of the variants matched successfully.
1235 // If all of the instructions reported an invalid mnemonic, then the original
1236 // mnemonic was invalid.
1237 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1238 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1239 if (!WasOriginallyInvalidOperand) {
1240 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1244 // Recover location info for the operand if we know which was the problem.
1245 if (OrigErrorInfo != ~0U) {
1246 if (OrigErrorInfo >= Operands.size())
1247 return Error(IDLoc, "too few operands for instruction");
1249 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1250 if (Operand->getStartLoc().isValid()) {
1251 SMRange OperandRange = Operand->getLocRange();
1252 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1257 return Error(IDLoc, "invalid operand for instruction");
1260 // If one instruction matched with a missing feature, report this as a
1262 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1263 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1264 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1268 // If one instruction matched with an invalid operand, report this as an
1270 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1271 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1272 Error(IDLoc, "invalid operand for instruction");
1276 // If all of these were an outright failure, report it in a useless way.
1277 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1282 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1283 StringRef IDVal = DirectiveID.getIdentifier();
1284 if (IDVal == ".word")
1285 return ParseDirectiveWord(2, DirectiveID.getLoc());
1286 else if (IDVal.startswith(".code"))
1287 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1291 /// ParseDirectiveWord
1292 /// ::= .word [ expression (, expression)* ]
1293 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1294 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1296 const MCExpr *Value;
1297 if (getParser().ParseExpression(Value))
1300 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1302 if (getLexer().is(AsmToken::EndOfStatement))
1305 // FIXME: Improve diagnostic.
1306 if (getLexer().isNot(AsmToken::Comma))
1307 return Error(L, "unexpected token in directive");
1316 /// ParseDirectiveCode
1317 /// ::= .code32 | .code64
1318 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1319 if (IDVal == ".code32") {
1321 if (is64BitMode()) {
1323 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1325 } else if (IDVal == ".code64") {
1327 if (!is64BitMode()) {
1329 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1332 return Error(L, "unexpected directive " + IDVal);
1339 extern "C" void LLVMInitializeX86AsmLexer();
1341 // Force static initialization.
1342 extern "C" void LLVMInitializeX86AsmParser() {
1343 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1344 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1345 LLVMInitializeX86AsmLexer();
1348 #define GET_REGISTER_MATCHER
1349 #define GET_MATCHER_IMPLEMENTATION
1350 #include "X86GenAsmMatcher.inc"