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))
882 // Validate the scale amount.
883 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
884 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
887 Scale = (unsigned)ScaleVal;
890 } else if (getLexer().isNot(AsmToken::RParen)) {
891 // A scale amount without an index is ignored.
893 SMLoc Loc = Parser.getTok().getLoc();
896 if (getParser().ParseAbsoluteExpression(Value))
900 Warning(Loc, "scale factor without index register is ignored");
905 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
906 if (getLexer().isNot(AsmToken::RParen)) {
907 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
910 SMLoc MemEnd = Parser.getTok().getLoc();
911 Parser.Lex(); // Eat the ')'.
913 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
918 ParseInstruction(StringRef Name, SMLoc NameLoc,
919 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
920 StringRef PatchedName = Name;
922 // FIXME: Hack to recognize setneb as setne.
923 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
924 PatchedName != "setb" && PatchedName != "setnb")
925 PatchedName = PatchedName.substr(0, Name.size()-1);
927 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
928 const MCExpr *ExtraImmOp = 0;
929 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
930 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
931 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
932 bool IsVCMP = PatchedName.startswith("vcmp");
933 unsigned SSECCIdx = IsVCMP ? 4 : 3;
934 unsigned SSEComparisonCode = StringSwitch<unsigned>(
935 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
948 .Case("neq_oq", 0x0C)
955 .Case("unord_s", 0x13)
956 .Case("neq_us", 0x14)
957 .Case("nlt_uq", 0x15)
958 .Case("nle_uq", 0x16)
961 .Case("nge_uq", 0x19)
962 .Case("ngt_uq", 0x1A)
963 .Case("false_os", 0x1B)
964 .Case("neq_os", 0x1C)
967 .Case("true_us", 0x1F)
969 if (SSEComparisonCode != ~0U) {
970 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
971 getParser().getContext());
972 if (PatchedName.endswith("ss")) {
973 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
974 } else if (PatchedName.endswith("sd")) {
975 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
976 } else if (PatchedName.endswith("ps")) {
977 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
979 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
980 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
985 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
987 if (ExtraImmOp && !isParsingIntelSyntax())
988 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
990 // Determine whether this is an instruction prefix.
992 Name == "lock" || Name == "rep" ||
993 Name == "repe" || Name == "repz" ||
994 Name == "repne" || Name == "repnz" ||
995 Name == "rex64" || Name == "data16";
998 // This does the actual operand parsing. Don't parse any more if we have a
999 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1000 // just want to parse the "lock" as the first instruction and the "incl" as
1002 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1004 // Parse '*' modifier.
1005 if (getLexer().is(AsmToken::Star)) {
1006 SMLoc Loc = Parser.getTok().getLoc();
1007 Operands.push_back(X86Operand::CreateToken("*", Loc));
1008 Parser.Lex(); // Eat the star.
1011 // Read the first operand.
1012 if (X86Operand *Op = ParseOperand())
1013 Operands.push_back(Op);
1015 Parser.EatToEndOfStatement();
1019 while (getLexer().is(AsmToken::Comma)) {
1020 Parser.Lex(); // Eat the comma.
1022 // Parse and remember the operand.
1023 if (X86Operand *Op = ParseOperand())
1024 Operands.push_back(Op);
1026 Parser.EatToEndOfStatement();
1031 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1032 SMLoc Loc = getLexer().getLoc();
1033 Parser.EatToEndOfStatement();
1034 return Error(Loc, "unexpected token in argument list");
1038 if (getLexer().is(AsmToken::EndOfStatement))
1039 Parser.Lex(); // Consume the EndOfStatement
1040 else if (isPrefix && getLexer().is(AsmToken::Slash))
1041 Parser.Lex(); // Consume the prefix separator Slash
1043 if (ExtraImmOp && isParsingIntelSyntax())
1044 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1046 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1047 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1048 // documented form in various unofficial manuals, so a lot of code uses it.
1049 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1050 Operands.size() == 3) {
1051 X86Operand &Op = *(X86Operand*)Operands.back();
1052 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1053 isa<MCConstantExpr>(Op.Mem.Disp) &&
1054 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1055 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1056 SMLoc Loc = Op.getEndLoc();
1057 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1061 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1062 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1063 Operands.size() == 3) {
1064 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1065 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1066 isa<MCConstantExpr>(Op.Mem.Disp) &&
1067 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1068 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1069 SMLoc Loc = Op.getEndLoc();
1070 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1074 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1075 if (Name.startswith("ins") && Operands.size() == 3 &&
1076 (Name == "insb" || Name == "insw" || Name == "insl")) {
1077 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1078 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1079 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1080 Operands.pop_back();
1081 Operands.pop_back();
1087 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1088 if (Name.startswith("outs") && Operands.size() == 3 &&
1089 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1090 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1091 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1092 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1093 Operands.pop_back();
1094 Operands.pop_back();
1100 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1101 if (Name.startswith("movs") && Operands.size() == 3 &&
1102 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1103 (is64BitMode() && Name == "movsq"))) {
1104 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1105 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1106 if (isSrcOp(Op) && isDstOp(Op2)) {
1107 Operands.pop_back();
1108 Operands.pop_back();
1113 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1114 if (Name.startswith("lods") && Operands.size() == 3 &&
1115 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1116 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1117 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1118 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1119 if (isSrcOp(*Op1) && Op2->isReg()) {
1121 unsigned reg = Op2->getReg();
1122 bool isLods = Name == "lods";
1123 if (reg == X86::AL && (isLods || Name == "lodsb"))
1125 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1127 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1129 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1134 Operands.pop_back();
1135 Operands.pop_back();
1139 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1143 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1144 if (Name.startswith("stos") && Operands.size() == 3 &&
1145 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1146 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1147 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1148 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1149 if (isDstOp(*Op2) && Op1->isReg()) {
1151 unsigned reg = Op1->getReg();
1152 bool isStos = Name == "stos";
1153 if (reg == X86::AL && (isStos || Name == "stosb"))
1155 else if (reg == X86::AX && (isStos || Name == "stosw"))
1157 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1159 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1164 Operands.pop_back();
1165 Operands.pop_back();
1169 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1174 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1176 if ((Name.startswith("shr") || Name.startswith("sar") ||
1177 Name.startswith("shl") || Name.startswith("sal") ||
1178 Name.startswith("rcl") || Name.startswith("rcr") ||
1179 Name.startswith("rol") || Name.startswith("ror")) &&
1180 Operands.size() == 3) {
1181 if (isParsingIntelSyntax()) {
1183 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1184 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1185 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1187 Operands.pop_back();
1190 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1191 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1192 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1194 Operands.erase(Operands.begin() + 1);
1199 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1200 // instalias with an immediate operand yet.
1201 if (Name == "int" && Operands.size() == 2) {
1202 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1203 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1204 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1206 Operands.erase(Operands.begin() + 1);
1207 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1215 processInstruction(MCInst &Inst,
1216 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1217 switch (Inst.getOpcode()) {
1218 default: return false;
1219 case X86::AND16i16: {
1220 if (!Inst.getOperand(0).isImm() ||
1221 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1225 TmpInst.setOpcode(X86::AND16ri8);
1226 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1227 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1228 TmpInst.addOperand(Inst.getOperand(0));
1232 case X86::AND32i32: {
1233 if (!Inst.getOperand(0).isImm() ||
1234 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1238 TmpInst.setOpcode(X86::AND32ri8);
1239 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1240 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1241 TmpInst.addOperand(Inst.getOperand(0));
1245 case X86::AND64i32: {
1246 if (!Inst.getOperand(0).isImm() ||
1247 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1251 TmpInst.setOpcode(X86::AND64ri8);
1252 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1253 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1254 TmpInst.addOperand(Inst.getOperand(0));
1258 case X86::XOR16i16: {
1259 if (!Inst.getOperand(0).isImm() ||
1260 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1264 TmpInst.setOpcode(X86::XOR16ri8);
1265 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1266 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1267 TmpInst.addOperand(Inst.getOperand(0));
1271 case X86::XOR32i32: {
1272 if (!Inst.getOperand(0).isImm() ||
1273 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1277 TmpInst.setOpcode(X86::XOR32ri8);
1278 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1279 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1280 TmpInst.addOperand(Inst.getOperand(0));
1284 case X86::XOR64i32: {
1285 if (!Inst.getOperand(0).isImm() ||
1286 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1290 TmpInst.setOpcode(X86::XOR64ri8);
1291 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1292 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1293 TmpInst.addOperand(Inst.getOperand(0));
1297 case X86::OR16i16: {
1298 if (!Inst.getOperand(0).isImm() ||
1299 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1303 TmpInst.setOpcode(X86::OR16ri8);
1304 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1305 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1306 TmpInst.addOperand(Inst.getOperand(0));
1310 case X86::OR32i32: {
1311 if (!Inst.getOperand(0).isImm() ||
1312 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1316 TmpInst.setOpcode(X86::OR32ri8);
1317 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1318 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1319 TmpInst.addOperand(Inst.getOperand(0));
1323 case X86::OR64i32: {
1324 if (!Inst.getOperand(0).isImm() ||
1325 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1329 TmpInst.setOpcode(X86::OR64ri8);
1330 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1331 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1332 TmpInst.addOperand(Inst.getOperand(0));
1336 case X86::CMP16i16: {
1337 if (!Inst.getOperand(0).isImm() ||
1338 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1342 TmpInst.setOpcode(X86::CMP16ri8);
1343 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1344 TmpInst.addOperand(Inst.getOperand(0));
1348 case X86::CMP32i32: {
1349 if (!Inst.getOperand(0).isImm() ||
1350 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1354 TmpInst.setOpcode(X86::CMP32ri8);
1355 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1356 TmpInst.addOperand(Inst.getOperand(0));
1360 case X86::CMP64i32: {
1361 if (!Inst.getOperand(0).isImm() ||
1362 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1366 TmpInst.setOpcode(X86::CMP64ri8);
1367 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1368 TmpInst.addOperand(Inst.getOperand(0));
1372 case X86::ADD16i16: {
1373 if (!Inst.getOperand(0).isImm() ||
1374 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1378 TmpInst.setOpcode(X86::ADD16ri8);
1379 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1380 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1381 TmpInst.addOperand(Inst.getOperand(0));
1385 case X86::ADD32i32: {
1386 if (!Inst.getOperand(0).isImm() ||
1387 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1391 TmpInst.setOpcode(X86::ADD32ri8);
1392 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1393 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1394 TmpInst.addOperand(Inst.getOperand(0));
1398 case X86::ADD64i32: {
1399 if (!Inst.getOperand(0).isImm() ||
1400 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1404 TmpInst.setOpcode(X86::ADD64ri8);
1405 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1406 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1407 TmpInst.addOperand(Inst.getOperand(0));
1411 case X86::SUB16i16: {
1412 if (!Inst.getOperand(0).isImm() ||
1413 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1417 TmpInst.setOpcode(X86::SUB16ri8);
1418 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1419 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1420 TmpInst.addOperand(Inst.getOperand(0));
1424 case X86::SUB32i32: {
1425 if (!Inst.getOperand(0).isImm() ||
1426 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1430 TmpInst.setOpcode(X86::SUB32ri8);
1431 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1432 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1433 TmpInst.addOperand(Inst.getOperand(0));
1437 case X86::SUB64i32: {
1438 if (!Inst.getOperand(0).isImm() ||
1439 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1443 TmpInst.setOpcode(X86::SUB64ri8);
1444 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1445 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1446 TmpInst.addOperand(Inst.getOperand(0));
1454 MatchAndEmitInstruction(SMLoc IDLoc,
1455 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1457 assert(!Operands.empty() && "Unexpect empty operand list!");
1458 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1459 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1461 // First, handle aliases that expand to multiple instructions.
1462 // FIXME: This should be replaced with a real .td file alias mechanism.
1463 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1465 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1466 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1467 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1468 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1470 Inst.setOpcode(X86::WAIT);
1472 Out.EmitInstruction(Inst);
1475 StringSwitch<const char*>(Op->getToken())
1476 .Case("finit", "fninit")
1477 .Case("fsave", "fnsave")
1478 .Case("fstcw", "fnstcw")
1479 .Case("fstcww", "fnstcw")
1480 .Case("fstenv", "fnstenv")
1481 .Case("fstsw", "fnstsw")
1482 .Case("fstsww", "fnstsw")
1483 .Case("fclex", "fnclex")
1485 assert(Repl && "Unknown wait-prefixed instruction");
1487 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1490 bool WasOriginallyInvalidOperand = false;
1491 unsigned OrigErrorInfo;
1494 // First, try a direct match.
1495 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo,
1496 isParsingIntelSyntax())) {
1499 // Some instructions need post-processing to, for example, tweak which
1500 // encoding is selected. Loop on it while changes happen so the
1501 // individual transformations can chain off each other.
1502 while (processInstruction(Inst, Operands))
1506 Out.EmitInstruction(Inst);
1508 case Match_MissingFeature:
1509 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1511 case Match_ConversionFail:
1512 return Error(IDLoc, "unable to convert operands to instruction");
1513 case Match_InvalidOperand:
1514 WasOriginallyInvalidOperand = true;
1516 case Match_MnemonicFail:
1520 // FIXME: Ideally, we would only attempt suffix matches for things which are
1521 // valid prefixes, and we could just infer the right unambiguous
1522 // type. However, that requires substantially more matcher support than the
1525 // Change the operand to point to a temporary token.
1526 StringRef Base = Op->getToken();
1527 SmallString<16> Tmp;
1530 Op->setTokenValue(Tmp.str());
1532 // If this instruction starts with an 'f', then it is a floating point stack
1533 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1534 // 80-bit floating point, which use the suffixes s,l,t respectively.
1536 // Otherwise, we assume that this may be an integer instruction, which comes
1537 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1538 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1540 // Check for the various suffix matches.
1541 Tmp[Base.size()] = Suffixes[0];
1542 unsigned ErrorInfoIgnore;
1543 unsigned Match1, Match2, Match3, Match4;
1545 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1546 Tmp[Base.size()] = Suffixes[1];
1547 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1548 Tmp[Base.size()] = Suffixes[2];
1549 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1550 Tmp[Base.size()] = Suffixes[3];
1551 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1553 // Restore the old token.
1554 Op->setTokenValue(Base);
1556 // If exactly one matched, then we treat that as a successful match (and the
1557 // instruction will already have been filled in correctly, since the failing
1558 // matches won't have modified it).
1559 unsigned NumSuccessfulMatches =
1560 (Match1 == Match_Success) + (Match2 == Match_Success) +
1561 (Match3 == Match_Success) + (Match4 == Match_Success);
1562 if (NumSuccessfulMatches == 1) {
1564 Out.EmitInstruction(Inst);
1568 // Otherwise, the match failed, try to produce a decent error message.
1570 // If we had multiple suffix matches, then identify this as an ambiguous
1572 if (NumSuccessfulMatches > 1) {
1574 unsigned NumMatches = 0;
1575 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1576 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1577 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1578 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1580 SmallString<126> Msg;
1581 raw_svector_ostream OS(Msg);
1582 OS << "ambiguous instructions require an explicit suffix (could be ";
1583 for (unsigned i = 0; i != NumMatches; ++i) {
1586 if (i + 1 == NumMatches)
1588 OS << "'" << Base << MatchChars[i] << "'";
1591 Error(IDLoc, OS.str());
1595 // Okay, we know that none of the variants matched successfully.
1597 // If all of the instructions reported an invalid mnemonic, then the original
1598 // mnemonic was invalid.
1599 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1600 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1601 if (!WasOriginallyInvalidOperand) {
1602 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1606 // Recover location info for the operand if we know which was the problem.
1607 if (OrigErrorInfo != ~0U) {
1608 if (OrigErrorInfo >= Operands.size())
1609 return Error(IDLoc, "too few operands for instruction");
1611 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1612 if (Operand->getStartLoc().isValid()) {
1613 SMRange OperandRange = Operand->getLocRange();
1614 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1619 return Error(IDLoc, "invalid operand for instruction");
1622 // If one instruction matched with a missing feature, report this as a
1624 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1625 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1626 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1630 // If one instruction matched with an invalid operand, report this as an
1632 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1633 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1634 Error(IDLoc, "invalid operand for instruction");
1638 // If all of these were an outright failure, report it in a useless way.
1639 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1644 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1645 StringRef IDVal = DirectiveID.getIdentifier();
1646 if (IDVal == ".word")
1647 return ParseDirectiveWord(2, DirectiveID.getLoc());
1648 else if (IDVal.startswith(".code"))
1649 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1650 else if (IDVal.startswith(".intel_syntax")) {
1651 getParser().setAssemblerDialect(1);
1652 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1653 if(Parser.getTok().getString() == "noprefix") {
1654 // FIXME : Handle noprefix
1664 /// ParseDirectiveWord
1665 /// ::= .word [ expression (, expression)* ]
1666 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1667 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1669 const MCExpr *Value;
1670 if (getParser().ParseExpression(Value))
1673 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1675 if (getLexer().is(AsmToken::EndOfStatement))
1678 // FIXME: Improve diagnostic.
1679 if (getLexer().isNot(AsmToken::Comma))
1680 return Error(L, "unexpected token in directive");
1689 /// ParseDirectiveCode
1690 /// ::= .code32 | .code64
1691 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1692 if (IDVal == ".code32") {
1694 if (is64BitMode()) {
1696 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1698 } else if (IDVal == ".code64") {
1700 if (!is64BitMode()) {
1702 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1705 return Error(L, "unexpected directive " + IDVal);
1712 extern "C" void LLVMInitializeX86AsmLexer();
1714 // Force static initialization.
1715 extern "C" void LLVMInitializeX86AsmParser() {
1716 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1717 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1718 LLVMInitializeX86AsmLexer();
1721 #define GET_REGISTER_MATCHER
1722 #define GET_MATCHER_IMPLEMENTATION
1723 #include "X86GenAsmMatcher.inc"