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,
71 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
72 SmallVectorImpl<MCInst> &MCInsts,
73 unsigned &OrigErrorInfo,
74 bool matchingInlineAsm = false);
76 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
77 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
78 bool isSrcOp(X86Operand &Op);
80 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
81 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
82 bool isDstOp(X86Operand &Op);
84 bool is64BitMode() const {
85 // FIXME: Can tablegen auto-generate this?
86 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
89 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
90 setAvailableFeatures(FB);
93 /// @name Auto-generated Matcher Functions
96 #define GET_ASSEMBLER_HEADER
97 #include "X86GenAsmMatcher.inc"
102 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
103 : MCTargetAsmParser(), STI(sti), Parser(parser) {
105 // Initialize the set of available features.
106 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
108 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
110 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
111 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
113 virtual bool ParseDirective(AsmToken DirectiveID);
115 bool isParsingIntelSyntax() {
116 return getParser().getAssemblerDialect();
119 } // end anonymous namespace
121 /// @name Auto-generated Match Functions
124 static unsigned MatchRegisterName(StringRef Name);
128 static bool isImmSExti16i8Value(uint64_t Value) {
129 return (( Value <= 0x000000000000007FULL)||
130 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
131 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
134 static bool isImmSExti32i8Value(uint64_t Value) {
135 return (( Value <= 0x000000000000007FULL)||
136 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
137 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
140 static bool isImmZExtu32u8Value(uint64_t Value) {
141 return (Value <= 0x00000000000000FFULL);
144 static bool isImmSExti64i8Value(uint64_t Value) {
145 return (( Value <= 0x000000000000007FULL)||
146 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
149 static bool isImmSExti64i32Value(uint64_t Value) {
150 return (( Value <= 0x000000007FFFFFFFULL)||
151 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
155 /// X86Operand - Instances of this class represent a parsed X86 machine
157 struct X86Operand : public MCParsedAsmOperand {
165 SMLoc StartLoc, EndLoc;
191 X86Operand(KindTy K, SMLoc Start, SMLoc End)
192 : Kind(K), StartLoc(Start), EndLoc(End) {}
194 /// getStartLoc - Get the location of the first token of this operand.
195 SMLoc getStartLoc() const { return StartLoc; }
196 /// getEndLoc - Get the location of the last token of this operand.
197 SMLoc getEndLoc() const { return EndLoc; }
199 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
201 virtual void print(raw_ostream &OS) const {}
203 StringRef getToken() const {
204 assert(Kind == Token && "Invalid access!");
205 return StringRef(Tok.Data, Tok.Length);
207 void setTokenValue(StringRef Value) {
208 assert(Kind == Token && "Invalid access!");
209 Tok.Data = Value.data();
210 Tok.Length = Value.size();
213 unsigned getReg() const {
214 assert(Kind == Register && "Invalid access!");
218 const MCExpr *getImm() const {
219 assert(Kind == Immediate && "Invalid access!");
223 const MCExpr *getMemDisp() const {
224 assert(Kind == Memory && "Invalid access!");
227 unsigned getMemSegReg() const {
228 assert(Kind == Memory && "Invalid access!");
231 unsigned getMemBaseReg() const {
232 assert(Kind == Memory && "Invalid access!");
235 unsigned getMemIndexReg() const {
236 assert(Kind == Memory && "Invalid access!");
239 unsigned getMemScale() const {
240 assert(Kind == Memory && "Invalid access!");
244 bool isToken() const {return Kind == Token; }
246 bool isImm() const { return Kind == Immediate; }
248 bool isImmSExti16i8() const {
252 // If this isn't a constant expr, just assume it fits and let relaxation
254 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
258 // Otherwise, check the value is in a range that makes sense for this
260 return isImmSExti16i8Value(CE->getValue());
262 bool isImmSExti32i8() const {
266 // If this isn't a constant expr, just assume it fits and let relaxation
268 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
272 // Otherwise, check the value is in a range that makes sense for this
274 return isImmSExti32i8Value(CE->getValue());
276 bool isImmZExtu32u8() const {
280 // If this isn't a constant expr, just assume it fits and let relaxation
282 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
286 // Otherwise, check the value is in a range that makes sense for this
288 return isImmZExtu32u8Value(CE->getValue());
290 bool isImmSExti64i8() const {
294 // If this isn't a constant expr, just assume it fits and let relaxation
296 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
300 // Otherwise, check the value is in a range that makes sense for this
302 return isImmSExti64i8Value(CE->getValue());
304 bool isImmSExti64i32() const {
308 // If this isn't a constant expr, just assume it fits and let relaxation
310 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
314 // Otherwise, check the value is in a range that makes sense for this
316 return isImmSExti64i32Value(CE->getValue());
319 bool isMem() const { return Kind == Memory; }
320 bool isMem8() const {
321 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
323 bool isMem16() const {
324 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
326 bool isMem32() const {
327 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
329 bool isMem64() const {
330 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
332 bool isMem80() const {
333 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
335 bool isMem128() const {
336 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
338 bool isMem256() const {
339 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
342 bool isMemVX32() const {
343 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
344 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
346 bool isMemVY32() const {
347 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
348 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
350 bool isMemVX64() const {
351 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
352 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
354 bool isMemVY64() const {
355 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
356 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
359 bool isAbsMem() const {
360 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
361 !getMemIndexReg() && getMemScale() == 1;
364 bool isReg() const { return Kind == Register; }
366 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
367 // Add as immediates when possible.
368 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
369 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
371 Inst.addOperand(MCOperand::CreateExpr(Expr));
374 void addRegOperands(MCInst &Inst, unsigned N) const {
375 assert(N == 1 && "Invalid number of operands!");
376 Inst.addOperand(MCOperand::CreateReg(getReg()));
379 void addImmOperands(MCInst &Inst, unsigned N) const {
380 assert(N == 1 && "Invalid number of operands!");
381 addExpr(Inst, getImm());
384 void addMem8Operands(MCInst &Inst, unsigned N) const {
385 addMemOperands(Inst, N);
387 void addMem16Operands(MCInst &Inst, unsigned N) const {
388 addMemOperands(Inst, N);
390 void addMem32Operands(MCInst &Inst, unsigned N) const {
391 addMemOperands(Inst, N);
393 void addMem64Operands(MCInst &Inst, unsigned N) const {
394 addMemOperands(Inst, N);
396 void addMem80Operands(MCInst &Inst, unsigned N) const {
397 addMemOperands(Inst, N);
399 void addMem128Operands(MCInst &Inst, unsigned N) const {
400 addMemOperands(Inst, N);
402 void addMem256Operands(MCInst &Inst, unsigned N) const {
403 addMemOperands(Inst, N);
405 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
406 addMemOperands(Inst, N);
408 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
409 addMemOperands(Inst, N);
411 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
412 addMemOperands(Inst, N);
414 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
415 addMemOperands(Inst, N);
418 void addMemOperands(MCInst &Inst, unsigned N) const {
419 assert((N == 5) && "Invalid number of operands!");
420 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
421 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
422 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
423 addExpr(Inst, getMemDisp());
424 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
427 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
428 assert((N == 1) && "Invalid number of operands!");
429 // Add as immediates when possible.
430 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
431 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
433 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
436 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
437 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
438 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
439 Res->Tok.Data = Str.data();
440 Res->Tok.Length = Str.size();
444 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
445 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
446 Res->Reg.RegNo = RegNo;
450 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
451 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
456 /// Create an absolute memory operand.
457 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
458 SMLoc EndLoc, unsigned Size = 0) {
459 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
461 Res->Mem.Disp = Disp;
462 Res->Mem.BaseReg = 0;
463 Res->Mem.IndexReg = 0;
465 Res->Mem.Size = Size;
469 /// Create a generalized memory operand.
470 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
471 unsigned BaseReg, unsigned IndexReg,
472 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
474 // We should never just have a displacement, that should be parsed as an
475 // absolute memory operand.
476 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
478 // The scale should always be one of {1,2,4,8}.
479 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
481 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
482 Res->Mem.SegReg = SegReg;
483 Res->Mem.Disp = Disp;
484 Res->Mem.BaseReg = BaseReg;
485 Res->Mem.IndexReg = IndexReg;
486 Res->Mem.Scale = Scale;
487 Res->Mem.Size = Size;
492 } // end anonymous namespace.
494 bool X86AsmParser::isSrcOp(X86Operand &Op) {
495 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
497 return (Op.isMem() &&
498 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
499 isa<MCConstantExpr>(Op.Mem.Disp) &&
500 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
501 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
504 bool X86AsmParser::isDstOp(X86Operand &Op) {
505 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
508 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
509 isa<MCConstantExpr>(Op.Mem.Disp) &&
510 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
511 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
514 bool X86AsmParser::ParseRegister(unsigned &RegNo,
515 SMLoc &StartLoc, SMLoc &EndLoc) {
517 if (!isParsingIntelSyntax()) {
518 const AsmToken &TokPercent = Parser.getTok();
519 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
520 StartLoc = TokPercent.getLoc();
521 Parser.Lex(); // Eat percent token.
524 const AsmToken &Tok = Parser.getTok();
525 if (Tok.isNot(AsmToken::Identifier)) {
526 if (isParsingIntelSyntax()) return true;
527 return Error(StartLoc, "invalid register name",
528 SMRange(StartLoc, Tok.getEndLoc()));
531 RegNo = MatchRegisterName(Tok.getString());
533 // If the match failed, try the register name as lowercase.
535 RegNo = MatchRegisterName(Tok.getString().lower());
537 if (!is64BitMode()) {
538 // FIXME: This should be done using Requires<In32BitMode> and
539 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
541 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
543 if (RegNo == X86::RIZ ||
544 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
545 X86II::isX86_64NonExtLowByteReg(RegNo) ||
546 X86II::isX86_64ExtendedReg(RegNo))
547 return Error(StartLoc, "register %"
548 + Tok.getString() + " is only available in 64-bit mode",
549 SMRange(StartLoc, Tok.getEndLoc()));
552 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
553 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
555 EndLoc = Tok.getLoc();
556 Parser.Lex(); // Eat 'st'
558 // Check to see if we have '(4)' after %st.
559 if (getLexer().isNot(AsmToken::LParen))
564 const AsmToken &IntTok = Parser.getTok();
565 if (IntTok.isNot(AsmToken::Integer))
566 return Error(IntTok.getLoc(), "expected stack index");
567 switch (IntTok.getIntVal()) {
568 case 0: RegNo = X86::ST0; break;
569 case 1: RegNo = X86::ST1; break;
570 case 2: RegNo = X86::ST2; break;
571 case 3: RegNo = X86::ST3; break;
572 case 4: RegNo = X86::ST4; break;
573 case 5: RegNo = X86::ST5; break;
574 case 6: RegNo = X86::ST6; break;
575 case 7: RegNo = X86::ST7; break;
576 default: return Error(IntTok.getLoc(), "invalid stack index");
579 if (getParser().Lex().isNot(AsmToken::RParen))
580 return Error(Parser.getTok().getLoc(), "expected ')'");
582 EndLoc = Tok.getLoc();
583 Parser.Lex(); // Eat ')'
587 // If this is "db[0-7]", match it as an alias
589 if (RegNo == 0 && Tok.getString().size() == 3 &&
590 Tok.getString().startswith("db")) {
591 switch (Tok.getString()[2]) {
592 case '0': RegNo = X86::DR0; break;
593 case '1': RegNo = X86::DR1; break;
594 case '2': RegNo = X86::DR2; break;
595 case '3': RegNo = X86::DR3; break;
596 case '4': RegNo = X86::DR4; break;
597 case '5': RegNo = X86::DR5; break;
598 case '6': RegNo = X86::DR6; break;
599 case '7': RegNo = X86::DR7; break;
603 EndLoc = Tok.getLoc();
604 Parser.Lex(); // Eat it.
610 if (isParsingIntelSyntax()) return true;
611 return Error(StartLoc, "invalid register name",
612 SMRange(StartLoc, Tok.getEndLoc()));
615 EndLoc = Tok.getEndLoc();
616 Parser.Lex(); // Eat identifier token.
620 X86Operand *X86AsmParser::ParseOperand() {
621 if (isParsingIntelSyntax())
622 return ParseIntelOperand();
623 return ParseATTOperand();
626 /// getIntelMemOperandSize - Return intel memory operand size.
627 static unsigned getIntelMemOperandSize(StringRef OpStr) {
629 if (OpStr == "BYTE") Size = 8;
630 if (OpStr == "WORD") Size = 16;
631 if (OpStr == "DWORD") Size = 32;
632 if (OpStr == "QWORD") Size = 64;
633 if (OpStr == "XWORD") Size = 80;
634 if (OpStr == "XMMWORD") Size = 128;
635 if (OpStr == "YMMWORD") Size = 256;
639 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
641 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
642 SMLoc Start = Parser.getTok().getLoc(), End;
644 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
645 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
648 if (getLexer().isNot(AsmToken::LBrac))
649 return ErrorOperand(Start, "Expected '[' token!");
652 if (getLexer().is(AsmToken::Identifier)) {
654 if (ParseRegister(BaseReg, Start, End)) {
655 // Handle '[' 'symbol' ']'
656 if (getParser().ParseExpression(Disp, End)) return 0;
657 if (getLexer().isNot(AsmToken::RBrac))
658 return ErrorOperand(Start, "Expected ']' token!");
660 return X86Operand::CreateMem(Disp, Start, End, Size);
662 } else if (getLexer().is(AsmToken::Integer)) {
663 int64_t Val = Parser.getTok().getIntVal();
665 SMLoc Loc = Parser.getTok().getLoc();
666 if (getLexer().is(AsmToken::RBrac)) {
667 // Handle '[' number ']'
669 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
671 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
673 return X86Operand::CreateMem(Disp, Start, End, Size);
674 } else if (getLexer().is(AsmToken::Star)) {
675 // Handle '[' Scale*IndexReg ']'
677 SMLoc IdxRegLoc = Parser.getTok().getLoc();
678 if (ParseRegister(IndexReg, IdxRegLoc, End))
679 return ErrorOperand(IdxRegLoc, "Expected register");
682 return ErrorOperand(Loc, "Unexpected token");
685 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
686 bool isPlus = getLexer().is(AsmToken::Plus);
688 SMLoc PlusLoc = Parser.getTok().getLoc();
689 if (getLexer().is(AsmToken::Integer)) {
690 int64_t Val = Parser.getTok().getIntVal();
692 if (getLexer().is(AsmToken::Star)) {
694 SMLoc IdxRegLoc = Parser.getTok().getLoc();
695 if (ParseRegister(IndexReg, IdxRegLoc, End))
696 return ErrorOperand(IdxRegLoc, "Expected register");
698 } else if (getLexer().is(AsmToken::RBrac)) {
699 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
700 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
702 return ErrorOperand(PlusLoc, "unexpected token after +");
703 } else if (getLexer().is(AsmToken::Identifier)) {
704 // This could be an index register or a displacement expression.
705 End = Parser.getTok().getLoc();
707 ParseRegister(IndexReg, Start, End);
708 else if (getParser().ParseExpression(Disp, End)) return 0;
712 if (getLexer().isNot(AsmToken::RBrac))
713 if (getParser().ParseExpression(Disp, End)) return 0;
715 End = Parser.getTok().getLoc();
716 if (getLexer().isNot(AsmToken::RBrac))
717 return ErrorOperand(End, "expected ']' token!");
719 End = Parser.getTok().getLoc();
722 if (!BaseReg && !IndexReg)
723 return X86Operand::CreateMem(Disp, Start, End, Size);
725 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
729 /// ParseIntelMemOperand - Parse intel style memory operand.
730 X86Operand *X86AsmParser::ParseIntelMemOperand() {
731 const AsmToken &Tok = Parser.getTok();
732 SMLoc Start = Parser.getTok().getLoc(), End;
735 unsigned Size = getIntelMemOperandSize(Tok.getString());
738 assert (Tok.getString() == "PTR" && "Unexpected token!");
742 if (getLexer().is(AsmToken::LBrac))
743 return ParseIntelBracExpression(SegReg, Size);
745 if (!ParseRegister(SegReg, Start, End)) {
746 // Handel SegReg : [ ... ]
747 if (getLexer().isNot(AsmToken::Colon))
748 return ErrorOperand(Start, "Expected ':' token!");
749 Parser.Lex(); // Eat :
750 if (getLexer().isNot(AsmToken::LBrac))
751 return ErrorOperand(Start, "Expected '[' token!");
752 return ParseIntelBracExpression(SegReg, Size);
755 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
756 if (getParser().ParseExpression(Disp, End)) return 0;
757 return X86Operand::CreateMem(Disp, Start, End, Size);
760 X86Operand *X86AsmParser::ParseIntelOperand() {
761 SMLoc Start = Parser.getTok().getLoc(), End;
764 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
765 getLexer().is(AsmToken::Minus)) {
767 if (!getParser().ParseExpression(Val, End)) {
768 End = Parser.getTok().getLoc();
769 return X86Operand::CreateImm(Val, Start, End);
775 if (!ParseRegister(RegNo, Start, End)) {
776 End = Parser.getTok().getLoc();
777 return X86Operand::CreateReg(RegNo, Start, End);
781 return ParseIntelMemOperand();
784 X86Operand *X86AsmParser::ParseATTOperand() {
785 switch (getLexer().getKind()) {
787 // Parse a memory operand with no segment register.
788 return ParseMemOperand(0, Parser.getTok().getLoc());
789 case AsmToken::Percent: {
790 // Read the register.
793 if (ParseRegister(RegNo, Start, End)) return 0;
794 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
795 Error(Start, "%eiz and %riz can only be used as index registers",
796 SMRange(Start, End));
800 // If this is a segment register followed by a ':', then this is the start
801 // of a memory reference, otherwise this is a normal register reference.
802 if (getLexer().isNot(AsmToken::Colon))
803 return X86Operand::CreateReg(RegNo, Start, End);
806 getParser().Lex(); // Eat the colon.
807 return ParseMemOperand(RegNo, Start);
809 case AsmToken::Dollar: {
811 SMLoc Start = Parser.getTok().getLoc(), End;
814 if (getParser().ParseExpression(Val, End))
816 return X86Operand::CreateImm(Val, Start, End);
821 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
822 /// has already been parsed if present.
823 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
825 // We have to disambiguate a parenthesized expression "(4+5)" from the start
826 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
827 // only way to do this without lookahead is to eat the '(' and see what is
829 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
830 if (getLexer().isNot(AsmToken::LParen)) {
832 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
834 // After parsing the base expression we could either have a parenthesized
835 // memory address or not. If not, return now. If so, eat the (.
836 if (getLexer().isNot(AsmToken::LParen)) {
837 // Unless we have a segment register, treat this as an immediate.
839 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
840 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
846 // Okay, we have a '('. We don't know if this is an expression or not, but
847 // so we have to eat the ( to see beyond it.
848 SMLoc LParenLoc = Parser.getTok().getLoc();
849 Parser.Lex(); // Eat the '('.
851 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
852 // Nothing to do here, fall into the code below with the '(' part of the
853 // memory operand consumed.
857 // It must be an parenthesized expression, parse it now.
858 if (getParser().ParseParenExpression(Disp, ExprEnd))
861 // After parsing the base expression we could either have a parenthesized
862 // memory address or not. If not, return now. If so, eat the (.
863 if (getLexer().isNot(AsmToken::LParen)) {
864 // Unless we have a segment register, treat this as an immediate.
866 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
867 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
875 // If we reached here, then we just ate the ( of the memory operand. Process
876 // the rest of the memory operand.
877 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
880 if (getLexer().is(AsmToken::Percent)) {
881 SMLoc StartLoc, EndLoc;
882 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
883 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
884 Error(StartLoc, "eiz and riz can only be used as index registers",
885 SMRange(StartLoc, EndLoc));
890 if (getLexer().is(AsmToken::Comma)) {
891 Parser.Lex(); // Eat the comma.
892 IndexLoc = Parser.getTok().getLoc();
894 // Following the comma we should have either an index register, or a scale
895 // value. We don't support the later form, but we want to parse it
898 // Not that even though it would be completely consistent to support syntax
899 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
900 if (getLexer().is(AsmToken::Percent)) {
902 if (ParseRegister(IndexReg, L, L)) return 0;
904 if (getLexer().isNot(AsmToken::RParen)) {
905 // Parse the scale amount:
906 // ::= ',' [scale-expression]
907 if (getLexer().isNot(AsmToken::Comma)) {
908 Error(Parser.getTok().getLoc(),
909 "expected comma in scale expression");
912 Parser.Lex(); // Eat the comma.
914 if (getLexer().isNot(AsmToken::RParen)) {
915 SMLoc Loc = Parser.getTok().getLoc();
918 if (getParser().ParseAbsoluteExpression(ScaleVal)){
919 Error(Loc, "expected scale expression");
923 // Validate the scale amount.
924 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
925 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
928 Scale = (unsigned)ScaleVal;
931 } else if (getLexer().isNot(AsmToken::RParen)) {
932 // A scale amount without an index is ignored.
934 SMLoc Loc = Parser.getTok().getLoc();
937 if (getParser().ParseAbsoluteExpression(Value))
941 Warning(Loc, "scale factor without index register is ignored");
946 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
947 if (getLexer().isNot(AsmToken::RParen)) {
948 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
951 SMLoc MemEnd = Parser.getTok().getLoc();
952 Parser.Lex(); // Eat the ')'.
954 // If we have both a base register and an index register make sure they are
955 // both 64-bit or 32-bit registers.
956 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
957 if (BaseReg != 0 && IndexReg != 0) {
958 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
959 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
960 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
961 IndexReg != X86::RIZ) {
962 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
965 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
966 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
967 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
968 IndexReg != X86::EIZ){
969 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
974 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
979 ParseInstruction(StringRef Name, SMLoc NameLoc,
980 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
981 StringRef PatchedName = Name;
983 // FIXME: Hack to recognize setneb as setne.
984 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
985 PatchedName != "setb" && PatchedName != "setnb")
986 PatchedName = PatchedName.substr(0, Name.size()-1);
988 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
989 const MCExpr *ExtraImmOp = 0;
990 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
991 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
992 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
993 bool IsVCMP = PatchedName[0] == 'v';
994 unsigned SSECCIdx = IsVCMP ? 4 : 3;
995 unsigned SSEComparisonCode = StringSwitch<unsigned>(
996 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1000 .Case("unord", 0x03)
1005 /* AVX only from here */
1006 .Case("eq_uq", 0x08)
1009 .Case("false", 0x0B)
1010 .Case("neq_oq", 0x0C)
1014 .Case("eq_os", 0x10)
1015 .Case("lt_oq", 0x11)
1016 .Case("le_oq", 0x12)
1017 .Case("unord_s", 0x13)
1018 .Case("neq_us", 0x14)
1019 .Case("nlt_uq", 0x15)
1020 .Case("nle_uq", 0x16)
1021 .Case("ord_s", 0x17)
1022 .Case("eq_us", 0x18)
1023 .Case("nge_uq", 0x19)
1024 .Case("ngt_uq", 0x1A)
1025 .Case("false_os", 0x1B)
1026 .Case("neq_os", 0x1C)
1027 .Case("ge_oq", 0x1D)
1028 .Case("gt_oq", 0x1E)
1029 .Case("true_us", 0x1F)
1031 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1032 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1033 getParser().getContext());
1034 if (PatchedName.endswith("ss")) {
1035 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1036 } else if (PatchedName.endswith("sd")) {
1037 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1038 } else if (PatchedName.endswith("ps")) {
1039 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1041 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1042 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1047 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1049 if (ExtraImmOp && !isParsingIntelSyntax())
1050 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1052 // Determine whether this is an instruction prefix.
1054 Name == "lock" || Name == "rep" ||
1055 Name == "repe" || Name == "repz" ||
1056 Name == "repne" || Name == "repnz" ||
1057 Name == "rex64" || Name == "data16";
1060 // This does the actual operand parsing. Don't parse any more if we have a
1061 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1062 // just want to parse the "lock" as the first instruction and the "incl" as
1064 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1066 // Parse '*' modifier.
1067 if (getLexer().is(AsmToken::Star)) {
1068 SMLoc Loc = Parser.getTok().getLoc();
1069 Operands.push_back(X86Operand::CreateToken("*", Loc));
1070 Parser.Lex(); // Eat the star.
1073 // Read the first operand.
1074 if (X86Operand *Op = ParseOperand())
1075 Operands.push_back(Op);
1077 Parser.EatToEndOfStatement();
1081 while (getLexer().is(AsmToken::Comma)) {
1082 Parser.Lex(); // Eat the comma.
1084 // Parse and remember the operand.
1085 if (X86Operand *Op = ParseOperand())
1086 Operands.push_back(Op);
1088 Parser.EatToEndOfStatement();
1093 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1094 SMLoc Loc = getLexer().getLoc();
1095 Parser.EatToEndOfStatement();
1096 return Error(Loc, "unexpected token in argument list");
1100 if (getLexer().is(AsmToken::EndOfStatement))
1101 Parser.Lex(); // Consume the EndOfStatement
1102 else if (isPrefix && getLexer().is(AsmToken::Slash))
1103 Parser.Lex(); // Consume the prefix separator Slash
1105 if (ExtraImmOp && isParsingIntelSyntax())
1106 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1108 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1109 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1110 // documented form in various unofficial manuals, so a lot of code uses it.
1111 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1112 Operands.size() == 3) {
1113 X86Operand &Op = *(X86Operand*)Operands.back();
1114 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1115 isa<MCConstantExpr>(Op.Mem.Disp) &&
1116 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1117 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1118 SMLoc Loc = Op.getEndLoc();
1119 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1123 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1124 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1125 Operands.size() == 3) {
1126 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1127 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1128 isa<MCConstantExpr>(Op.Mem.Disp) &&
1129 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1130 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1131 SMLoc Loc = Op.getEndLoc();
1132 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1136 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1137 if (Name.startswith("ins") && Operands.size() == 3 &&
1138 (Name == "insb" || Name == "insw" || Name == "insl")) {
1139 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1140 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1141 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1142 Operands.pop_back();
1143 Operands.pop_back();
1149 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1150 if (Name.startswith("outs") && Operands.size() == 3 &&
1151 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1152 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1153 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1154 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1155 Operands.pop_back();
1156 Operands.pop_back();
1162 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1163 if (Name.startswith("movs") && Operands.size() == 3 &&
1164 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1165 (is64BitMode() && Name == "movsq"))) {
1166 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1167 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1168 if (isSrcOp(Op) && isDstOp(Op2)) {
1169 Operands.pop_back();
1170 Operands.pop_back();
1175 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1176 if (Name.startswith("lods") && Operands.size() == 3 &&
1177 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1178 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1179 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1180 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1181 if (isSrcOp(*Op1) && Op2->isReg()) {
1183 unsigned reg = Op2->getReg();
1184 bool isLods = Name == "lods";
1185 if (reg == X86::AL && (isLods || Name == "lodsb"))
1187 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1189 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1191 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1196 Operands.pop_back();
1197 Operands.pop_back();
1201 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1205 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1206 if (Name.startswith("stos") && Operands.size() == 3 &&
1207 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1208 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1209 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1210 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1211 if (isDstOp(*Op2) && Op1->isReg()) {
1213 unsigned reg = Op1->getReg();
1214 bool isStos = Name == "stos";
1215 if (reg == X86::AL && (isStos || Name == "stosb"))
1217 else if (reg == X86::AX && (isStos || Name == "stosw"))
1219 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1221 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1226 Operands.pop_back();
1227 Operands.pop_back();
1231 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1236 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1238 if ((Name.startswith("shr") || Name.startswith("sar") ||
1239 Name.startswith("shl") || Name.startswith("sal") ||
1240 Name.startswith("rcl") || Name.startswith("rcr") ||
1241 Name.startswith("rol") || Name.startswith("ror")) &&
1242 Operands.size() == 3) {
1243 if (isParsingIntelSyntax()) {
1245 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1246 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1247 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1249 Operands.pop_back();
1252 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1253 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1254 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1256 Operands.erase(Operands.begin() + 1);
1261 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1262 // instalias with an immediate operand yet.
1263 if (Name == "int" && Operands.size() == 2) {
1264 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1265 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1266 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1268 Operands.erase(Operands.begin() + 1);
1269 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1277 processInstruction(MCInst &Inst,
1278 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1279 switch (Inst.getOpcode()) {
1280 default: return false;
1281 case X86::AND16i16: {
1282 if (!Inst.getOperand(0).isImm() ||
1283 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1287 TmpInst.setOpcode(X86::AND16ri8);
1288 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1289 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1290 TmpInst.addOperand(Inst.getOperand(0));
1294 case X86::AND32i32: {
1295 if (!Inst.getOperand(0).isImm() ||
1296 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1300 TmpInst.setOpcode(X86::AND32ri8);
1301 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1302 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1303 TmpInst.addOperand(Inst.getOperand(0));
1307 case X86::AND64i32: {
1308 if (!Inst.getOperand(0).isImm() ||
1309 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1313 TmpInst.setOpcode(X86::AND64ri8);
1314 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1315 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1316 TmpInst.addOperand(Inst.getOperand(0));
1320 case X86::XOR16i16: {
1321 if (!Inst.getOperand(0).isImm() ||
1322 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1326 TmpInst.setOpcode(X86::XOR16ri8);
1327 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1328 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1329 TmpInst.addOperand(Inst.getOperand(0));
1333 case X86::XOR32i32: {
1334 if (!Inst.getOperand(0).isImm() ||
1335 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1339 TmpInst.setOpcode(X86::XOR32ri8);
1340 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1341 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1342 TmpInst.addOperand(Inst.getOperand(0));
1346 case X86::XOR64i32: {
1347 if (!Inst.getOperand(0).isImm() ||
1348 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1352 TmpInst.setOpcode(X86::XOR64ri8);
1353 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1354 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1355 TmpInst.addOperand(Inst.getOperand(0));
1359 case X86::OR16i16: {
1360 if (!Inst.getOperand(0).isImm() ||
1361 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1365 TmpInst.setOpcode(X86::OR16ri8);
1366 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1367 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1368 TmpInst.addOperand(Inst.getOperand(0));
1372 case X86::OR32i32: {
1373 if (!Inst.getOperand(0).isImm() ||
1374 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1378 TmpInst.setOpcode(X86::OR32ri8);
1379 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1380 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1381 TmpInst.addOperand(Inst.getOperand(0));
1385 case X86::OR64i32: {
1386 if (!Inst.getOperand(0).isImm() ||
1387 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1391 TmpInst.setOpcode(X86::OR64ri8);
1392 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1393 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1394 TmpInst.addOperand(Inst.getOperand(0));
1398 case X86::CMP16i16: {
1399 if (!Inst.getOperand(0).isImm() ||
1400 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1404 TmpInst.setOpcode(X86::CMP16ri8);
1405 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1406 TmpInst.addOperand(Inst.getOperand(0));
1410 case X86::CMP32i32: {
1411 if (!Inst.getOperand(0).isImm() ||
1412 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1416 TmpInst.setOpcode(X86::CMP32ri8);
1417 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1418 TmpInst.addOperand(Inst.getOperand(0));
1422 case X86::CMP64i32: {
1423 if (!Inst.getOperand(0).isImm() ||
1424 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1428 TmpInst.setOpcode(X86::CMP64ri8);
1429 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1430 TmpInst.addOperand(Inst.getOperand(0));
1434 case X86::ADD16i16: {
1435 if (!Inst.getOperand(0).isImm() ||
1436 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1440 TmpInst.setOpcode(X86::ADD16ri8);
1441 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1442 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1443 TmpInst.addOperand(Inst.getOperand(0));
1447 case X86::ADD32i32: {
1448 if (!Inst.getOperand(0).isImm() ||
1449 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1453 TmpInst.setOpcode(X86::ADD32ri8);
1454 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1455 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1456 TmpInst.addOperand(Inst.getOperand(0));
1460 case X86::ADD64i32: {
1461 if (!Inst.getOperand(0).isImm() ||
1462 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1466 TmpInst.setOpcode(X86::ADD64ri8);
1467 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1468 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1469 TmpInst.addOperand(Inst.getOperand(0));
1473 case X86::SUB16i16: {
1474 if (!Inst.getOperand(0).isImm() ||
1475 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1479 TmpInst.setOpcode(X86::SUB16ri8);
1480 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1481 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1482 TmpInst.addOperand(Inst.getOperand(0));
1486 case X86::SUB32i32: {
1487 if (!Inst.getOperand(0).isImm() ||
1488 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1492 TmpInst.setOpcode(X86::SUB32ri8);
1493 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1494 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1495 TmpInst.addOperand(Inst.getOperand(0));
1499 case X86::SUB64i32: {
1500 if (!Inst.getOperand(0).isImm() ||
1501 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1505 TmpInst.setOpcode(X86::SUB64ri8);
1506 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1507 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1508 TmpInst.addOperand(Inst.getOperand(0));
1516 MatchAndEmitInstruction(SMLoc IDLoc,
1517 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1519 SmallVector<MCInst, 2> Insts;
1521 bool Error = MatchInstruction(IDLoc, Operands, Insts, ErrorInfo);
1523 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
1524 Out.EmitInstruction(Insts[i]);
1529 MatchInstruction(SMLoc IDLoc,
1530 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1531 SmallVectorImpl<MCInst> &MCInsts, unsigned &OrigErrorInfo,
1532 bool matchingInlineAsm) {
1533 assert(!Operands.empty() && "Unexpect empty operand list!");
1534 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1535 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1536 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1538 // First, handle aliases that expand to multiple instructions.
1539 // FIXME: This should be replaced with a real .td file alias mechanism.
1540 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1542 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1543 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1544 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1545 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1547 Inst.setOpcode(X86::WAIT);
1549 MCInsts.push_back(Inst);
1552 StringSwitch<const char*>(Op->getToken())
1553 .Case("finit", "fninit")
1554 .Case("fsave", "fnsave")
1555 .Case("fstcw", "fnstcw")
1556 .Case("fstcww", "fnstcw")
1557 .Case("fstenv", "fnstenv")
1558 .Case("fstsw", "fnstsw")
1559 .Case("fstsww", "fnstsw")
1560 .Case("fclex", "fnclex")
1562 assert(Repl && "Unknown wait-prefixed instruction");
1564 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1567 bool WasOriginallyInvalidOperand = false;
1570 // First, try a direct match.
1571 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo,
1572 isParsingIntelSyntax())) {
1575 // Some instructions need post-processing to, for example, tweak which
1576 // encoding is selected. Loop on it while changes happen so the
1577 // individual transformations can chain off each other.
1578 while (processInstruction(Inst, Operands))
1582 MCInsts.push_back(Inst);
1584 case Match_MissingFeature:
1585 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1586 EmptyRanges, matchingInlineAsm);
1588 case Match_ConversionFail:
1589 return Error(IDLoc, "unable to convert operands to instruction",
1590 EmptyRanges, matchingInlineAsm);
1591 case Match_InvalidOperand:
1592 WasOriginallyInvalidOperand = true;
1594 case Match_MnemonicFail:
1598 // FIXME: Ideally, we would only attempt suffix matches for things which are
1599 // valid prefixes, and we could just infer the right unambiguous
1600 // type. However, that requires substantially more matcher support than the
1603 // Change the operand to point to a temporary token.
1604 StringRef Base = Op->getToken();
1605 SmallString<16> Tmp;
1608 Op->setTokenValue(Tmp.str());
1610 // If this instruction starts with an 'f', then it is a floating point stack
1611 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1612 // 80-bit floating point, which use the suffixes s,l,t respectively.
1614 // Otherwise, we assume that this may be an integer instruction, which comes
1615 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1616 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1618 // Check for the various suffix matches.
1619 Tmp[Base.size()] = Suffixes[0];
1620 unsigned ErrorInfoIgnore;
1621 unsigned Match1, Match2, Match3, Match4;
1623 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1624 Tmp[Base.size()] = Suffixes[1];
1625 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1626 Tmp[Base.size()] = Suffixes[2];
1627 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1628 Tmp[Base.size()] = Suffixes[3];
1629 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1631 // Restore the old token.
1632 Op->setTokenValue(Base);
1634 // If exactly one matched, then we treat that as a successful match (and the
1635 // instruction will already have been filled in correctly, since the failing
1636 // matches won't have modified it).
1637 unsigned NumSuccessfulMatches =
1638 (Match1 == Match_Success) + (Match2 == Match_Success) +
1639 (Match3 == Match_Success) + (Match4 == Match_Success);
1640 if (NumSuccessfulMatches == 1) {
1642 MCInsts.push_back(Inst);
1646 // Otherwise, the match failed, try to produce a decent error message.
1648 // If we had multiple suffix matches, then identify this as an ambiguous
1650 if (NumSuccessfulMatches > 1) {
1652 unsigned NumMatches = 0;
1653 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1654 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1655 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1656 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1658 SmallString<126> Msg;
1659 raw_svector_ostream OS(Msg);
1660 OS << "ambiguous instructions require an explicit suffix (could be ";
1661 for (unsigned i = 0; i != NumMatches; ++i) {
1664 if (i + 1 == NumMatches)
1666 OS << "'" << Base << MatchChars[i] << "'";
1669 Error(IDLoc, OS.str(), EmptyRanges, matchingInlineAsm);
1673 // Okay, we know that none of the variants matched successfully.
1675 // If all of the instructions reported an invalid mnemonic, then the original
1676 // mnemonic was invalid.
1677 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1678 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1679 if (!WasOriginallyInvalidOperand) {
1680 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1681 Op->getLocRange(), matchingInlineAsm);
1684 // Recover location info for the operand if we know which was the problem.
1685 if (OrigErrorInfo != ~0U) {
1686 if (OrigErrorInfo >= Operands.size())
1687 return Error(IDLoc, "too few operands for instruction",
1688 EmptyRanges, matchingInlineAsm);
1690 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1691 if (Operand->getStartLoc().isValid()) {
1692 SMRange OperandRange = Operand->getLocRange();
1693 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1694 OperandRange, matchingInlineAsm);
1698 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1702 // If one instruction matched with a missing feature, report this as a
1704 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1705 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1706 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1707 EmptyRanges, matchingInlineAsm);
1711 // If one instruction matched with an invalid operand, report this as an
1713 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1714 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1715 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1720 // If all of these were an outright failure, report it in a useless way.
1721 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1722 EmptyRanges, matchingInlineAsm);
1727 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1728 StringRef IDVal = DirectiveID.getIdentifier();
1729 if (IDVal == ".word")
1730 return ParseDirectiveWord(2, DirectiveID.getLoc());
1731 else if (IDVal.startswith(".code"))
1732 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1733 else if (IDVal.startswith(".intel_syntax")) {
1734 getParser().setAssemblerDialect(1);
1735 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1736 if(Parser.getTok().getString() == "noprefix") {
1737 // FIXME : Handle noprefix
1747 /// ParseDirectiveWord
1748 /// ::= .word [ expression (, expression)* ]
1749 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1750 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1752 const MCExpr *Value;
1753 if (getParser().ParseExpression(Value))
1756 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1758 if (getLexer().is(AsmToken::EndOfStatement))
1761 // FIXME: Improve diagnostic.
1762 if (getLexer().isNot(AsmToken::Comma))
1763 return Error(L, "unexpected token in directive");
1772 /// ParseDirectiveCode
1773 /// ::= .code32 | .code64
1774 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1775 if (IDVal == ".code32") {
1777 if (is64BitMode()) {
1779 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1781 } else if (IDVal == ".code64") {
1783 if (!is64BitMode()) {
1785 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1788 return Error(L, "unexpected directive " + IDVal);
1795 extern "C" void LLVMInitializeX86AsmLexer();
1797 // Force static initialization.
1798 extern "C" void LLVMInitializeX86AsmParser() {
1799 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1800 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1801 LLVMInitializeX86AsmLexer();
1804 #define GET_REGISTER_MATCHER
1805 #define GET_MATCHER_IMPLEMENTATION
1806 #include "X86GenAsmMatcher.inc"