1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
34 class X86AsmParser : public MCTargetAsmParser {
38 MCAsmParser &getParser() const { return Parser; }
40 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
42 bool Error(SMLoc L, const Twine &Msg,
43 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) {
44 return Parser.Error(L, Msg, Ranges);
47 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
52 X86Operand *ParseOperand();
53 X86Operand *ParseATTOperand();
54 X86Operand *ParseIntelOperand();
55 X86Operand *ParseIntelMemOperand();
56 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
57 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
59 bool ParseDirectiveWord(unsigned Size, SMLoc L);
60 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
62 bool processInstruction(MCInst &Inst,
63 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
65 bool MatchAndEmitInstruction(SMLoc IDLoc,
66 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
69 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
70 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
71 bool isSrcOp(X86Operand &Op);
73 /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
74 /// or %es:(%edi) in 32bit mode.
75 bool isDstOp(X86Operand &Op);
77 bool is64BitMode() const {
78 // FIXME: Can tablegen auto-generate this?
79 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
82 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
83 setAvailableFeatures(FB);
86 /// @name Auto-generated Matcher Functions
89 #define GET_ASSEMBLER_HEADER
90 #include "X86GenAsmMatcher.inc"
95 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
96 : MCTargetAsmParser(), STI(sti), Parser(parser) {
98 // Initialize the set of available features.
99 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
101 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
103 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
104 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
106 virtual bool ParseDirective(AsmToken DirectiveID);
108 bool isParsingIntelSyntax() {
109 return getParser().getAssemblerDialect();
112 } // end anonymous namespace
114 /// @name Auto-generated Match Functions
117 static unsigned MatchRegisterName(StringRef Name);
121 static bool isImmSExti16i8Value(uint64_t Value) {
122 return (( Value <= 0x000000000000007FULL)||
123 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
124 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
127 static bool isImmSExti32i8Value(uint64_t Value) {
128 return (( Value <= 0x000000000000007FULL)||
129 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
130 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
133 static bool isImmZExtu32u8Value(uint64_t Value) {
134 return (Value <= 0x00000000000000FFULL);
137 static bool isImmSExti64i8Value(uint64_t Value) {
138 return (( Value <= 0x000000000000007FULL)||
139 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
142 static bool isImmSExti64i32Value(uint64_t Value) {
143 return (( Value <= 0x000000007FFFFFFFULL)||
144 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
148 /// X86Operand - Instances of this class represent a parsed X86 machine
150 struct X86Operand : public MCParsedAsmOperand {
158 SMLoc StartLoc, EndLoc;
184 X86Operand(KindTy K, SMLoc Start, SMLoc End)
185 : Kind(K), StartLoc(Start), EndLoc(End) {}
187 /// getStartLoc - Get the location of the first token of this operand.
188 SMLoc getStartLoc() const { return StartLoc; }
189 /// getEndLoc - Get the location of the last token of this operand.
190 SMLoc getEndLoc() const { return EndLoc; }
192 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
194 virtual void print(raw_ostream &OS) const {}
196 StringRef getToken() const {
197 assert(Kind == Token && "Invalid access!");
198 return StringRef(Tok.Data, Tok.Length);
200 void setTokenValue(StringRef Value) {
201 assert(Kind == Token && "Invalid access!");
202 Tok.Data = Value.data();
203 Tok.Length = Value.size();
206 unsigned getReg() const {
207 assert(Kind == Register && "Invalid access!");
211 const MCExpr *getImm() const {
212 assert(Kind == Immediate && "Invalid access!");
216 const MCExpr *getMemDisp() const {
217 assert(Kind == Memory && "Invalid access!");
220 unsigned getMemSegReg() const {
221 assert(Kind == Memory && "Invalid access!");
224 unsigned getMemBaseReg() const {
225 assert(Kind == Memory && "Invalid access!");
228 unsigned getMemIndexReg() const {
229 assert(Kind == Memory && "Invalid access!");
232 unsigned getMemScale() const {
233 assert(Kind == Memory && "Invalid access!");
237 bool isToken() const {return Kind == Token; }
239 bool isImm() const { return Kind == Immediate; }
241 bool isImmSExti16i8() const {
245 // If this isn't a constant expr, just assume it fits and let relaxation
247 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
251 // Otherwise, check the value is in a range that makes sense for this
253 return isImmSExti16i8Value(CE->getValue());
255 bool isImmSExti32i8() 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 isImmSExti32i8Value(CE->getValue());
269 bool isImmZExtu32u8() 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 isImmZExtu32u8Value(CE->getValue());
283 bool isImmSExti64i8() 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 isImmSExti64i8Value(CE->getValue());
297 bool isImmSExti64i32() 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 isImmSExti64i32Value(CE->getValue());
312 bool isMem() const { return Kind == Memory; }
313 bool isMem8() const {
314 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
316 bool isMem16() const {
317 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
319 bool isMem32() const {
320 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
322 bool isMem64() const {
323 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
325 bool isMem80() const {
326 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
328 bool isMem128() const {
329 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
331 bool isMem256() const {
332 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
335 bool isAbsMem() const {
336 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
337 !getMemIndexReg() && getMemScale() == 1;
340 bool isReg() const { return Kind == Register; }
342 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
343 // Add as immediates when possible.
344 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
345 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
347 Inst.addOperand(MCOperand::CreateExpr(Expr));
350 void addRegOperands(MCInst &Inst, unsigned N) const {
351 assert(N == 1 && "Invalid number of operands!");
352 Inst.addOperand(MCOperand::CreateReg(getReg()));
355 void addImmOperands(MCInst &Inst, unsigned N) const {
356 assert(N == 1 && "Invalid number of operands!");
357 addExpr(Inst, getImm());
360 void addMem8Operands(MCInst &Inst, unsigned N) const {
361 addMemOperands(Inst, N);
363 void addMem16Operands(MCInst &Inst, unsigned N) const {
364 addMemOperands(Inst, N);
366 void addMem32Operands(MCInst &Inst, unsigned N) const {
367 addMemOperands(Inst, N);
369 void addMem64Operands(MCInst &Inst, unsigned N) const {
370 addMemOperands(Inst, N);
372 void addMem80Operands(MCInst &Inst, unsigned N) const {
373 addMemOperands(Inst, N);
375 void addMem128Operands(MCInst &Inst, unsigned N) const {
376 addMemOperands(Inst, N);
378 void addMem256Operands(MCInst &Inst, unsigned N) const {
379 addMemOperands(Inst, N);
382 void addMemOperands(MCInst &Inst, unsigned N) const {
383 assert((N == 5) && "Invalid number of operands!");
384 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
385 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
386 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
387 addExpr(Inst, getMemDisp());
388 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
391 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
392 assert((N == 1) && "Invalid number of operands!");
393 // Add as immediates when possible.
394 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
395 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
397 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
400 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
401 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
402 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
403 Res->Tok.Data = Str.data();
404 Res->Tok.Length = Str.size();
408 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
409 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
410 Res->Reg.RegNo = RegNo;
414 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
415 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
420 /// Create an absolute memory operand.
421 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
422 SMLoc EndLoc, unsigned Size = 0) {
423 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
425 Res->Mem.Disp = Disp;
426 Res->Mem.BaseReg = 0;
427 Res->Mem.IndexReg = 0;
429 Res->Mem.Size = Size;
433 /// Create a generalized memory operand.
434 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
435 unsigned BaseReg, unsigned IndexReg,
436 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
438 // We should never just have a displacement, that should be parsed as an
439 // absolute memory operand.
440 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
442 // The scale should always be one of {1,2,4,8}.
443 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
445 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
446 Res->Mem.SegReg = SegReg;
447 Res->Mem.Disp = Disp;
448 Res->Mem.BaseReg = BaseReg;
449 Res->Mem.IndexReg = IndexReg;
450 Res->Mem.Scale = Scale;
451 Res->Mem.Size = Size;
456 } // end anonymous namespace.
458 bool X86AsmParser::isSrcOp(X86Operand &Op) {
459 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
461 return (Op.isMem() &&
462 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
463 isa<MCConstantExpr>(Op.Mem.Disp) &&
464 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
465 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
468 bool X86AsmParser::isDstOp(X86Operand &Op) {
469 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
471 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
472 isa<MCConstantExpr>(Op.Mem.Disp) &&
473 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
474 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
477 bool X86AsmParser::ParseRegister(unsigned &RegNo,
478 SMLoc &StartLoc, SMLoc &EndLoc) {
480 if (!isParsingIntelSyntax()) {
481 const AsmToken &TokPercent = Parser.getTok();
482 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
483 StartLoc = TokPercent.getLoc();
484 Parser.Lex(); // Eat percent token.
487 const AsmToken &Tok = Parser.getTok();
488 if (Tok.isNot(AsmToken::Identifier)) {
489 if (isParsingIntelSyntax()) return true;
490 return Error(StartLoc, "invalid register name",
491 SMRange(StartLoc, Tok.getEndLoc()));
494 RegNo = MatchRegisterName(Tok.getString());
496 // If the match failed, try the register name as lowercase.
498 RegNo = MatchRegisterName(Tok.getString().lower());
500 if (!is64BitMode()) {
501 // FIXME: This should be done using Requires<In32BitMode> and
502 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
504 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
506 if (RegNo == X86::RIZ ||
507 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
508 X86II::isX86_64NonExtLowByteReg(RegNo) ||
509 X86II::isX86_64ExtendedReg(RegNo))
510 return Error(StartLoc, "register %"
511 + Tok.getString() + " is only available in 64-bit mode",
512 SMRange(StartLoc, Tok.getEndLoc()));
515 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
516 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
518 EndLoc = Tok.getLoc();
519 Parser.Lex(); // Eat 'st'
521 // Check to see if we have '(4)' after %st.
522 if (getLexer().isNot(AsmToken::LParen))
527 const AsmToken &IntTok = Parser.getTok();
528 if (IntTok.isNot(AsmToken::Integer))
529 return Error(IntTok.getLoc(), "expected stack index");
530 switch (IntTok.getIntVal()) {
531 case 0: RegNo = X86::ST0; break;
532 case 1: RegNo = X86::ST1; break;
533 case 2: RegNo = X86::ST2; break;
534 case 3: RegNo = X86::ST3; break;
535 case 4: RegNo = X86::ST4; break;
536 case 5: RegNo = X86::ST5; break;
537 case 6: RegNo = X86::ST6; break;
538 case 7: RegNo = X86::ST7; break;
539 default: return Error(IntTok.getLoc(), "invalid stack index");
542 if (getParser().Lex().isNot(AsmToken::RParen))
543 return Error(Parser.getTok().getLoc(), "expected ')'");
545 EndLoc = Tok.getLoc();
546 Parser.Lex(); // Eat ')'
550 // If this is "db[0-7]", match it as an alias
552 if (RegNo == 0 && Tok.getString().size() == 3 &&
553 Tok.getString().startswith("db")) {
554 switch (Tok.getString()[2]) {
555 case '0': RegNo = X86::DR0; break;
556 case '1': RegNo = X86::DR1; break;
557 case '2': RegNo = X86::DR2; break;
558 case '3': RegNo = X86::DR3; break;
559 case '4': RegNo = X86::DR4; break;
560 case '5': RegNo = X86::DR5; break;
561 case '6': RegNo = X86::DR6; break;
562 case '7': RegNo = X86::DR7; break;
566 EndLoc = Tok.getLoc();
567 Parser.Lex(); // Eat it.
573 if (isParsingIntelSyntax()) return true;
574 return Error(StartLoc, "invalid register name",
575 SMRange(StartLoc, Tok.getEndLoc()));
578 EndLoc = Tok.getEndLoc();
579 Parser.Lex(); // Eat identifier token.
583 X86Operand *X86AsmParser::ParseOperand() {
584 if (isParsingIntelSyntax())
585 return ParseIntelOperand();
586 return ParseATTOperand();
589 /// getIntelMemOperandSize - Return intel memory operand size.
590 static unsigned getIntelMemOperandSize(StringRef OpStr) {
592 if (OpStr == "BYTE") Size = 8;
593 if (OpStr == "WORD") Size = 16;
594 if (OpStr == "DWORD") Size = 32;
595 if (OpStr == "QWORD") Size = 64;
596 if (OpStr == "XWORD") Size = 80;
597 if (OpStr == "XMMWORD") Size = 128;
598 if (OpStr == "YMMWORD") Size = 256;
602 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
604 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
605 SMLoc Start = Parser.getTok().getLoc(), End;
607 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
608 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
611 if (getLexer().isNot(AsmToken::LBrac))
612 return ErrorOperand(Start, "Expected '[' token!");
615 if (getLexer().is(AsmToken::Identifier)) {
617 if (ParseRegister(BaseReg, Start, End)) {
618 // Handle '[' 'symbol' ']'
619 if (getParser().ParseExpression(Disp, End)) return 0;
620 if (getLexer().isNot(AsmToken::RBrac))
621 return ErrorOperand(Start, "Expected ']' token!");
623 return X86Operand::CreateMem(Disp, Start, End, Size);
625 } else if (getLexer().is(AsmToken::Integer)) {
626 int64_t Val = Parser.getTok().getIntVal();
628 SMLoc Loc = Parser.getTok().getLoc();
629 if (getLexer().is(AsmToken::RBrac)) {
630 // Handle '[' number ']'
632 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
634 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
636 return X86Operand::CreateMem(Disp, Start, End, Size);
637 } else if (getLexer().is(AsmToken::Star)) {
638 // Handle '[' Scale*IndexReg ']'
640 SMLoc IdxRegLoc = Parser.getTok().getLoc();
641 if (ParseRegister(IndexReg, IdxRegLoc, End))
642 return ErrorOperand(IdxRegLoc, "Expected register");
645 return ErrorOperand(Loc, "Unepxeted token");
648 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
649 bool isPlus = getLexer().is(AsmToken::Plus);
651 SMLoc PlusLoc = Parser.getTok().getLoc();
652 if (getLexer().is(AsmToken::Integer)) {
653 int64_t Val = Parser.getTok().getIntVal();
655 if (getLexer().is(AsmToken::Star)) {
657 SMLoc IdxRegLoc = Parser.getTok().getLoc();
658 if (ParseRegister(IndexReg, IdxRegLoc, End))
659 return ErrorOperand(IdxRegLoc, "Expected register");
661 } else if (getLexer().is(AsmToken::RBrac)) {
662 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
663 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
665 return ErrorOperand(PlusLoc, "unexpected token after +");
666 } else if (getLexer().is(AsmToken::Identifier)) {
667 // This could be an index register or a displacement expression.
668 End = Parser.getTok().getLoc();
670 ParseRegister(IndexReg, Start, End);
671 else if (getParser().ParseExpression(Disp, End)) return 0;
675 if (getLexer().isNot(AsmToken::RBrac))
676 if (getParser().ParseExpression(Disp, End)) return 0;
678 End = Parser.getTok().getLoc();
679 if (getLexer().isNot(AsmToken::RBrac))
680 return ErrorOperand(End, "expected ']' token!");
682 End = Parser.getTok().getLoc();
685 if (!BaseReg && !IndexReg)
686 return X86Operand::CreateMem(Disp, Start, End, Size);
688 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
692 /// ParseIntelMemOperand - Parse intel style memory operand.
693 X86Operand *X86AsmParser::ParseIntelMemOperand() {
694 const AsmToken &Tok = Parser.getTok();
695 SMLoc Start = Parser.getTok().getLoc(), End;
698 unsigned Size = getIntelMemOperandSize(Tok.getString());
701 assert (Tok.getString() == "PTR" && "Unexpected token!");
705 if (getLexer().is(AsmToken::LBrac))
706 return ParseIntelBracExpression(SegReg, Size);
708 if (!ParseRegister(SegReg, Start, End)) {
709 // Handel SegReg : [ ... ]
710 if (getLexer().isNot(AsmToken::Colon))
711 return ErrorOperand(Start, "Expected ':' token!");
712 Parser.Lex(); // Eat :
713 if (getLexer().isNot(AsmToken::LBrac))
714 return ErrorOperand(Start, "Expected '[' token!");
715 return ParseIntelBracExpression(SegReg, Size);
718 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
719 if (getParser().ParseExpression(Disp, End)) return 0;
720 return X86Operand::CreateMem(Disp, Start, End, Size);
723 X86Operand *X86AsmParser::ParseIntelOperand() {
724 SMLoc Start = Parser.getTok().getLoc(), End;
727 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
728 getLexer().is(AsmToken::Minus)) {
730 if (!getParser().ParseExpression(Val, End)) {
731 End = Parser.getTok().getLoc();
732 return X86Operand::CreateImm(Val, Start, End);
738 if (!ParseRegister(RegNo, Start, End)) {
739 End = Parser.getTok().getLoc();
740 return X86Operand::CreateReg(RegNo, Start, End);
744 return ParseIntelMemOperand();
747 X86Operand *X86AsmParser::ParseATTOperand() {
748 switch (getLexer().getKind()) {
750 // Parse a memory operand with no segment register.
751 return ParseMemOperand(0, Parser.getTok().getLoc());
752 case AsmToken::Percent: {
753 // Read the register.
756 if (ParseRegister(RegNo, Start, End)) return 0;
757 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
758 Error(Start, "%eiz and %riz can only be used as index registers",
759 SMRange(Start, End));
763 // If this is a segment register followed by a ':', then this is the start
764 // of a memory reference, otherwise this is a normal register reference.
765 if (getLexer().isNot(AsmToken::Colon))
766 return X86Operand::CreateReg(RegNo, Start, End);
769 getParser().Lex(); // Eat the colon.
770 return ParseMemOperand(RegNo, Start);
772 case AsmToken::Dollar: {
774 SMLoc Start = Parser.getTok().getLoc(), End;
777 if (getParser().ParseExpression(Val, End))
779 return X86Operand::CreateImm(Val, Start, End);
784 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
785 /// has already been parsed if present.
786 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
788 // We have to disambiguate a parenthesized expression "(4+5)" from the start
789 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
790 // only way to do this without lookahead is to eat the '(' and see what is
792 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
793 if (getLexer().isNot(AsmToken::LParen)) {
795 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
797 // After parsing the base expression we could either have a parenthesized
798 // memory address or not. If not, return now. If so, eat the (.
799 if (getLexer().isNot(AsmToken::LParen)) {
800 // Unless we have a segment register, treat this as an immediate.
802 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
803 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
809 // Okay, we have a '('. We don't know if this is an expression or not, but
810 // so we have to eat the ( to see beyond it.
811 SMLoc LParenLoc = Parser.getTok().getLoc();
812 Parser.Lex(); // Eat the '('.
814 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
815 // Nothing to do here, fall into the code below with the '(' part of the
816 // memory operand consumed.
820 // It must be an parenthesized expression, parse it now.
821 if (getParser().ParseParenExpression(Disp, ExprEnd))
824 // After parsing the base expression we could either have a parenthesized
825 // memory address or not. If not, return now. If so, eat the (.
826 if (getLexer().isNot(AsmToken::LParen)) {
827 // Unless we have a segment register, treat this as an immediate.
829 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
830 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
838 // If we reached here, then we just ate the ( of the memory operand. Process
839 // the rest of the memory operand.
840 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
842 if (getLexer().is(AsmToken::Percent)) {
843 SMLoc StartLoc, EndLoc;
844 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
845 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
846 Error(StartLoc, "eiz and riz can only be used as index registers",
847 SMRange(StartLoc, EndLoc));
852 if (getLexer().is(AsmToken::Comma)) {
853 Parser.Lex(); // Eat the comma.
855 // Following the comma we should have either an index register, or a scale
856 // value. We don't support the later form, but we want to parse it
859 // Not that even though it would be completely consistent to support syntax
860 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
861 if (getLexer().is(AsmToken::Percent)) {
863 if (ParseRegister(IndexReg, L, L)) return 0;
865 if (getLexer().isNot(AsmToken::RParen)) {
866 // Parse the scale amount:
867 // ::= ',' [scale-expression]
868 if (getLexer().isNot(AsmToken::Comma)) {
869 Error(Parser.getTok().getLoc(),
870 "expected comma in scale expression");
873 Parser.Lex(); // Eat the comma.
875 if (getLexer().isNot(AsmToken::RParen)) {
876 SMLoc Loc = Parser.getTok().getLoc();
879 if (getParser().ParseAbsoluteExpression(ScaleVal)){
880 Error(Loc, "expected scale expression");
884 // Validate the scale amount.
885 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
886 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
889 Scale = (unsigned)ScaleVal;
892 } else if (getLexer().isNot(AsmToken::RParen)) {
893 // A scale amount without an index is ignored.
895 SMLoc Loc = Parser.getTok().getLoc();
898 if (getParser().ParseAbsoluteExpression(Value))
902 Warning(Loc, "scale factor without index register is ignored");
907 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
908 if (getLexer().isNot(AsmToken::RParen)) {
909 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
912 SMLoc MemEnd = Parser.getTok().getLoc();
913 Parser.Lex(); // Eat the ')'.
915 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
920 ParseInstruction(StringRef Name, SMLoc NameLoc,
921 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
922 StringRef PatchedName = Name;
924 // FIXME: Hack to recognize setneb as setne.
925 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
926 PatchedName != "setb" && PatchedName != "setnb")
927 PatchedName = PatchedName.substr(0, Name.size()-1);
929 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
930 const MCExpr *ExtraImmOp = 0;
931 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
932 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
933 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
934 bool IsVCMP = PatchedName.startswith("vcmp");
935 unsigned SSECCIdx = IsVCMP ? 4 : 3;
936 unsigned SSEComparisonCode = StringSwitch<unsigned>(
937 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
950 .Case("neq_oq", 0x0C)
957 .Case("unord_s", 0x13)
958 .Case("neq_us", 0x14)
959 .Case("nlt_uq", 0x15)
960 .Case("nle_uq", 0x16)
963 .Case("nge_uq", 0x19)
964 .Case("ngt_uq", 0x1A)
965 .Case("false_os", 0x1B)
966 .Case("neq_os", 0x1C)
969 .Case("true_us", 0x1F)
971 if (SSEComparisonCode != ~0U) {
972 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
973 getParser().getContext());
974 if (PatchedName.endswith("ss")) {
975 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
976 } else if (PatchedName.endswith("sd")) {
977 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
978 } else if (PatchedName.endswith("ps")) {
979 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
981 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
982 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
987 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
989 if (ExtraImmOp && !isParsingIntelSyntax())
990 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
992 // Determine whether this is an instruction prefix.
994 Name == "lock" || Name == "rep" ||
995 Name == "repe" || Name == "repz" ||
996 Name == "repne" || Name == "repnz" ||
997 Name == "rex64" || Name == "data16";
1000 // This does the actual operand parsing. Don't parse any more if we have a
1001 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1002 // just want to parse the "lock" as the first instruction and the "incl" as
1004 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1006 // Parse '*' modifier.
1007 if (getLexer().is(AsmToken::Star)) {
1008 SMLoc Loc = Parser.getTok().getLoc();
1009 Operands.push_back(X86Operand::CreateToken("*", Loc));
1010 Parser.Lex(); // Eat the star.
1013 // Read the first operand.
1014 if (X86Operand *Op = ParseOperand())
1015 Operands.push_back(Op);
1017 Parser.EatToEndOfStatement();
1021 while (getLexer().is(AsmToken::Comma)) {
1022 Parser.Lex(); // Eat the comma.
1024 // Parse and remember the operand.
1025 if (X86Operand *Op = ParseOperand())
1026 Operands.push_back(Op);
1028 Parser.EatToEndOfStatement();
1033 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1034 SMLoc Loc = getLexer().getLoc();
1035 Parser.EatToEndOfStatement();
1036 return Error(Loc, "unexpected token in argument list");
1040 if (getLexer().is(AsmToken::EndOfStatement))
1041 Parser.Lex(); // Consume the EndOfStatement
1042 else if (isPrefix && getLexer().is(AsmToken::Slash))
1043 Parser.Lex(); // Consume the prefix separator Slash
1045 if (ExtraImmOp && isParsingIntelSyntax())
1046 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1048 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1049 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1050 // documented form in various unofficial manuals, so a lot of code uses it.
1051 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1052 Operands.size() == 3) {
1053 X86Operand &Op = *(X86Operand*)Operands.back();
1054 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1055 isa<MCConstantExpr>(Op.Mem.Disp) &&
1056 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1057 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1058 SMLoc Loc = Op.getEndLoc();
1059 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1063 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1064 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1065 Operands.size() == 3) {
1066 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1067 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1068 isa<MCConstantExpr>(Op.Mem.Disp) &&
1069 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1070 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1071 SMLoc Loc = Op.getEndLoc();
1072 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1076 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1077 if (Name.startswith("ins") && Operands.size() == 3 &&
1078 (Name == "insb" || Name == "insw" || Name == "insl")) {
1079 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1080 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1081 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1082 Operands.pop_back();
1083 Operands.pop_back();
1089 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1090 if (Name.startswith("outs") && Operands.size() == 3 &&
1091 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1092 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1093 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1094 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1095 Operands.pop_back();
1096 Operands.pop_back();
1102 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1103 if (Name.startswith("movs") && Operands.size() == 3 &&
1104 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1105 (is64BitMode() && Name == "movsq"))) {
1106 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1107 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1108 if (isSrcOp(Op) && isDstOp(Op2)) {
1109 Operands.pop_back();
1110 Operands.pop_back();
1115 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1116 if (Name.startswith("lods") && Operands.size() == 3 &&
1117 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1118 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1119 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1120 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1121 if (isSrcOp(*Op1) && Op2->isReg()) {
1123 unsigned reg = Op2->getReg();
1124 bool isLods = Name == "lods";
1125 if (reg == X86::AL && (isLods || Name == "lodsb"))
1127 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1129 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1131 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1136 Operands.pop_back();
1137 Operands.pop_back();
1141 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1145 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1146 if (Name.startswith("stos") && Operands.size() == 3 &&
1147 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1148 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1149 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1150 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1151 if (isDstOp(*Op2) && Op1->isReg()) {
1153 unsigned reg = Op1->getReg();
1154 bool isStos = Name == "stos";
1155 if (reg == X86::AL && (isStos || Name == "stosb"))
1157 else if (reg == X86::AX && (isStos || Name == "stosw"))
1159 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1161 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1166 Operands.pop_back();
1167 Operands.pop_back();
1171 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1176 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1178 if ((Name.startswith("shr") || Name.startswith("sar") ||
1179 Name.startswith("shl") || Name.startswith("sal") ||
1180 Name.startswith("rcl") || Name.startswith("rcr") ||
1181 Name.startswith("rol") || Name.startswith("ror")) &&
1182 Operands.size() == 3) {
1183 if (isParsingIntelSyntax()) {
1185 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1186 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1187 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1189 Operands.pop_back();
1192 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1193 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1194 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1196 Operands.erase(Operands.begin() + 1);
1201 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1202 // instalias with an immediate operand yet.
1203 if (Name == "int" && Operands.size() == 2) {
1204 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1205 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1206 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1208 Operands.erase(Operands.begin() + 1);
1209 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1217 processInstruction(MCInst &Inst,
1218 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1219 switch (Inst.getOpcode()) {
1220 default: return false;
1221 case X86::AND16i16: {
1222 if (!Inst.getOperand(0).isImm() ||
1223 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1227 TmpInst.setOpcode(X86::AND16ri8);
1228 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1229 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1230 TmpInst.addOperand(Inst.getOperand(0));
1234 case X86::AND32i32: {
1235 if (!Inst.getOperand(0).isImm() ||
1236 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1240 TmpInst.setOpcode(X86::AND32ri8);
1241 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1242 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1243 TmpInst.addOperand(Inst.getOperand(0));
1247 case X86::AND64i32: {
1248 if (!Inst.getOperand(0).isImm() ||
1249 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1253 TmpInst.setOpcode(X86::AND64ri8);
1254 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1255 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1256 TmpInst.addOperand(Inst.getOperand(0));
1260 case X86::XOR16i16: {
1261 if (!Inst.getOperand(0).isImm() ||
1262 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1266 TmpInst.setOpcode(X86::XOR16ri8);
1267 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1268 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1269 TmpInst.addOperand(Inst.getOperand(0));
1273 case X86::XOR32i32: {
1274 if (!Inst.getOperand(0).isImm() ||
1275 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1279 TmpInst.setOpcode(X86::XOR32ri8);
1280 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1281 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1282 TmpInst.addOperand(Inst.getOperand(0));
1286 case X86::XOR64i32: {
1287 if (!Inst.getOperand(0).isImm() ||
1288 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1292 TmpInst.setOpcode(X86::XOR64ri8);
1293 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1294 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1295 TmpInst.addOperand(Inst.getOperand(0));
1299 case X86::OR16i16: {
1300 if (!Inst.getOperand(0).isImm() ||
1301 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1305 TmpInst.setOpcode(X86::OR16ri8);
1306 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1307 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1308 TmpInst.addOperand(Inst.getOperand(0));
1312 case X86::OR32i32: {
1313 if (!Inst.getOperand(0).isImm() ||
1314 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1318 TmpInst.setOpcode(X86::OR32ri8);
1319 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1320 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1321 TmpInst.addOperand(Inst.getOperand(0));
1325 case X86::OR64i32: {
1326 if (!Inst.getOperand(0).isImm() ||
1327 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1331 TmpInst.setOpcode(X86::OR64ri8);
1332 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1333 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1334 TmpInst.addOperand(Inst.getOperand(0));
1338 case X86::CMP16i16: {
1339 if (!Inst.getOperand(0).isImm() ||
1340 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1344 TmpInst.setOpcode(X86::CMP16ri8);
1345 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1346 TmpInst.addOperand(Inst.getOperand(0));
1350 case X86::CMP32i32: {
1351 if (!Inst.getOperand(0).isImm() ||
1352 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1356 TmpInst.setOpcode(X86::CMP32ri8);
1357 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1358 TmpInst.addOperand(Inst.getOperand(0));
1362 case X86::CMP64i32: {
1363 if (!Inst.getOperand(0).isImm() ||
1364 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1368 TmpInst.setOpcode(X86::CMP64ri8);
1369 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1370 TmpInst.addOperand(Inst.getOperand(0));
1374 case X86::ADD16i16: {
1375 if (!Inst.getOperand(0).isImm() ||
1376 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1380 TmpInst.setOpcode(X86::ADD16ri8);
1381 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1382 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1383 TmpInst.addOperand(Inst.getOperand(0));
1387 case X86::ADD32i32: {
1388 if (!Inst.getOperand(0).isImm() ||
1389 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1393 TmpInst.setOpcode(X86::ADD32ri8);
1394 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1395 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1396 TmpInst.addOperand(Inst.getOperand(0));
1400 case X86::ADD64i32: {
1401 if (!Inst.getOperand(0).isImm() ||
1402 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1406 TmpInst.setOpcode(X86::ADD64ri8);
1407 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1408 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1409 TmpInst.addOperand(Inst.getOperand(0));
1413 case X86::SUB16i16: {
1414 if (!Inst.getOperand(0).isImm() ||
1415 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1419 TmpInst.setOpcode(X86::SUB16ri8);
1420 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1421 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1422 TmpInst.addOperand(Inst.getOperand(0));
1426 case X86::SUB32i32: {
1427 if (!Inst.getOperand(0).isImm() ||
1428 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1432 TmpInst.setOpcode(X86::SUB32ri8);
1433 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1434 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1435 TmpInst.addOperand(Inst.getOperand(0));
1439 case X86::SUB64i32: {
1440 if (!Inst.getOperand(0).isImm() ||
1441 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1445 TmpInst.setOpcode(X86::SUB64ri8);
1446 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1447 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1448 TmpInst.addOperand(Inst.getOperand(0));
1456 MatchAndEmitInstruction(SMLoc IDLoc,
1457 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1459 assert(!Operands.empty() && "Unexpect empty operand list!");
1460 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1461 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1463 // First, handle aliases that expand to multiple instructions.
1464 // FIXME: This should be replaced with a real .td file alias mechanism.
1465 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1467 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1468 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1469 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1470 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1472 Inst.setOpcode(X86::WAIT);
1474 Out.EmitInstruction(Inst);
1477 StringSwitch<const char*>(Op->getToken())
1478 .Case("finit", "fninit")
1479 .Case("fsave", "fnsave")
1480 .Case("fstcw", "fnstcw")
1481 .Case("fstcww", "fnstcw")
1482 .Case("fstenv", "fnstenv")
1483 .Case("fstsw", "fnstsw")
1484 .Case("fstsww", "fnstsw")
1485 .Case("fclex", "fnclex")
1487 assert(Repl && "Unknown wait-prefixed instruction");
1489 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1492 bool WasOriginallyInvalidOperand = false;
1493 unsigned OrigErrorInfo;
1496 // First, try a direct match.
1497 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo,
1498 isParsingIntelSyntax())) {
1501 // Some instructions need post-processing to, for example, tweak which
1502 // encoding is selected. Loop on it while changes happen so the
1503 // individual transformations can chain off each other.
1504 while (processInstruction(Inst, Operands))
1508 Out.EmitInstruction(Inst);
1510 case Match_MissingFeature:
1511 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1513 case Match_ConversionFail:
1514 return Error(IDLoc, "unable to convert operands to instruction");
1515 case Match_InvalidOperand:
1516 WasOriginallyInvalidOperand = true;
1518 case Match_MnemonicFail:
1522 // FIXME: Ideally, we would only attempt suffix matches for things which are
1523 // valid prefixes, and we could just infer the right unambiguous
1524 // type. However, that requires substantially more matcher support than the
1527 // Change the operand to point to a temporary token.
1528 StringRef Base = Op->getToken();
1529 SmallString<16> Tmp;
1532 Op->setTokenValue(Tmp.str());
1534 // If this instruction starts with an 'f', then it is a floating point stack
1535 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1536 // 80-bit floating point, which use the suffixes s,l,t respectively.
1538 // Otherwise, we assume that this may be an integer instruction, which comes
1539 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1540 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1542 // Check for the various suffix matches.
1543 Tmp[Base.size()] = Suffixes[0];
1544 unsigned ErrorInfoIgnore;
1545 unsigned Match1, Match2, Match3, Match4;
1547 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1548 Tmp[Base.size()] = Suffixes[1];
1549 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1550 Tmp[Base.size()] = Suffixes[2];
1551 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1552 Tmp[Base.size()] = Suffixes[3];
1553 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1555 // Restore the old token.
1556 Op->setTokenValue(Base);
1558 // If exactly one matched, then we treat that as a successful match (and the
1559 // instruction will already have been filled in correctly, since the failing
1560 // matches won't have modified it).
1561 unsigned NumSuccessfulMatches =
1562 (Match1 == Match_Success) + (Match2 == Match_Success) +
1563 (Match3 == Match_Success) + (Match4 == Match_Success);
1564 if (NumSuccessfulMatches == 1) {
1566 Out.EmitInstruction(Inst);
1570 // Otherwise, the match failed, try to produce a decent error message.
1572 // If we had multiple suffix matches, then identify this as an ambiguous
1574 if (NumSuccessfulMatches > 1) {
1576 unsigned NumMatches = 0;
1577 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1578 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1579 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1580 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1582 SmallString<126> Msg;
1583 raw_svector_ostream OS(Msg);
1584 OS << "ambiguous instructions require an explicit suffix (could be ";
1585 for (unsigned i = 0; i != NumMatches; ++i) {
1588 if (i + 1 == NumMatches)
1590 OS << "'" << Base << MatchChars[i] << "'";
1593 Error(IDLoc, OS.str());
1597 // Okay, we know that none of the variants matched successfully.
1599 // If all of the instructions reported an invalid mnemonic, then the original
1600 // mnemonic was invalid.
1601 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1602 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1603 if (!WasOriginallyInvalidOperand) {
1604 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1608 // Recover location info for the operand if we know which was the problem.
1609 if (OrigErrorInfo != ~0U) {
1610 if (OrigErrorInfo >= Operands.size())
1611 return Error(IDLoc, "too few operands for instruction");
1613 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1614 if (Operand->getStartLoc().isValid()) {
1615 SMRange OperandRange = Operand->getLocRange();
1616 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1621 return Error(IDLoc, "invalid operand for instruction");
1624 // If one instruction matched with a missing feature, report this as a
1626 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1627 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1628 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1632 // If one instruction matched with an invalid operand, report this as an
1634 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1635 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1636 Error(IDLoc, "invalid operand for instruction");
1640 // If all of these were an outright failure, report it in a useless way.
1641 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1646 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1647 StringRef IDVal = DirectiveID.getIdentifier();
1648 if (IDVal == ".word")
1649 return ParseDirectiveWord(2, DirectiveID.getLoc());
1650 else if (IDVal.startswith(".code"))
1651 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1652 else if (IDVal.startswith(".intel_syntax")) {
1653 getParser().setAssemblerDialect(1);
1654 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1655 if(Parser.getTok().getString() == "noprefix") {
1656 // FIXME : Handle noprefix
1666 /// ParseDirectiveWord
1667 /// ::= .word [ expression (, expression)* ]
1668 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1669 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1671 const MCExpr *Value;
1672 if (getParser().ParseExpression(Value))
1675 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1677 if (getLexer().is(AsmToken::EndOfStatement))
1680 // FIXME: Improve diagnostic.
1681 if (getLexer().isNot(AsmToken::Comma))
1682 return Error(L, "unexpected token in directive");
1691 /// ParseDirectiveCode
1692 /// ::= .code32 | .code64
1693 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1694 if (IDVal == ".code32") {
1696 if (is64BitMode()) {
1698 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1700 } else if (IDVal == ".code64") {
1702 if (!is64BitMode()) {
1704 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1707 return Error(L, "unexpected directive " + IDVal);
1714 extern "C" void LLVMInitializeX86AsmLexer();
1716 // Force static initialization.
1717 extern "C" void LLVMInitializeX86AsmParser() {
1718 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1719 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1720 LLVMInitializeX86AsmLexer();
1723 #define GET_REGISTER_MATCHER
1724 #define GET_MATCHER_IMPLEMENTATION
1725 #include "X86GenAsmMatcher.inc"