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/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Support/raw_ostream.h"
33 class X86AsmParser : public MCTargetAsmParser {
37 MCAsmParser &getParser() const { return Parser; }
39 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
41 bool Error(SMLoc L, const Twine &Msg,
42 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
43 bool matchingInlineAsm = false) {
44 if (matchingInlineAsm) return true;
45 return Parser.Error(L, Msg, Ranges);
48 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
53 X86Operand *ParseOperand();
54 X86Operand *ParseATTOperand();
55 X86Operand *ParseIntelOperand();
56 X86Operand *ParseIntelMemOperand();
57 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
58 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
60 bool ParseDirectiveWord(unsigned Size, SMLoc L);
61 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
63 bool processInstruction(MCInst &Inst,
64 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
66 bool MatchAndEmitInstruction(SMLoc IDLoc,
67 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
70 bool MatchInstruction(SMLoc IDLoc, unsigned &Kind,
71 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
72 SmallVectorImpl<MCInst> &MCInsts,
73 unsigned &OrigErrorInfo,
74 bool matchingInlineAsm = false);
76 unsigned getMCInstOperandNum(unsigned Kind, MCInst &Inst,
77 const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
78 unsigned OperandNum, unsigned &NumMCOperands) {
79 return getMCInstOperandNumImpl(Kind, Inst, Operands, OperandNum,
83 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
84 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
85 bool isSrcOp(X86Operand &Op);
87 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
88 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
89 bool isDstOp(X86Operand &Op);
91 bool is64BitMode() const {
92 // FIXME: Can tablegen auto-generate this?
93 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
96 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
97 setAvailableFeatures(FB);
100 /// @name Auto-generated Matcher Functions
103 #define GET_ASSEMBLER_HEADER
104 #include "X86GenAsmMatcher.inc"
109 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
110 : MCTargetAsmParser(), STI(sti), Parser(parser) {
112 // Initialize the set of available features.
113 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
115 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
117 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
118 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
120 virtual bool ParseDirective(AsmToken DirectiveID);
122 bool isParsingIntelSyntax() {
123 return getParser().getAssemblerDialect();
126 } // end anonymous namespace
128 /// @name Auto-generated Match Functions
131 static unsigned MatchRegisterName(StringRef Name);
135 static bool isImmSExti16i8Value(uint64_t Value) {
136 return (( Value <= 0x000000000000007FULL)||
137 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
138 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
141 static bool isImmSExti32i8Value(uint64_t Value) {
142 return (( Value <= 0x000000000000007FULL)||
143 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
144 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
147 static bool isImmZExtu32u8Value(uint64_t Value) {
148 return (Value <= 0x00000000000000FFULL);
151 static bool isImmSExti64i8Value(uint64_t Value) {
152 return (( Value <= 0x000000000000007FULL)||
153 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
156 static bool isImmSExti64i32Value(uint64_t Value) {
157 return (( Value <= 0x000000007FFFFFFFULL)||
158 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
162 /// X86Operand - Instances of this class represent a parsed X86 machine
164 struct X86Operand : public MCParsedAsmOperand {
172 SMLoc StartLoc, EndLoc;
198 X86Operand(KindTy K, SMLoc Start, SMLoc End)
199 : Kind(K), StartLoc(Start), EndLoc(End) {}
201 /// getStartLoc - Get the location of the first token of this operand.
202 SMLoc getStartLoc() const { return StartLoc; }
203 /// getEndLoc - Get the location of the last token of this operand.
204 SMLoc getEndLoc() const { return EndLoc; }
206 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
208 virtual void print(raw_ostream &OS) const {}
210 StringRef getToken() const {
211 assert(Kind == Token && "Invalid access!");
212 return StringRef(Tok.Data, Tok.Length);
214 void setTokenValue(StringRef Value) {
215 assert(Kind == Token && "Invalid access!");
216 Tok.Data = Value.data();
217 Tok.Length = Value.size();
220 unsigned getReg() const {
221 assert(Kind == Register && "Invalid access!");
225 const MCExpr *getImm() const {
226 assert(Kind == Immediate && "Invalid access!");
230 const MCExpr *getMemDisp() const {
231 assert(Kind == Memory && "Invalid access!");
234 unsigned getMemSegReg() const {
235 assert(Kind == Memory && "Invalid access!");
238 unsigned getMemBaseReg() const {
239 assert(Kind == Memory && "Invalid access!");
242 unsigned getMemIndexReg() const {
243 assert(Kind == Memory && "Invalid access!");
246 unsigned getMemScale() const {
247 assert(Kind == Memory && "Invalid access!");
251 bool isToken() const {return Kind == Token; }
253 bool isImm() const { return Kind == Immediate; }
255 bool isImmSExti16i8() const {
259 // If this isn't a constant expr, just assume it fits and let relaxation
261 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
265 // Otherwise, check the value is in a range that makes sense for this
267 return isImmSExti16i8Value(CE->getValue());
269 bool isImmSExti32i8() 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 return isImmSExti32i8Value(CE->getValue());
283 bool isImmZExtu32u8() const {
287 // If this isn't a constant expr, just assume it fits and let relaxation
289 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
293 // Otherwise, check the value is in a range that makes sense for this
295 return isImmZExtu32u8Value(CE->getValue());
297 bool isImmSExti64i8() const {
301 // If this isn't a constant expr, just assume it fits and let relaxation
303 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
307 // Otherwise, check the value is in a range that makes sense for this
309 return isImmSExti64i8Value(CE->getValue());
311 bool isImmSExti64i32() const {
315 // If this isn't a constant expr, just assume it fits and let relaxation
317 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
321 // Otherwise, check the value is in a range that makes sense for this
323 return isImmSExti64i32Value(CE->getValue());
326 bool isMem() const { return Kind == Memory; }
327 bool isMem8() const {
328 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
330 bool isMem16() const {
331 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
333 bool isMem32() const {
334 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
336 bool isMem64() const {
337 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
339 bool isMem80() const {
340 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
342 bool isMem128() const {
343 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
345 bool isMem256() const {
346 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
349 bool isMemVX32() const {
350 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
351 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
353 bool isMemVY32() const {
354 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
355 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
357 bool isMemVX64() const {
358 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
359 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
361 bool isMemVY64() const {
362 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
363 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
366 bool isAbsMem() const {
367 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
368 !getMemIndexReg() && getMemScale() == 1;
371 bool isReg() const { return Kind == Register; }
373 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
374 // Add as immediates when possible.
375 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
376 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
378 Inst.addOperand(MCOperand::CreateExpr(Expr));
381 void addRegOperands(MCInst &Inst, unsigned N) const {
382 assert(N == 1 && "Invalid number of operands!");
383 Inst.addOperand(MCOperand::CreateReg(getReg()));
386 void addImmOperands(MCInst &Inst, unsigned N) const {
387 assert(N == 1 && "Invalid number of operands!");
388 addExpr(Inst, getImm());
391 void addMem8Operands(MCInst &Inst, unsigned N) const {
392 addMemOperands(Inst, N);
394 void addMem16Operands(MCInst &Inst, unsigned N) const {
395 addMemOperands(Inst, N);
397 void addMem32Operands(MCInst &Inst, unsigned N) const {
398 addMemOperands(Inst, N);
400 void addMem64Operands(MCInst &Inst, unsigned N) const {
401 addMemOperands(Inst, N);
403 void addMem80Operands(MCInst &Inst, unsigned N) const {
404 addMemOperands(Inst, N);
406 void addMem128Operands(MCInst &Inst, unsigned N) const {
407 addMemOperands(Inst, N);
409 void addMem256Operands(MCInst &Inst, unsigned N) const {
410 addMemOperands(Inst, N);
412 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
413 addMemOperands(Inst, N);
415 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
416 addMemOperands(Inst, N);
418 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
419 addMemOperands(Inst, N);
421 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
422 addMemOperands(Inst, N);
425 void addMemOperands(MCInst &Inst, unsigned N) const {
426 assert((N == 5) && "Invalid number of operands!");
427 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
428 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
429 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
430 addExpr(Inst, getMemDisp());
431 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
434 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
435 assert((N == 1) && "Invalid number of operands!");
436 // Add as immediates when possible.
437 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
438 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
440 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
443 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
444 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
445 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
446 Res->Tok.Data = Str.data();
447 Res->Tok.Length = Str.size();
451 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
452 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
453 Res->Reg.RegNo = RegNo;
457 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
458 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
463 /// Create an absolute memory operand.
464 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
465 SMLoc EndLoc, unsigned Size = 0) {
466 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
468 Res->Mem.Disp = Disp;
469 Res->Mem.BaseReg = 0;
470 Res->Mem.IndexReg = 0;
472 Res->Mem.Size = Size;
476 /// Create a generalized memory operand.
477 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
478 unsigned BaseReg, unsigned IndexReg,
479 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
481 // We should never just have a displacement, that should be parsed as an
482 // absolute memory operand.
483 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
485 // The scale should always be one of {1,2,4,8}.
486 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
488 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
489 Res->Mem.SegReg = SegReg;
490 Res->Mem.Disp = Disp;
491 Res->Mem.BaseReg = BaseReg;
492 Res->Mem.IndexReg = IndexReg;
493 Res->Mem.Scale = Scale;
494 Res->Mem.Size = Size;
499 } // end anonymous namespace.
501 bool X86AsmParser::isSrcOp(X86Operand &Op) {
502 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
504 return (Op.isMem() &&
505 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
506 isa<MCConstantExpr>(Op.Mem.Disp) &&
507 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
508 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
511 bool X86AsmParser::isDstOp(X86Operand &Op) {
512 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
515 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
516 isa<MCConstantExpr>(Op.Mem.Disp) &&
517 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
518 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
521 bool X86AsmParser::ParseRegister(unsigned &RegNo,
522 SMLoc &StartLoc, SMLoc &EndLoc) {
524 const AsmToken &PercentTok = Parser.getTok();
525 StartLoc = PercentTok.getLoc();
527 // If we encounter a %, ignore it. This code handles registers with and
528 // without the prefix, unprefixed registers can occur in cfi directives.
529 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
530 Parser.Lex(); // Eat percent token.
532 const AsmToken &Tok = Parser.getTok();
533 if (Tok.isNot(AsmToken::Identifier)) {
534 if (isParsingIntelSyntax()) return true;
535 return Error(StartLoc, "invalid register name",
536 SMRange(StartLoc, Tok.getEndLoc()));
539 RegNo = MatchRegisterName(Tok.getString());
541 // If the match failed, try the register name as lowercase.
543 RegNo = MatchRegisterName(Tok.getString().lower());
545 if (!is64BitMode()) {
546 // FIXME: This should be done using Requires<In32BitMode> and
547 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
549 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
551 if (RegNo == X86::RIZ ||
552 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
553 X86II::isX86_64NonExtLowByteReg(RegNo) ||
554 X86II::isX86_64ExtendedReg(RegNo))
555 return Error(StartLoc, "register %"
556 + Tok.getString() + " is only available in 64-bit mode",
557 SMRange(StartLoc, Tok.getEndLoc()));
560 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
561 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
563 EndLoc = Tok.getLoc();
564 Parser.Lex(); // Eat 'st'
566 // Check to see if we have '(4)' after %st.
567 if (getLexer().isNot(AsmToken::LParen))
572 const AsmToken &IntTok = Parser.getTok();
573 if (IntTok.isNot(AsmToken::Integer))
574 return Error(IntTok.getLoc(), "expected stack index");
575 switch (IntTok.getIntVal()) {
576 case 0: RegNo = X86::ST0; break;
577 case 1: RegNo = X86::ST1; break;
578 case 2: RegNo = X86::ST2; break;
579 case 3: RegNo = X86::ST3; break;
580 case 4: RegNo = X86::ST4; break;
581 case 5: RegNo = X86::ST5; break;
582 case 6: RegNo = X86::ST6; break;
583 case 7: RegNo = X86::ST7; break;
584 default: return Error(IntTok.getLoc(), "invalid stack index");
587 if (getParser().Lex().isNot(AsmToken::RParen))
588 return Error(Parser.getTok().getLoc(), "expected ')'");
590 EndLoc = Tok.getLoc();
591 Parser.Lex(); // Eat ')'
595 // If this is "db[0-7]", match it as an alias
597 if (RegNo == 0 && Tok.getString().size() == 3 &&
598 Tok.getString().startswith("db")) {
599 switch (Tok.getString()[2]) {
600 case '0': RegNo = X86::DR0; break;
601 case '1': RegNo = X86::DR1; break;
602 case '2': RegNo = X86::DR2; break;
603 case '3': RegNo = X86::DR3; break;
604 case '4': RegNo = X86::DR4; break;
605 case '5': RegNo = X86::DR5; break;
606 case '6': RegNo = X86::DR6; break;
607 case '7': RegNo = X86::DR7; break;
611 EndLoc = Tok.getLoc();
612 Parser.Lex(); // Eat it.
618 if (isParsingIntelSyntax()) return true;
619 return Error(StartLoc, "invalid register name",
620 SMRange(StartLoc, Tok.getEndLoc()));
623 EndLoc = Tok.getEndLoc();
624 Parser.Lex(); // Eat identifier token.
628 X86Operand *X86AsmParser::ParseOperand() {
629 if (isParsingIntelSyntax())
630 return ParseIntelOperand();
631 return ParseATTOperand();
634 /// getIntelMemOperandSize - Return intel memory operand size.
635 static unsigned getIntelMemOperandSize(StringRef OpStr) {
636 unsigned Size = StringSwitch<unsigned>(OpStr)
637 .Cases("BYTE", "byte", 8)
638 .Cases("WORD", "word", 16)
639 .Cases("DWORD", "dword", 32)
640 .Cases("QWORD", "qword", 64)
641 .Cases("XWORD", "xword", 80)
642 .Cases("XMMWORD", "xmmword", 128)
643 .Cases("YMMWORD", "ymmword", 256)
648 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
650 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
651 SMLoc Start = Parser.getTok().getLoc(), End;
653 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
654 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
657 if (getLexer().isNot(AsmToken::LBrac))
658 return ErrorOperand(Start, "Expected '[' token!");
661 if (getLexer().is(AsmToken::Identifier)) {
663 if (ParseRegister(BaseReg, Start, End)) {
664 // Handle '[' 'symbol' ']'
665 if (getParser().ParseExpression(Disp, End)) return 0;
666 if (getLexer().isNot(AsmToken::RBrac))
667 return ErrorOperand(Start, "Expected ']' token!");
669 return X86Operand::CreateMem(Disp, Start, End, Size);
671 } else if (getLexer().is(AsmToken::Integer)) {
672 int64_t Val = Parser.getTok().getIntVal();
674 SMLoc Loc = Parser.getTok().getLoc();
675 if (getLexer().is(AsmToken::RBrac)) {
676 // Handle '[' number ']'
678 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
680 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
682 return X86Operand::CreateMem(Disp, Start, End, Size);
683 } else if (getLexer().is(AsmToken::Star)) {
684 // Handle '[' Scale*IndexReg ']'
686 SMLoc IdxRegLoc = Parser.getTok().getLoc();
687 if (ParseRegister(IndexReg, IdxRegLoc, End))
688 return ErrorOperand(IdxRegLoc, "Expected register");
691 return ErrorOperand(Loc, "Unexpected token");
694 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
695 bool isPlus = getLexer().is(AsmToken::Plus);
697 SMLoc PlusLoc = Parser.getTok().getLoc();
698 if (getLexer().is(AsmToken::Integer)) {
699 int64_t Val = Parser.getTok().getIntVal();
701 if (getLexer().is(AsmToken::Star)) {
703 SMLoc IdxRegLoc = Parser.getTok().getLoc();
704 if (ParseRegister(IndexReg, IdxRegLoc, End))
705 return ErrorOperand(IdxRegLoc, "Expected register");
707 } else if (getLexer().is(AsmToken::RBrac)) {
708 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
709 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
711 return ErrorOperand(PlusLoc, "unexpected token after +");
712 } else if (getLexer().is(AsmToken::Identifier)) {
713 // This could be an index register or a displacement expression.
714 End = Parser.getTok().getLoc();
716 ParseRegister(IndexReg, Start, End);
717 else if (getParser().ParseExpression(Disp, End)) return 0;
721 if (getLexer().isNot(AsmToken::RBrac))
722 if (getParser().ParseExpression(Disp, End)) return 0;
724 End = Parser.getTok().getLoc();
725 if (getLexer().isNot(AsmToken::RBrac))
726 return ErrorOperand(End, "expected ']' token!");
728 End = Parser.getTok().getLoc();
731 if (!BaseReg && !IndexReg)
732 return X86Operand::CreateMem(Disp, Start, End, Size);
734 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
738 /// ParseIntelMemOperand - Parse intel style memory operand.
739 X86Operand *X86AsmParser::ParseIntelMemOperand() {
740 const AsmToken &Tok = Parser.getTok();
741 SMLoc Start = Parser.getTok().getLoc(), End;
744 unsigned Size = getIntelMemOperandSize(Tok.getString());
747 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
748 "Unexpected token!");
752 if (getLexer().is(AsmToken::LBrac))
753 return ParseIntelBracExpression(SegReg, Size);
755 if (!ParseRegister(SegReg, Start, End)) {
756 // Handel SegReg : [ ... ]
757 if (getLexer().isNot(AsmToken::Colon))
758 return ErrorOperand(Start, "Expected ':' token!");
759 Parser.Lex(); // Eat :
760 if (getLexer().isNot(AsmToken::LBrac))
761 return ErrorOperand(Start, "Expected '[' token!");
762 return ParseIntelBracExpression(SegReg, Size);
765 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
766 if (getParser().ParseExpression(Disp, End)) return 0;
767 return X86Operand::CreateMem(Disp, Start, End, Size);
770 X86Operand *X86AsmParser::ParseIntelOperand() {
771 SMLoc Start = Parser.getTok().getLoc(), End;
774 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
775 getLexer().is(AsmToken::Minus)) {
777 if (!getParser().ParseExpression(Val, End)) {
778 End = Parser.getTok().getLoc();
779 return X86Operand::CreateImm(Val, Start, End);
785 if (!ParseRegister(RegNo, Start, End)) {
786 End = Parser.getTok().getLoc();
787 return X86Operand::CreateReg(RegNo, Start, End);
791 return ParseIntelMemOperand();
794 X86Operand *X86AsmParser::ParseATTOperand() {
795 switch (getLexer().getKind()) {
797 // Parse a memory operand with no segment register.
798 return ParseMemOperand(0, Parser.getTok().getLoc());
799 case AsmToken::Percent: {
800 // Read the register.
803 if (ParseRegister(RegNo, Start, End)) return 0;
804 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
805 Error(Start, "%eiz and %riz can only be used as index registers",
806 SMRange(Start, End));
810 // If this is a segment register followed by a ':', then this is the start
811 // of a memory reference, otherwise this is a normal register reference.
812 if (getLexer().isNot(AsmToken::Colon))
813 return X86Operand::CreateReg(RegNo, Start, End);
816 getParser().Lex(); // Eat the colon.
817 return ParseMemOperand(RegNo, Start);
819 case AsmToken::Dollar: {
821 SMLoc Start = Parser.getTok().getLoc(), End;
824 if (getParser().ParseExpression(Val, End))
826 return X86Operand::CreateImm(Val, Start, End);
831 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
832 /// has already been parsed if present.
833 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
835 // We have to disambiguate a parenthesized expression "(4+5)" from the start
836 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
837 // only way to do this without lookahead is to eat the '(' and see what is
839 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
840 if (getLexer().isNot(AsmToken::LParen)) {
842 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
844 // After parsing the base expression we could either have a parenthesized
845 // memory address or not. If not, return now. If so, eat the (.
846 if (getLexer().isNot(AsmToken::LParen)) {
847 // Unless we have a segment register, treat this as an immediate.
849 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
850 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
856 // Okay, we have a '('. We don't know if this is an expression or not, but
857 // so we have to eat the ( to see beyond it.
858 SMLoc LParenLoc = Parser.getTok().getLoc();
859 Parser.Lex(); // Eat the '('.
861 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
862 // Nothing to do here, fall into the code below with the '(' part of the
863 // memory operand consumed.
867 // It must be an parenthesized expression, parse it now.
868 if (getParser().ParseParenExpression(Disp, ExprEnd))
871 // After parsing the base expression we could either have a parenthesized
872 // memory address or not. If not, return now. If so, eat the (.
873 if (getLexer().isNot(AsmToken::LParen)) {
874 // Unless we have a segment register, treat this as an immediate.
876 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
877 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
885 // If we reached here, then we just ate the ( of the memory operand. Process
886 // the rest of the memory operand.
887 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
890 if (getLexer().is(AsmToken::Percent)) {
891 SMLoc StartLoc, EndLoc;
892 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
893 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
894 Error(StartLoc, "eiz and riz can only be used as index registers",
895 SMRange(StartLoc, EndLoc));
900 if (getLexer().is(AsmToken::Comma)) {
901 Parser.Lex(); // Eat the comma.
902 IndexLoc = Parser.getTok().getLoc();
904 // Following the comma we should have either an index register, or a scale
905 // value. We don't support the later form, but we want to parse it
908 // Not that even though it would be completely consistent to support syntax
909 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
910 if (getLexer().is(AsmToken::Percent)) {
912 if (ParseRegister(IndexReg, L, L)) return 0;
914 if (getLexer().isNot(AsmToken::RParen)) {
915 // Parse the scale amount:
916 // ::= ',' [scale-expression]
917 if (getLexer().isNot(AsmToken::Comma)) {
918 Error(Parser.getTok().getLoc(),
919 "expected comma in scale expression");
922 Parser.Lex(); // Eat the comma.
924 if (getLexer().isNot(AsmToken::RParen)) {
925 SMLoc Loc = Parser.getTok().getLoc();
928 if (getParser().ParseAbsoluteExpression(ScaleVal)){
929 Error(Loc, "expected scale expression");
933 // Validate the scale amount.
934 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
935 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
938 Scale = (unsigned)ScaleVal;
941 } else if (getLexer().isNot(AsmToken::RParen)) {
942 // A scale amount without an index is ignored.
944 SMLoc Loc = Parser.getTok().getLoc();
947 if (getParser().ParseAbsoluteExpression(Value))
951 Warning(Loc, "scale factor without index register is ignored");
956 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
957 if (getLexer().isNot(AsmToken::RParen)) {
958 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
961 SMLoc MemEnd = Parser.getTok().getLoc();
962 Parser.Lex(); // Eat the ')'.
964 // If we have both a base register and an index register make sure they are
965 // both 64-bit or 32-bit registers.
966 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
967 if (BaseReg != 0 && IndexReg != 0) {
968 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
969 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
970 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
971 IndexReg != X86::RIZ) {
972 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
975 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
976 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
977 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
978 IndexReg != X86::EIZ){
979 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
984 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
989 ParseInstruction(StringRef Name, SMLoc NameLoc,
990 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
991 StringRef PatchedName = Name;
993 // FIXME: Hack to recognize setneb as setne.
994 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
995 PatchedName != "setb" && PatchedName != "setnb")
996 PatchedName = PatchedName.substr(0, Name.size()-1);
998 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
999 const MCExpr *ExtraImmOp = 0;
1000 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1001 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1002 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1003 bool IsVCMP = PatchedName[0] == 'v';
1004 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1005 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1006 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1010 .Case("unord", 0x03)
1015 /* AVX only from here */
1016 .Case("eq_uq", 0x08)
1019 .Case("false", 0x0B)
1020 .Case("neq_oq", 0x0C)
1024 .Case("eq_os", 0x10)
1025 .Case("lt_oq", 0x11)
1026 .Case("le_oq", 0x12)
1027 .Case("unord_s", 0x13)
1028 .Case("neq_us", 0x14)
1029 .Case("nlt_uq", 0x15)
1030 .Case("nle_uq", 0x16)
1031 .Case("ord_s", 0x17)
1032 .Case("eq_us", 0x18)
1033 .Case("nge_uq", 0x19)
1034 .Case("ngt_uq", 0x1A)
1035 .Case("false_os", 0x1B)
1036 .Case("neq_os", 0x1C)
1037 .Case("ge_oq", 0x1D)
1038 .Case("gt_oq", 0x1E)
1039 .Case("true_us", 0x1F)
1041 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1042 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1043 getParser().getContext());
1044 if (PatchedName.endswith("ss")) {
1045 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1046 } else if (PatchedName.endswith("sd")) {
1047 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1048 } else if (PatchedName.endswith("ps")) {
1049 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1051 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1052 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1057 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1059 if (ExtraImmOp && !isParsingIntelSyntax())
1060 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1062 // Determine whether this is an instruction prefix.
1064 Name == "lock" || Name == "rep" ||
1065 Name == "repe" || Name == "repz" ||
1066 Name == "repne" || Name == "repnz" ||
1067 Name == "rex64" || Name == "data16";
1070 // This does the actual operand parsing. Don't parse any more if we have a
1071 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1072 // just want to parse the "lock" as the first instruction and the "incl" as
1074 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1076 // Parse '*' modifier.
1077 if (getLexer().is(AsmToken::Star)) {
1078 SMLoc Loc = Parser.getTok().getLoc();
1079 Operands.push_back(X86Operand::CreateToken("*", Loc));
1080 Parser.Lex(); // Eat the star.
1083 // Read the first operand.
1084 if (X86Operand *Op = ParseOperand())
1085 Operands.push_back(Op);
1087 Parser.EatToEndOfStatement();
1091 while (getLexer().is(AsmToken::Comma)) {
1092 Parser.Lex(); // Eat the comma.
1094 // Parse and remember the operand.
1095 if (X86Operand *Op = ParseOperand())
1096 Operands.push_back(Op);
1098 Parser.EatToEndOfStatement();
1103 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1104 SMLoc Loc = getLexer().getLoc();
1105 Parser.EatToEndOfStatement();
1106 return Error(Loc, "unexpected token in argument list");
1110 if (getLexer().is(AsmToken::EndOfStatement))
1111 Parser.Lex(); // Consume the EndOfStatement
1112 else if (isPrefix && getLexer().is(AsmToken::Slash))
1113 Parser.Lex(); // Consume the prefix separator Slash
1115 if (ExtraImmOp && isParsingIntelSyntax())
1116 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1118 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1119 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1120 // documented form in various unofficial manuals, so a lot of code uses it.
1121 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1122 Operands.size() == 3) {
1123 X86Operand &Op = *(X86Operand*)Operands.back();
1124 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1125 isa<MCConstantExpr>(Op.Mem.Disp) &&
1126 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1127 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1128 SMLoc Loc = Op.getEndLoc();
1129 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1133 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1134 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1135 Operands.size() == 3) {
1136 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1137 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1138 isa<MCConstantExpr>(Op.Mem.Disp) &&
1139 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1140 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1141 SMLoc Loc = Op.getEndLoc();
1142 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1146 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1147 if (Name.startswith("ins") && Operands.size() == 3 &&
1148 (Name == "insb" || Name == "insw" || Name == "insl")) {
1149 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1150 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1151 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1152 Operands.pop_back();
1153 Operands.pop_back();
1159 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1160 if (Name.startswith("outs") && Operands.size() == 3 &&
1161 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1162 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1163 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1164 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1165 Operands.pop_back();
1166 Operands.pop_back();
1172 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1173 if (Name.startswith("movs") && Operands.size() == 3 &&
1174 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1175 (is64BitMode() && Name == "movsq"))) {
1176 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1177 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1178 if (isSrcOp(Op) && isDstOp(Op2)) {
1179 Operands.pop_back();
1180 Operands.pop_back();
1185 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1186 if (Name.startswith("lods") && Operands.size() == 3 &&
1187 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1188 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1189 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1190 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1191 if (isSrcOp(*Op1) && Op2->isReg()) {
1193 unsigned reg = Op2->getReg();
1194 bool isLods = Name == "lods";
1195 if (reg == X86::AL && (isLods || Name == "lodsb"))
1197 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1199 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1201 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1206 Operands.pop_back();
1207 Operands.pop_back();
1211 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1215 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1216 if (Name.startswith("stos") && Operands.size() == 3 &&
1217 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1218 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1219 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1220 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1221 if (isDstOp(*Op2) && Op1->isReg()) {
1223 unsigned reg = Op1->getReg();
1224 bool isStos = Name == "stos";
1225 if (reg == X86::AL && (isStos || Name == "stosb"))
1227 else if (reg == X86::AX && (isStos || Name == "stosw"))
1229 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1231 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1236 Operands.pop_back();
1237 Operands.pop_back();
1241 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1246 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1248 if ((Name.startswith("shr") || Name.startswith("sar") ||
1249 Name.startswith("shl") || Name.startswith("sal") ||
1250 Name.startswith("rcl") || Name.startswith("rcr") ||
1251 Name.startswith("rol") || Name.startswith("ror")) &&
1252 Operands.size() == 3) {
1253 if (isParsingIntelSyntax()) {
1255 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1256 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1257 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1259 Operands.pop_back();
1262 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1263 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1264 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1266 Operands.erase(Operands.begin() + 1);
1271 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1272 // instalias with an immediate operand yet.
1273 if (Name == "int" && Operands.size() == 2) {
1274 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1275 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1276 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1278 Operands.erase(Operands.begin() + 1);
1279 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1287 processInstruction(MCInst &Inst,
1288 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1289 switch (Inst.getOpcode()) {
1290 default: return false;
1291 case X86::AND16i16: {
1292 if (!Inst.getOperand(0).isImm() ||
1293 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1297 TmpInst.setOpcode(X86::AND16ri8);
1298 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1299 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1300 TmpInst.addOperand(Inst.getOperand(0));
1304 case X86::AND32i32: {
1305 if (!Inst.getOperand(0).isImm() ||
1306 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1310 TmpInst.setOpcode(X86::AND32ri8);
1311 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1312 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1313 TmpInst.addOperand(Inst.getOperand(0));
1317 case X86::AND64i32: {
1318 if (!Inst.getOperand(0).isImm() ||
1319 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1323 TmpInst.setOpcode(X86::AND64ri8);
1324 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1325 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1326 TmpInst.addOperand(Inst.getOperand(0));
1330 case X86::XOR16i16: {
1331 if (!Inst.getOperand(0).isImm() ||
1332 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1336 TmpInst.setOpcode(X86::XOR16ri8);
1337 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1338 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1339 TmpInst.addOperand(Inst.getOperand(0));
1343 case X86::XOR32i32: {
1344 if (!Inst.getOperand(0).isImm() ||
1345 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1349 TmpInst.setOpcode(X86::XOR32ri8);
1350 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1351 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1352 TmpInst.addOperand(Inst.getOperand(0));
1356 case X86::XOR64i32: {
1357 if (!Inst.getOperand(0).isImm() ||
1358 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1362 TmpInst.setOpcode(X86::XOR64ri8);
1363 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1364 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1365 TmpInst.addOperand(Inst.getOperand(0));
1369 case X86::OR16i16: {
1370 if (!Inst.getOperand(0).isImm() ||
1371 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1375 TmpInst.setOpcode(X86::OR16ri8);
1376 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1377 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1378 TmpInst.addOperand(Inst.getOperand(0));
1382 case X86::OR32i32: {
1383 if (!Inst.getOperand(0).isImm() ||
1384 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1388 TmpInst.setOpcode(X86::OR32ri8);
1389 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1390 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1391 TmpInst.addOperand(Inst.getOperand(0));
1395 case X86::OR64i32: {
1396 if (!Inst.getOperand(0).isImm() ||
1397 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1401 TmpInst.setOpcode(X86::OR64ri8);
1402 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1403 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1404 TmpInst.addOperand(Inst.getOperand(0));
1408 case X86::CMP16i16: {
1409 if (!Inst.getOperand(0).isImm() ||
1410 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1414 TmpInst.setOpcode(X86::CMP16ri8);
1415 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1416 TmpInst.addOperand(Inst.getOperand(0));
1420 case X86::CMP32i32: {
1421 if (!Inst.getOperand(0).isImm() ||
1422 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1426 TmpInst.setOpcode(X86::CMP32ri8);
1427 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1428 TmpInst.addOperand(Inst.getOperand(0));
1432 case X86::CMP64i32: {
1433 if (!Inst.getOperand(0).isImm() ||
1434 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1438 TmpInst.setOpcode(X86::CMP64ri8);
1439 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1440 TmpInst.addOperand(Inst.getOperand(0));
1444 case X86::ADD16i16: {
1445 if (!Inst.getOperand(0).isImm() ||
1446 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1450 TmpInst.setOpcode(X86::ADD16ri8);
1451 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1452 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1453 TmpInst.addOperand(Inst.getOperand(0));
1457 case X86::ADD32i32: {
1458 if (!Inst.getOperand(0).isImm() ||
1459 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1463 TmpInst.setOpcode(X86::ADD32ri8);
1464 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1465 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1466 TmpInst.addOperand(Inst.getOperand(0));
1470 case X86::ADD64i32: {
1471 if (!Inst.getOperand(0).isImm() ||
1472 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1476 TmpInst.setOpcode(X86::ADD64ri8);
1477 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1478 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1479 TmpInst.addOperand(Inst.getOperand(0));
1483 case X86::SUB16i16: {
1484 if (!Inst.getOperand(0).isImm() ||
1485 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1489 TmpInst.setOpcode(X86::SUB16ri8);
1490 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1491 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1492 TmpInst.addOperand(Inst.getOperand(0));
1496 case X86::SUB32i32: {
1497 if (!Inst.getOperand(0).isImm() ||
1498 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1502 TmpInst.setOpcode(X86::SUB32ri8);
1503 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1504 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1505 TmpInst.addOperand(Inst.getOperand(0));
1509 case X86::SUB64i32: {
1510 if (!Inst.getOperand(0).isImm() ||
1511 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1515 TmpInst.setOpcode(X86::SUB64ri8);
1516 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1517 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1518 TmpInst.addOperand(Inst.getOperand(0));
1526 MatchAndEmitInstruction(SMLoc IDLoc,
1527 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1531 SmallVector<MCInst, 2> Insts;
1533 bool Error = MatchInstruction(IDLoc, Kind, Operands, Insts,
1536 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
1537 Out.EmitInstruction(Insts[i]);
1542 MatchInstruction(SMLoc IDLoc, unsigned &Kind,
1543 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1544 SmallVectorImpl<MCInst> &MCInsts, unsigned &OrigErrorInfo,
1545 bool matchingInlineAsm) {
1546 assert(!Operands.empty() && "Unexpect empty operand list!");
1547 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1548 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1549 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1551 // First, handle aliases that expand to multiple instructions.
1552 // FIXME: This should be replaced with a real .td file alias mechanism.
1553 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1555 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1556 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1557 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1558 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1560 Inst.setOpcode(X86::WAIT);
1562 MCInsts.push_back(Inst);
1565 StringSwitch<const char*>(Op->getToken())
1566 .Case("finit", "fninit")
1567 .Case("fsave", "fnsave")
1568 .Case("fstcw", "fnstcw")
1569 .Case("fstcww", "fnstcw")
1570 .Case("fstenv", "fnstenv")
1571 .Case("fstsw", "fnstsw")
1572 .Case("fstsww", "fnstsw")
1573 .Case("fclex", "fnclex")
1575 assert(Repl && "Unknown wait-prefixed instruction");
1577 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1580 bool WasOriginallyInvalidOperand = false;
1583 // First, try a direct match.
1584 switch (MatchInstructionImpl(Operands, Kind, Inst, OrigErrorInfo,
1585 isParsingIntelSyntax())) {
1588 // Some instructions need post-processing to, for example, tweak which
1589 // encoding is selected. Loop on it while changes happen so the
1590 // individual transformations can chain off each other.
1591 while (processInstruction(Inst, Operands))
1595 MCInsts.push_back(Inst);
1597 case Match_MissingFeature:
1598 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1599 EmptyRanges, matchingInlineAsm);
1601 case Match_InvalidOperand:
1602 WasOriginallyInvalidOperand = true;
1604 case Match_MnemonicFail:
1608 // FIXME: Ideally, we would only attempt suffix matches for things which are
1609 // valid prefixes, and we could just infer the right unambiguous
1610 // type. However, that requires substantially more matcher support than the
1613 // Change the operand to point to a temporary token.
1614 StringRef Base = Op->getToken();
1615 SmallString<16> Tmp;
1618 Op->setTokenValue(Tmp.str());
1620 // If this instruction starts with an 'f', then it is a floating point stack
1621 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1622 // 80-bit floating point, which use the suffixes s,l,t respectively.
1624 // Otherwise, we assume that this may be an integer instruction, which comes
1625 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1626 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1628 // Check for the various suffix matches.
1629 Tmp[Base.size()] = Suffixes[0];
1630 unsigned ErrorInfoIgnore;
1631 unsigned Match1, Match2, Match3, Match4;
1634 Match1 = MatchInstructionImpl(Operands, tKind, Inst, ErrorInfoIgnore);
1635 if (Match1 == Match_Success) Kind = tKind;
1636 Tmp[Base.size()] = Suffixes[1];
1637 Match2 = MatchInstructionImpl(Operands, tKind, Inst, ErrorInfoIgnore);
1638 if (Match2 == Match_Success) Kind = tKind;
1639 Tmp[Base.size()] = Suffixes[2];
1640 Match3 = MatchInstructionImpl(Operands, tKind, Inst, ErrorInfoIgnore);
1641 if (Match3 == Match_Success) Kind = tKind;
1642 Tmp[Base.size()] = Suffixes[3];
1643 Match4 = MatchInstructionImpl(Operands, tKind, Inst, ErrorInfoIgnore);
1644 if (Match4 == Match_Success) Kind = tKind;
1646 // Restore the old token.
1647 Op->setTokenValue(Base);
1649 // If exactly one matched, then we treat that as a successful match (and the
1650 // instruction will already have been filled in correctly, since the failing
1651 // matches won't have modified it).
1652 unsigned NumSuccessfulMatches =
1653 (Match1 == Match_Success) + (Match2 == Match_Success) +
1654 (Match3 == Match_Success) + (Match4 == Match_Success);
1655 if (NumSuccessfulMatches == 1) {
1657 MCInsts.push_back(Inst);
1661 // Otherwise, the match failed, try to produce a decent error message.
1663 // If we had multiple suffix matches, then identify this as an ambiguous
1665 if (NumSuccessfulMatches > 1) {
1667 unsigned NumMatches = 0;
1668 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1669 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1670 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1671 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1673 SmallString<126> Msg;
1674 raw_svector_ostream OS(Msg);
1675 OS << "ambiguous instructions require an explicit suffix (could be ";
1676 for (unsigned i = 0; i != NumMatches; ++i) {
1679 if (i + 1 == NumMatches)
1681 OS << "'" << Base << MatchChars[i] << "'";
1684 Error(IDLoc, OS.str(), EmptyRanges, matchingInlineAsm);
1688 // Okay, we know that none of the variants matched successfully.
1690 // If all of the instructions reported an invalid mnemonic, then the original
1691 // mnemonic was invalid.
1692 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1693 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1694 if (!WasOriginallyInvalidOperand) {
1695 ArrayRef<SMRange> Ranges = matchingInlineAsm ? EmptyRanges :
1697 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1698 Ranges, matchingInlineAsm);
1701 // Recover location info for the operand if we know which was the problem.
1702 if (OrigErrorInfo != ~0U) {
1703 if (OrigErrorInfo >= Operands.size())
1704 return Error(IDLoc, "too few operands for instruction",
1705 EmptyRanges, matchingInlineAsm);
1707 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1708 if (Operand->getStartLoc().isValid()) {
1709 SMRange OperandRange = Operand->getLocRange();
1710 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1711 OperandRange, matchingInlineAsm);
1715 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1719 // If one instruction matched with a missing feature, report this as a
1721 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1722 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1723 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1724 EmptyRanges, matchingInlineAsm);
1728 // If one instruction matched with an invalid operand, report this as an
1730 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1731 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1732 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1737 // If all of these were an outright failure, report it in a useless way.
1738 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1739 EmptyRanges, matchingInlineAsm);
1744 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1745 StringRef IDVal = DirectiveID.getIdentifier();
1746 if (IDVal == ".word")
1747 return ParseDirectiveWord(2, DirectiveID.getLoc());
1748 else if (IDVal.startswith(".code"))
1749 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1750 else if (IDVal.startswith(".att_syntax")) {
1751 getParser().setAssemblerDialect(0);
1753 } else if (IDVal.startswith(".intel_syntax")) {
1754 getParser().setAssemblerDialect(1);
1755 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1756 if(Parser.getTok().getString() == "noprefix") {
1757 // FIXME : Handle noprefix
1767 /// ParseDirectiveWord
1768 /// ::= .word [ expression (, expression)* ]
1769 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1770 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1772 const MCExpr *Value;
1773 if (getParser().ParseExpression(Value))
1776 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1778 if (getLexer().is(AsmToken::EndOfStatement))
1781 // FIXME: Improve diagnostic.
1782 if (getLexer().isNot(AsmToken::Comma))
1783 return Error(L, "unexpected token in directive");
1792 /// ParseDirectiveCode
1793 /// ::= .code32 | .code64
1794 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1795 if (IDVal == ".code32") {
1797 if (is64BitMode()) {
1799 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1801 } else if (IDVal == ".code64") {
1803 if (!is64BitMode()) {
1805 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1808 return Error(L, "unexpected directive " + IDVal);
1815 extern "C" void LLVMInitializeX86AsmLexer();
1817 // Force static initialization.
1818 extern "C" void LLVMInitializeX86AsmParser() {
1819 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1820 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1821 LLVMInitializeX86AsmLexer();
1824 #define GET_REGISTER_MATCHER
1825 #define GET_MATCHER_IMPLEMENTATION
1826 #include "X86GenAsmMatcher.inc"