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 "llvm/Target/TargetAsmParser.h"
12 #include "X86Subtarget.h"
13 #include "llvm/Target/TargetRegistry.h"
14 #include "llvm/Target/TargetAsmParser.h"
15 #include "llvm/MC/MCStreamer.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCAsmParser.h"
20 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
33 class X86ATTAsmParser : public TargetAsmParser {
41 MCAsmParser &getParser() const { return Parser; }
43 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
45 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
47 X86Operand *ParseOperand();
48 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
50 bool ParseDirectiveWord(unsigned Size, SMLoc L);
52 bool MatchAndEmitInstruction(SMLoc IDLoc,
53 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
56 /// @name Auto-generated Matcher Functions
59 #define GET_ASSEMBLER_HEADER
60 #include "X86GenAsmMatcher.inc"
65 X86ATTAsmParser(const Target &T, MCAsmParser &parser, TargetMachine &TM)
66 : TargetAsmParser(T), Parser(parser), TM(TM) {
68 // Initialize the set of available features.
69 setAvailableFeatures(ComputeAvailableFeatures(
70 &TM.getSubtarget<X86Subtarget>()));
72 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
74 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
75 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
77 virtual bool ParseDirective(AsmToken DirectiveID);
80 class X86_32ATTAsmParser : public X86ATTAsmParser {
82 X86_32ATTAsmParser(const Target &T, MCAsmParser &Parser, TargetMachine &TM)
83 : X86ATTAsmParser(T, Parser, TM) {
88 class X86_64ATTAsmParser : public X86ATTAsmParser {
90 X86_64ATTAsmParser(const Target &T, MCAsmParser &Parser, TargetMachine &TM)
91 : X86ATTAsmParser(T, Parser, TM) {
96 } // end anonymous namespace
98 /// @name Auto-generated Match Functions
101 static unsigned MatchRegisterName(StringRef Name);
107 /// X86Operand - Instances of this class represent a parsed X86 machine
109 struct X86Operand : public MCParsedAsmOperand {
117 SMLoc StartLoc, EndLoc;
142 X86Operand(KindTy K, SMLoc Start, SMLoc End)
143 : Kind(K), StartLoc(Start), EndLoc(End) {}
145 /// getStartLoc - Get the location of the first token of this operand.
146 SMLoc getStartLoc() const { return StartLoc; }
147 /// getEndLoc - Get the location of the last token of this operand.
148 SMLoc getEndLoc() const { return EndLoc; }
150 virtual void dump(raw_ostream &OS) const {}
152 StringRef getToken() const {
153 assert(Kind == Token && "Invalid access!");
154 return StringRef(Tok.Data, Tok.Length);
156 void setTokenValue(StringRef Value) {
157 assert(Kind == Token && "Invalid access!");
158 Tok.Data = Value.data();
159 Tok.Length = Value.size();
162 unsigned getReg() const {
163 assert(Kind == Register && "Invalid access!");
167 const MCExpr *getImm() const {
168 assert(Kind == Immediate && "Invalid access!");
172 const MCExpr *getMemDisp() const {
173 assert(Kind == Memory && "Invalid access!");
176 unsigned getMemSegReg() const {
177 assert(Kind == Memory && "Invalid access!");
180 unsigned getMemBaseReg() const {
181 assert(Kind == Memory && "Invalid access!");
184 unsigned getMemIndexReg() const {
185 assert(Kind == Memory && "Invalid access!");
188 unsigned getMemScale() const {
189 assert(Kind == Memory && "Invalid access!");
193 bool isToken() const {return Kind == Token; }
195 bool isImm() const { return Kind == Immediate; }
197 bool isImmSExti16i8() const {
201 // If this isn't a constant expr, just assume it fits and let relaxation
203 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
207 // Otherwise, check the value is in a range that makes sense for this
209 uint64_t Value = CE->getValue();
210 return (( Value <= 0x000000000000007FULL)||
211 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
212 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
214 bool isImmSExti32i8() const {
218 // If this isn't a constant expr, just assume it fits and let relaxation
220 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
224 // Otherwise, check the value is in a range that makes sense for this
226 uint64_t Value = CE->getValue();
227 return (( Value <= 0x000000000000007FULL)||
228 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
229 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
231 bool isImmSExti64i8() const {
235 // If this isn't a constant expr, just assume it fits and let relaxation
237 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
241 // Otherwise, check the value is in a range that makes sense for this
243 uint64_t Value = CE->getValue();
244 return (( Value <= 0x000000000000007FULL)||
245 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
247 bool isImmSExti64i32() const {
251 // If this isn't a constant expr, just assume it fits and let relaxation
253 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
257 // Otherwise, check the value is in a range that makes sense for this
259 uint64_t Value = CE->getValue();
260 return (( Value <= 0x000000007FFFFFFFULL)||
261 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
264 bool isMem() const { return Kind == Memory; }
266 bool isAbsMem() const {
267 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
268 !getMemIndexReg() && getMemScale() == 1;
271 bool isReg() const { return Kind == Register; }
273 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
274 // Add as immediates when possible.
275 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
276 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
278 Inst.addOperand(MCOperand::CreateExpr(Expr));
281 void addRegOperands(MCInst &Inst, unsigned N) const {
282 assert(N == 1 && "Invalid number of operands!");
283 Inst.addOperand(MCOperand::CreateReg(getReg()));
286 void addImmOperands(MCInst &Inst, unsigned N) const {
287 assert(N == 1 && "Invalid number of operands!");
288 addExpr(Inst, getImm());
291 void addMemOperands(MCInst &Inst, unsigned N) const {
292 assert((N == 5) && "Invalid number of operands!");
293 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
294 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
295 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
296 addExpr(Inst, getMemDisp());
297 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
300 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
301 assert((N == 1) && "Invalid number of operands!");
302 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
305 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
306 X86Operand *Res = new X86Operand(Token, Loc, Loc);
307 Res->Tok.Data = Str.data();
308 Res->Tok.Length = Str.size();
312 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
313 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
314 Res->Reg.RegNo = RegNo;
318 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
319 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
324 /// Create an absolute memory operand.
325 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
327 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
329 Res->Mem.Disp = Disp;
330 Res->Mem.BaseReg = 0;
331 Res->Mem.IndexReg = 0;
336 /// Create a generalized memory operand.
337 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
338 unsigned BaseReg, unsigned IndexReg,
339 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
340 // We should never just have a displacement, that should be parsed as an
341 // absolute memory operand.
342 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
344 // The scale should always be one of {1,2,4,8}.
345 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
347 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
348 Res->Mem.SegReg = SegReg;
349 Res->Mem.Disp = Disp;
350 Res->Mem.BaseReg = BaseReg;
351 Res->Mem.IndexReg = IndexReg;
352 Res->Mem.Scale = Scale;
357 } // end anonymous namespace.
360 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
361 SMLoc &StartLoc, SMLoc &EndLoc) {
363 const AsmToken &TokPercent = Parser.getTok();
364 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
365 StartLoc = TokPercent.getLoc();
366 Parser.Lex(); // Eat percent token.
368 const AsmToken &Tok = Parser.getTok();
369 if (Tok.isNot(AsmToken::Identifier))
370 return Error(Tok.getLoc(), "invalid register name");
372 // FIXME: Validate register for the current architecture; we have to do
373 // validation later, so maybe there is no need for this here.
374 RegNo = MatchRegisterName(Tok.getString());
376 // If the match failed, try the register name as lowercase.
378 RegNo = MatchRegisterName(LowercaseString(Tok.getString()));
380 // FIXME: This should be done using Requires<In32BitMode> and
381 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions
382 // can be also checked.
383 if (RegNo == X86::RIZ && !Is64Bit)
384 return Error(Tok.getLoc(), "riz register in 64-bit mode only");
386 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
387 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
389 EndLoc = Tok.getLoc();
390 Parser.Lex(); // Eat 'st'
392 // Check to see if we have '(4)' after %st.
393 if (getLexer().isNot(AsmToken::LParen))
398 const AsmToken &IntTok = Parser.getTok();
399 if (IntTok.isNot(AsmToken::Integer))
400 return Error(IntTok.getLoc(), "expected stack index");
401 switch (IntTok.getIntVal()) {
402 case 0: RegNo = X86::ST0; break;
403 case 1: RegNo = X86::ST1; break;
404 case 2: RegNo = X86::ST2; break;
405 case 3: RegNo = X86::ST3; break;
406 case 4: RegNo = X86::ST4; break;
407 case 5: RegNo = X86::ST5; break;
408 case 6: RegNo = X86::ST6; break;
409 case 7: RegNo = X86::ST7; break;
410 default: return Error(IntTok.getLoc(), "invalid stack index");
413 if (getParser().Lex().isNot(AsmToken::RParen))
414 return Error(Parser.getTok().getLoc(), "expected ')'");
416 EndLoc = Tok.getLoc();
417 Parser.Lex(); // Eat ')'
421 // If this is "db[0-7]", match it as an alias
423 if (RegNo == 0 && Tok.getString().size() == 3 &&
424 Tok.getString().startswith("db")) {
425 switch (Tok.getString()[2]) {
426 case '0': RegNo = X86::DR0; break;
427 case '1': RegNo = X86::DR1; break;
428 case '2': RegNo = X86::DR2; break;
429 case '3': RegNo = X86::DR3; break;
430 case '4': RegNo = X86::DR4; break;
431 case '5': RegNo = X86::DR5; break;
432 case '6': RegNo = X86::DR6; break;
433 case '7': RegNo = X86::DR7; break;
437 EndLoc = Tok.getLoc();
438 Parser.Lex(); // Eat it.
444 return Error(Tok.getLoc(), "invalid register name");
446 EndLoc = Tok.getLoc();
447 Parser.Lex(); // Eat identifier token.
451 X86Operand *X86ATTAsmParser::ParseOperand() {
452 switch (getLexer().getKind()) {
454 // Parse a memory operand with no segment register.
455 return ParseMemOperand(0, Parser.getTok().getLoc());
456 case AsmToken::Percent: {
457 // Read the register.
460 if (ParseRegister(RegNo, Start, End)) return 0;
461 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
462 Error(Start, "eiz and riz can only be used as index registers");
466 // If this is a segment register followed by a ':', then this is the start
467 // of a memory reference, otherwise this is a normal register reference.
468 if (getLexer().isNot(AsmToken::Colon))
469 return X86Operand::CreateReg(RegNo, Start, End);
472 getParser().Lex(); // Eat the colon.
473 return ParseMemOperand(RegNo, Start);
475 case AsmToken::Dollar: {
477 SMLoc Start = Parser.getTok().getLoc(), End;
480 if (getParser().ParseExpression(Val, End))
482 return X86Operand::CreateImm(Val, Start, End);
487 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
488 /// has already been parsed if present.
489 X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
491 // We have to disambiguate a parenthesized expression "(4+5)" from the start
492 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
493 // only way to do this without lookahead is to eat the '(' and see what is
495 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
496 if (getLexer().isNot(AsmToken::LParen)) {
498 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
500 // After parsing the base expression we could either have a parenthesized
501 // memory address or not. If not, return now. If so, eat the (.
502 if (getLexer().isNot(AsmToken::LParen)) {
503 // Unless we have a segment register, treat this as an immediate.
505 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
506 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
512 // Okay, we have a '('. We don't know if this is an expression or not, but
513 // so we have to eat the ( to see beyond it.
514 SMLoc LParenLoc = Parser.getTok().getLoc();
515 Parser.Lex(); // Eat the '('.
517 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
518 // Nothing to do here, fall into the code below with the '(' part of the
519 // memory operand consumed.
523 // It must be an parenthesized expression, parse it now.
524 if (getParser().ParseParenExpression(Disp, ExprEnd))
527 // After parsing the base expression we could either have a parenthesized
528 // memory address or not. If not, return now. If so, eat the (.
529 if (getLexer().isNot(AsmToken::LParen)) {
530 // Unless we have a segment register, treat this as an immediate.
532 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
533 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
541 // If we reached here, then we just ate the ( of the memory operand. Process
542 // the rest of the memory operand.
543 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
545 if (getLexer().is(AsmToken::Percent)) {
547 if (ParseRegister(BaseReg, L, L)) return 0;
548 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
549 Error(L, "eiz and riz can only be used as index registers");
554 if (getLexer().is(AsmToken::Comma)) {
555 Parser.Lex(); // Eat the comma.
557 // Following the comma we should have either an index register, or a scale
558 // value. We don't support the later form, but we want to parse it
561 // Not that even though it would be completely consistent to support syntax
562 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
563 if (getLexer().is(AsmToken::Percent)) {
565 if (ParseRegister(IndexReg, L, L)) return 0;
567 if (getLexer().isNot(AsmToken::RParen)) {
568 // Parse the scale amount:
569 // ::= ',' [scale-expression]
570 if (getLexer().isNot(AsmToken::Comma)) {
571 Error(Parser.getTok().getLoc(),
572 "expected comma in scale expression");
575 Parser.Lex(); // Eat the comma.
577 if (getLexer().isNot(AsmToken::RParen)) {
578 SMLoc Loc = Parser.getTok().getLoc();
581 if (getParser().ParseAbsoluteExpression(ScaleVal))
584 // Validate the scale amount.
585 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
586 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
589 Scale = (unsigned)ScaleVal;
592 } else if (getLexer().isNot(AsmToken::RParen)) {
593 // A scale amount without an index is ignored.
595 SMLoc Loc = Parser.getTok().getLoc();
598 if (getParser().ParseAbsoluteExpression(Value))
602 Warning(Loc, "scale factor without index register is ignored");
607 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
608 if (getLexer().isNot(AsmToken::RParen)) {
609 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
612 SMLoc MemEnd = Parser.getTok().getLoc();
613 Parser.Lex(); // Eat the ')'.
615 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
619 bool X86ATTAsmParser::
620 ParseInstruction(StringRef Name, SMLoc NameLoc,
621 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
622 StringRef PatchedName = Name;
624 // FIXME: Hack to recognize setneb as setne.
625 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
626 PatchedName != "setb" && PatchedName != "setnb")
627 PatchedName = PatchedName.substr(0, Name.size()-1);
629 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
630 const MCExpr *ExtraImmOp = 0;
631 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
632 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
633 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
634 bool IsVCMP = PatchedName.startswith("vcmp");
635 unsigned SSECCIdx = IsVCMP ? 4 : 3;
636 unsigned SSEComparisonCode = StringSwitch<unsigned>(
637 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
650 .Case("neq_oq", 0x0C)
657 .Case("unord_s", 0x13)
658 .Case("neq_us", 0x14)
659 .Case("nlt_uq", 0x15)
660 .Case("nle_uq", 0x16)
663 .Case("nge_uq", 0x19)
664 .Case("ngt_uq", 0x1A)
665 .Case("false_os", 0x1B)
666 .Case("neq_os", 0x1C)
669 .Case("true_us", 0x1F)
671 if (SSEComparisonCode != ~0U) {
672 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
673 getParser().getContext());
674 if (PatchedName.endswith("ss")) {
675 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
676 } else if (PatchedName.endswith("sd")) {
677 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
678 } else if (PatchedName.endswith("ps")) {
679 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
681 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
682 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
687 // FIXME: Hack to recognize vpclmul<src1_quadword, src2_quadword>dq
688 if (PatchedName.startswith("vpclmul")) {
689 unsigned CLMULQuadWordSelect = StringSwitch<unsigned>(
690 PatchedName.slice(7, PatchedName.size() - 2))
691 .Case("lqlq", 0x00) // src1[63:0], src2[63:0]
692 .Case("hqlq", 0x01) // src1[127:64], src2[63:0]
693 .Case("lqhq", 0x10) // src1[63:0], src2[127:64]
694 .Case("hqhq", 0x11) // src1[127:64], src2[127:64]
696 if (CLMULQuadWordSelect != ~0U) {
697 ExtraImmOp = MCConstantExpr::Create(CLMULQuadWordSelect,
698 getParser().getContext());
699 assert(PatchedName.endswith("dq") && "Unexpected mnemonic!");
700 PatchedName = "vpclmulqdq";
704 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
707 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
710 // Determine whether this is an instruction prefix.
712 Name == "lock" || Name == "rep" ||
713 Name == "repe" || Name == "repz" ||
714 Name == "repne" || Name == "repnz" ||
715 Name == "rex64" || Name == "data16";
718 // This does the actual operand parsing. Don't parse any more if we have a
719 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
720 // just want to parse the "lock" as the first instruction and the "incl" as
722 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
724 // Parse '*' modifier.
725 if (getLexer().is(AsmToken::Star)) {
726 SMLoc Loc = Parser.getTok().getLoc();
727 Operands.push_back(X86Operand::CreateToken("*", Loc));
728 Parser.Lex(); // Eat the star.
731 // Read the first operand.
732 if (X86Operand *Op = ParseOperand())
733 Operands.push_back(Op);
735 Parser.EatToEndOfStatement();
739 while (getLexer().is(AsmToken::Comma)) {
740 Parser.Lex(); // Eat the comma.
742 // Parse and remember the operand.
743 if (X86Operand *Op = ParseOperand())
744 Operands.push_back(Op);
746 Parser.EatToEndOfStatement();
751 if (getLexer().isNot(AsmToken::EndOfStatement)) {
752 SMLoc Loc = getLexer().getLoc();
753 Parser.EatToEndOfStatement();
754 return Error(Loc, "unexpected token in argument list");
758 if (getLexer().is(AsmToken::EndOfStatement))
759 Parser.Lex(); // Consume the EndOfStatement
760 else if (isPrefix && getLexer().is(AsmToken::Slash))
761 Parser.Lex(); // Consume the prefix separator Slash
763 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
764 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
765 // documented form in various unofficial manuals, so a lot of code uses it.
766 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
767 Operands.size() == 3) {
768 X86Operand &Op = *(X86Operand*)Operands.back();
769 if (Op.isMem() && Op.Mem.SegReg == 0 &&
770 isa<MCConstantExpr>(Op.Mem.Disp) &&
771 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
772 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
773 SMLoc Loc = Op.getEndLoc();
774 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
779 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
781 if ((Name.startswith("shr") || Name.startswith("sar") ||
782 Name.startswith("shl") || Name.startswith("sal") ||
783 Name.startswith("rcl") || Name.startswith("rcr") ||
784 Name.startswith("rol") || Name.startswith("ror")) &&
785 Operands.size() == 3) {
786 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
787 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
788 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
790 Operands.erase(Operands.begin() + 1);
797 bool X86ATTAsmParser::
798 MatchAndEmitInstruction(SMLoc IDLoc,
799 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
801 assert(!Operands.empty() && "Unexpect empty operand list!");
802 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
803 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
805 // First, handle aliases that expand to multiple instructions.
806 // FIXME: This should be replaced with a real .td file alias mechanism.
807 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
809 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
810 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
811 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
812 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
814 Inst.setOpcode(X86::WAIT);
815 Out.EmitInstruction(Inst);
818 StringSwitch<const char*>(Op->getToken())
819 .Case("finit", "fninit")
820 .Case("fsave", "fnsave")
821 .Case("fstcw", "fnstcw")
822 .Case("fstcww", "fnstcw")
823 .Case("fstenv", "fnstenv")
824 .Case("fstsw", "fnstsw")
825 .Case("fstsww", "fnstsw")
826 .Case("fclex", "fnclex")
828 assert(Repl && "Unknown wait-prefixed instruction");
830 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
833 bool WasOriginallyInvalidOperand = false;
834 unsigned OrigErrorInfo;
837 // First, try a direct match.
838 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
840 Out.EmitInstruction(Inst);
842 case Match_MissingFeature:
843 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
845 case Match_ConversionFail:
846 return Error(IDLoc, "unable to convert operands to instruction");
847 case Match_InvalidOperand:
848 WasOriginallyInvalidOperand = true;
850 case Match_MnemonicFail:
854 // FIXME: Ideally, we would only attempt suffix matches for things which are
855 // valid prefixes, and we could just infer the right unambiguous
856 // type. However, that requires substantially more matcher support than the
859 // Change the operand to point to a temporary token.
860 StringRef Base = Op->getToken();
864 Op->setTokenValue(Tmp.str());
866 // If this instruction starts with an 'f', then it is a floating point stack
867 // instruction. These come in up to three forms for 32-bit, 64-bit, and
868 // 80-bit floating point, which use the suffixes s,l,t respectively.
870 // Otherwise, we assume that this may be an integer instruction, which comes
871 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
872 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
874 // Check for the various suffix matches.
875 Tmp[Base.size()] = Suffixes[0];
876 unsigned ErrorInfoIgnore;
877 MatchResultTy Match1, Match2, Match3, Match4;
879 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
880 Tmp[Base.size()] = Suffixes[1];
881 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
882 Tmp[Base.size()] = Suffixes[2];
883 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
884 Tmp[Base.size()] = Suffixes[3];
885 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
887 // Restore the old token.
888 Op->setTokenValue(Base);
890 // If exactly one matched, then we treat that as a successful match (and the
891 // instruction will already have been filled in correctly, since the failing
892 // matches won't have modified it).
893 unsigned NumSuccessfulMatches =
894 (Match1 == Match_Success) + (Match2 == Match_Success) +
895 (Match3 == Match_Success) + (Match4 == Match_Success);
896 if (NumSuccessfulMatches == 1) {
897 Out.EmitInstruction(Inst);
901 // Otherwise, the match failed, try to produce a decent error message.
903 // If we had multiple suffix matches, then identify this as an ambiguous
905 if (NumSuccessfulMatches > 1) {
907 unsigned NumMatches = 0;
908 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
909 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
910 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
911 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
913 SmallString<126> Msg;
914 raw_svector_ostream OS(Msg);
915 OS << "ambiguous instructions require an explicit suffix (could be ";
916 for (unsigned i = 0; i != NumMatches; ++i) {
919 if (i + 1 == NumMatches)
921 OS << "'" << Base << MatchChars[i] << "'";
924 Error(IDLoc, OS.str());
928 // Okay, we know that none of the variants matched successfully.
930 // If all of the instructions reported an invalid mnemonic, then the original
931 // mnemonic was invalid.
932 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
933 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
934 if (!WasOriginallyInvalidOperand) {
935 Error(IDLoc, "invalid instruction mnemonic '" + Base + "'");
939 // Recover location info for the operand if we know which was the problem.
940 SMLoc ErrorLoc = IDLoc;
941 if (OrigErrorInfo != ~0U) {
942 if (OrigErrorInfo >= Operands.size())
943 return Error(IDLoc, "too few operands for instruction");
945 ErrorLoc = ((X86Operand*)Operands[OrigErrorInfo])->getStartLoc();
946 if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
949 return Error(ErrorLoc, "invalid operand for instruction");
952 // If one instruction matched with a missing feature, report this as a
954 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
955 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
956 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
960 // If one instruction matched with an invalid operand, report this as an
962 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
963 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
964 Error(IDLoc, "invalid operand for instruction");
968 // If all of these were an outright failure, report it in a useless way.
969 // FIXME: We should give nicer diagnostics about the exact failure.
970 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
975 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
976 StringRef IDVal = DirectiveID.getIdentifier();
977 if (IDVal == ".word")
978 return ParseDirectiveWord(2, DirectiveID.getLoc());
982 /// ParseDirectiveWord
983 /// ::= .word [ expression (, expression)* ]
984 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
985 if (getLexer().isNot(AsmToken::EndOfStatement)) {
988 if (getParser().ParseExpression(Value))
991 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
993 if (getLexer().is(AsmToken::EndOfStatement))
996 // FIXME: Improve diagnostic.
997 if (getLexer().isNot(AsmToken::Comma))
998 return Error(L, "unexpected token in directive");
1010 extern "C" void LLVMInitializeX86AsmLexer();
1012 // Force static initialization.
1013 extern "C" void LLVMInitializeX86AsmParser() {
1014 RegisterAsmParser<X86_32ATTAsmParser> X(TheX86_32Target);
1015 RegisterAsmParser<X86_64ATTAsmParser> Y(TheX86_64Target);
1016 LLVMInitializeX86AsmLexer();
1019 #define GET_REGISTER_MATCHER
1020 #define GET_MATCHER_IMPLEMENTATION
1021 #include "X86GenAsmMatcher.inc"