1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Support/raw_ostream.h"
33 class X86AsmParser : public MCTargetAsmParser {
37 MCAsmParser &getParser() const { return Parser; }
39 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
41 bool Error(SMLoc L, const Twine &Msg,
42 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) {
43 return Parser.Error(L, Msg, Ranges);
46 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
51 X86Operand *ParseOperand();
52 X86Operand *ParseATTOperand();
53 X86Operand *ParseIntelOperand();
54 X86Operand *ParseIntelMemOperand();
55 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
56 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
58 bool ParseDirectiveWord(unsigned Size, SMLoc L);
59 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
61 bool processInstruction(MCInst &Inst,
62 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
64 bool MatchAndEmitInstruction(SMLoc IDLoc,
65 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
68 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
69 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
70 bool isSrcOp(X86Operand &Op);
72 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
73 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
74 bool isDstOp(X86Operand &Op);
76 bool is64BitMode() const {
77 // FIXME: Can tablegen auto-generate this?
78 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
81 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
82 setAvailableFeatures(FB);
85 /// @name Auto-generated Matcher Functions
88 #define GET_ASSEMBLER_HEADER
89 #include "X86GenAsmMatcher.inc"
94 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
95 : MCTargetAsmParser(), STI(sti), Parser(parser) {
97 // Initialize the set of available features.
98 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
100 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
102 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
103 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
105 virtual bool ParseDirective(AsmToken DirectiveID);
107 bool isParsingIntelSyntax() {
108 return getParser().getAssemblerDialect();
111 } // end anonymous namespace
113 /// @name Auto-generated Match Functions
116 static unsigned MatchRegisterName(StringRef Name);
120 static bool isImmSExti16i8Value(uint64_t Value) {
121 return (( Value <= 0x000000000000007FULL)||
122 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
123 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
126 static bool isImmSExti32i8Value(uint64_t Value) {
127 return (( Value <= 0x000000000000007FULL)||
128 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
129 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
132 static bool isImmZExtu32u8Value(uint64_t Value) {
133 return (Value <= 0x00000000000000FFULL);
136 static bool isImmSExti64i8Value(uint64_t Value) {
137 return (( Value <= 0x000000000000007FULL)||
138 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
141 static bool isImmSExti64i32Value(uint64_t Value) {
142 return (( Value <= 0x000000007FFFFFFFULL)||
143 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
147 /// X86Operand - Instances of this class represent a parsed X86 machine
149 struct X86Operand : public MCParsedAsmOperand {
157 SMLoc StartLoc, EndLoc;
183 X86Operand(KindTy K, SMLoc Start, SMLoc End)
184 : Kind(K), StartLoc(Start), EndLoc(End) {}
186 /// getStartLoc - Get the location of the first token of this operand.
187 SMLoc getStartLoc() const { return StartLoc; }
188 /// getEndLoc - Get the location of the last token of this operand.
189 SMLoc getEndLoc() const { return EndLoc; }
191 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
193 virtual void print(raw_ostream &OS) const {}
195 StringRef getToken() const {
196 assert(Kind == Token && "Invalid access!");
197 return StringRef(Tok.Data, Tok.Length);
199 void setTokenValue(StringRef Value) {
200 assert(Kind == Token && "Invalid access!");
201 Tok.Data = Value.data();
202 Tok.Length = Value.size();
205 unsigned getReg() const {
206 assert(Kind == Register && "Invalid access!");
210 const MCExpr *getImm() const {
211 assert(Kind == Immediate && "Invalid access!");
215 const MCExpr *getMemDisp() const {
216 assert(Kind == Memory && "Invalid access!");
219 unsigned getMemSegReg() const {
220 assert(Kind == Memory && "Invalid access!");
223 unsigned getMemBaseReg() const {
224 assert(Kind == Memory && "Invalid access!");
227 unsigned getMemIndexReg() const {
228 assert(Kind == Memory && "Invalid access!");
231 unsigned getMemScale() const {
232 assert(Kind == Memory && "Invalid access!");
236 bool isToken() const {return Kind == Token; }
238 bool isImm() const { return Kind == Immediate; }
240 bool isImmSExti16i8() const {
244 // If this isn't a constant expr, just assume it fits and let relaxation
246 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
250 // Otherwise, check the value is in a range that makes sense for this
252 return isImmSExti16i8Value(CE->getValue());
254 bool isImmSExti32i8() const {
258 // If this isn't a constant expr, just assume it fits and let relaxation
260 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
264 // Otherwise, check the value is in a range that makes sense for this
266 return isImmSExti32i8Value(CE->getValue());
268 bool isImmZExtu32u8() const {
272 // If this isn't a constant expr, just assume it fits and let relaxation
274 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
278 // Otherwise, check the value is in a range that makes sense for this
280 return isImmZExtu32u8Value(CE->getValue());
282 bool isImmSExti64i8() const {
286 // If this isn't a constant expr, just assume it fits and let relaxation
288 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
292 // Otherwise, check the value is in a range that makes sense for this
294 return isImmSExti64i8Value(CE->getValue());
296 bool isImmSExti64i32() const {
300 // If this isn't a constant expr, just assume it fits and let relaxation
302 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
306 // Otherwise, check the value is in a range that makes sense for this
308 return isImmSExti64i32Value(CE->getValue());
311 bool isMem() const { return Kind == Memory; }
312 bool isMem8() const {
313 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
315 bool isMem16() const {
316 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
318 bool isMem32() const {
319 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
321 bool isMem64() const {
322 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
324 bool isMem80() const {
325 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
327 bool isMem128() const {
328 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
330 bool isMem256() const {
331 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
334 bool isMemVX32() const {
335 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
336 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
338 bool isMemVY32() const {
339 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
340 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
342 bool isMemVX64() const {
343 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
344 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
346 bool isMemVY64() const {
347 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
348 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
351 bool isAbsMem() const {
352 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
353 !getMemIndexReg() && getMemScale() == 1;
356 bool isReg() const { return Kind == Register; }
358 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
359 // Add as immediates when possible.
360 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
361 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
363 Inst.addOperand(MCOperand::CreateExpr(Expr));
366 void addRegOperands(MCInst &Inst, unsigned N) const {
367 assert(N == 1 && "Invalid number of operands!");
368 Inst.addOperand(MCOperand::CreateReg(getReg()));
371 void addImmOperands(MCInst &Inst, unsigned N) const {
372 assert(N == 1 && "Invalid number of operands!");
373 addExpr(Inst, getImm());
376 void addMem8Operands(MCInst &Inst, unsigned N) const {
377 addMemOperands(Inst, N);
379 void addMem16Operands(MCInst &Inst, unsigned N) const {
380 addMemOperands(Inst, N);
382 void addMem32Operands(MCInst &Inst, unsigned N) const {
383 addMemOperands(Inst, N);
385 void addMem64Operands(MCInst &Inst, unsigned N) const {
386 addMemOperands(Inst, N);
388 void addMem80Operands(MCInst &Inst, unsigned N) const {
389 addMemOperands(Inst, N);
391 void addMem128Operands(MCInst &Inst, unsigned N) const {
392 addMemOperands(Inst, N);
394 void addMem256Operands(MCInst &Inst, unsigned N) const {
395 addMemOperands(Inst, N);
397 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
398 addMemOperands(Inst, N);
400 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
401 addMemOperands(Inst, N);
403 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
404 addMemOperands(Inst, N);
406 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
407 addMemOperands(Inst, N);
410 void addMemOperands(MCInst &Inst, unsigned N) const {
411 assert((N == 5) && "Invalid number of operands!");
412 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
413 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
414 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
415 addExpr(Inst, getMemDisp());
416 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
419 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
420 assert((N == 1) && "Invalid number of operands!");
421 // Add as immediates when possible.
422 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
423 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
425 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
428 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
429 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
430 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
431 Res->Tok.Data = Str.data();
432 Res->Tok.Length = Str.size();
436 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
437 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
438 Res->Reg.RegNo = RegNo;
442 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
443 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
448 /// Create an absolute memory operand.
449 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
450 SMLoc EndLoc, unsigned Size = 0) {
451 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
453 Res->Mem.Disp = Disp;
454 Res->Mem.BaseReg = 0;
455 Res->Mem.IndexReg = 0;
457 Res->Mem.Size = Size;
461 /// Create a generalized memory operand.
462 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
463 unsigned BaseReg, unsigned IndexReg,
464 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
466 // We should never just have a displacement, that should be parsed as an
467 // absolute memory operand.
468 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
470 // The scale should always be one of {1,2,4,8}.
471 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
473 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
474 Res->Mem.SegReg = SegReg;
475 Res->Mem.Disp = Disp;
476 Res->Mem.BaseReg = BaseReg;
477 Res->Mem.IndexReg = IndexReg;
478 Res->Mem.Scale = Scale;
479 Res->Mem.Size = Size;
484 } // end anonymous namespace.
486 bool X86AsmParser::isSrcOp(X86Operand &Op) {
487 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
489 return (Op.isMem() &&
490 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
491 isa<MCConstantExpr>(Op.Mem.Disp) &&
492 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
493 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
496 bool X86AsmParser::isDstOp(X86Operand &Op) {
497 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
500 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
501 isa<MCConstantExpr>(Op.Mem.Disp) &&
502 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
503 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
506 bool X86AsmParser::ParseRegister(unsigned &RegNo,
507 SMLoc &StartLoc, SMLoc &EndLoc) {
509 if (!isParsingIntelSyntax()) {
510 const AsmToken &TokPercent = Parser.getTok();
511 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
512 StartLoc = TokPercent.getLoc();
513 Parser.Lex(); // Eat percent token.
516 const AsmToken &Tok = Parser.getTok();
517 if (Tok.isNot(AsmToken::Identifier)) {
518 if (isParsingIntelSyntax()) return true;
519 return Error(StartLoc, "invalid register name",
520 SMRange(StartLoc, Tok.getEndLoc()));
523 RegNo = MatchRegisterName(Tok.getString());
525 // If the match failed, try the register name as lowercase.
527 RegNo = MatchRegisterName(Tok.getString().lower());
529 if (!is64BitMode()) {
530 // FIXME: This should be done using Requires<In32BitMode> and
531 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
533 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
535 if (RegNo == X86::RIZ ||
536 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
537 X86II::isX86_64NonExtLowByteReg(RegNo) ||
538 X86II::isX86_64ExtendedReg(RegNo))
539 return Error(StartLoc, "register %"
540 + Tok.getString() + " is only available in 64-bit mode",
541 SMRange(StartLoc, Tok.getEndLoc()));
544 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
545 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
547 EndLoc = Tok.getLoc();
548 Parser.Lex(); // Eat 'st'
550 // Check to see if we have '(4)' after %st.
551 if (getLexer().isNot(AsmToken::LParen))
556 const AsmToken &IntTok = Parser.getTok();
557 if (IntTok.isNot(AsmToken::Integer))
558 return Error(IntTok.getLoc(), "expected stack index");
559 switch (IntTok.getIntVal()) {
560 case 0: RegNo = X86::ST0; break;
561 case 1: RegNo = X86::ST1; break;
562 case 2: RegNo = X86::ST2; break;
563 case 3: RegNo = X86::ST3; break;
564 case 4: RegNo = X86::ST4; break;
565 case 5: RegNo = X86::ST5; break;
566 case 6: RegNo = X86::ST6; break;
567 case 7: RegNo = X86::ST7; break;
568 default: return Error(IntTok.getLoc(), "invalid stack index");
571 if (getParser().Lex().isNot(AsmToken::RParen))
572 return Error(Parser.getTok().getLoc(), "expected ')'");
574 EndLoc = Tok.getLoc();
575 Parser.Lex(); // Eat ')'
579 // If this is "db[0-7]", match it as an alias
581 if (RegNo == 0 && Tok.getString().size() == 3 &&
582 Tok.getString().startswith("db")) {
583 switch (Tok.getString()[2]) {
584 case '0': RegNo = X86::DR0; break;
585 case '1': RegNo = X86::DR1; break;
586 case '2': RegNo = X86::DR2; break;
587 case '3': RegNo = X86::DR3; break;
588 case '4': RegNo = X86::DR4; break;
589 case '5': RegNo = X86::DR5; break;
590 case '6': RegNo = X86::DR6; break;
591 case '7': RegNo = X86::DR7; break;
595 EndLoc = Tok.getLoc();
596 Parser.Lex(); // Eat it.
602 if (isParsingIntelSyntax()) return true;
603 return Error(StartLoc, "invalid register name",
604 SMRange(StartLoc, Tok.getEndLoc()));
607 EndLoc = Tok.getEndLoc();
608 Parser.Lex(); // Eat identifier token.
612 X86Operand *X86AsmParser::ParseOperand() {
613 if (isParsingIntelSyntax())
614 return ParseIntelOperand();
615 return ParseATTOperand();
618 /// getIntelMemOperandSize - Return intel memory operand size.
619 static unsigned getIntelMemOperandSize(StringRef OpStr) {
621 if (OpStr == "BYTE") Size = 8;
622 if (OpStr == "WORD") Size = 16;
623 if (OpStr == "DWORD") Size = 32;
624 if (OpStr == "QWORD") Size = 64;
625 if (OpStr == "XWORD") Size = 80;
626 if (OpStr == "XMMWORD") Size = 128;
627 if (OpStr == "YMMWORD") Size = 256;
631 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
633 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
634 SMLoc Start = Parser.getTok().getLoc(), End;
636 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
637 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
640 if (getLexer().isNot(AsmToken::LBrac))
641 return ErrorOperand(Start, "Expected '[' token!");
644 if (getLexer().is(AsmToken::Identifier)) {
646 if (ParseRegister(BaseReg, Start, End)) {
647 // Handle '[' 'symbol' ']'
648 if (getParser().ParseExpression(Disp, End)) return 0;
649 if (getLexer().isNot(AsmToken::RBrac))
650 return ErrorOperand(Start, "Expected ']' token!");
652 return X86Operand::CreateMem(Disp, Start, End, Size);
654 } else if (getLexer().is(AsmToken::Integer)) {
655 int64_t Val = Parser.getTok().getIntVal();
657 SMLoc Loc = Parser.getTok().getLoc();
658 if (getLexer().is(AsmToken::RBrac)) {
659 // Handle '[' number ']'
661 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
663 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
665 return X86Operand::CreateMem(Disp, Start, End, Size);
666 } else if (getLexer().is(AsmToken::Star)) {
667 // Handle '[' Scale*IndexReg ']'
669 SMLoc IdxRegLoc = Parser.getTok().getLoc();
670 if (ParseRegister(IndexReg, IdxRegLoc, End))
671 return ErrorOperand(IdxRegLoc, "Expected register");
674 return ErrorOperand(Loc, "Unexpected token");
677 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
678 bool isPlus = getLexer().is(AsmToken::Plus);
680 SMLoc PlusLoc = Parser.getTok().getLoc();
681 if (getLexer().is(AsmToken::Integer)) {
682 int64_t Val = Parser.getTok().getIntVal();
684 if (getLexer().is(AsmToken::Star)) {
686 SMLoc IdxRegLoc = Parser.getTok().getLoc();
687 if (ParseRegister(IndexReg, IdxRegLoc, End))
688 return ErrorOperand(IdxRegLoc, "Expected register");
690 } else if (getLexer().is(AsmToken::RBrac)) {
691 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
692 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
694 return ErrorOperand(PlusLoc, "unexpected token after +");
695 } else if (getLexer().is(AsmToken::Identifier)) {
696 // This could be an index register or a displacement expression.
697 End = Parser.getTok().getLoc();
699 ParseRegister(IndexReg, Start, End);
700 else if (getParser().ParseExpression(Disp, End)) return 0;
704 if (getLexer().isNot(AsmToken::RBrac))
705 if (getParser().ParseExpression(Disp, End)) return 0;
707 End = Parser.getTok().getLoc();
708 if (getLexer().isNot(AsmToken::RBrac))
709 return ErrorOperand(End, "expected ']' token!");
711 End = Parser.getTok().getLoc();
714 if (!BaseReg && !IndexReg)
715 return X86Operand::CreateMem(Disp, Start, End, Size);
717 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
721 /// ParseIntelMemOperand - Parse intel style memory operand.
722 X86Operand *X86AsmParser::ParseIntelMemOperand() {
723 const AsmToken &Tok = Parser.getTok();
724 SMLoc Start = Parser.getTok().getLoc(), End;
727 unsigned Size = getIntelMemOperandSize(Tok.getString());
730 assert (Tok.getString() == "PTR" && "Unexpected token!");
734 if (getLexer().is(AsmToken::LBrac))
735 return ParseIntelBracExpression(SegReg, Size);
737 if (!ParseRegister(SegReg, Start, End)) {
738 // Handel SegReg : [ ... ]
739 if (getLexer().isNot(AsmToken::Colon))
740 return ErrorOperand(Start, "Expected ':' token!");
741 Parser.Lex(); // Eat :
742 if (getLexer().isNot(AsmToken::LBrac))
743 return ErrorOperand(Start, "Expected '[' token!");
744 return ParseIntelBracExpression(SegReg, Size);
747 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
748 if (getParser().ParseExpression(Disp, End)) return 0;
749 return X86Operand::CreateMem(Disp, Start, End, Size);
752 X86Operand *X86AsmParser::ParseIntelOperand() {
753 SMLoc Start = Parser.getTok().getLoc(), End;
756 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
757 getLexer().is(AsmToken::Minus)) {
759 if (!getParser().ParseExpression(Val, End)) {
760 End = Parser.getTok().getLoc();
761 return X86Operand::CreateImm(Val, Start, End);
767 if (!ParseRegister(RegNo, Start, End)) {
768 End = Parser.getTok().getLoc();
769 return X86Operand::CreateReg(RegNo, Start, End);
773 return ParseIntelMemOperand();
776 X86Operand *X86AsmParser::ParseATTOperand() {
777 switch (getLexer().getKind()) {
779 // Parse a memory operand with no segment register.
780 return ParseMemOperand(0, Parser.getTok().getLoc());
781 case AsmToken::Percent: {
782 // Read the register.
785 if (ParseRegister(RegNo, Start, End)) return 0;
786 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
787 Error(Start, "%eiz and %riz can only be used as index registers",
788 SMRange(Start, End));
792 // If this is a segment register followed by a ':', then this is the start
793 // of a memory reference, otherwise this is a normal register reference.
794 if (getLexer().isNot(AsmToken::Colon))
795 return X86Operand::CreateReg(RegNo, Start, End);
798 getParser().Lex(); // Eat the colon.
799 return ParseMemOperand(RegNo, Start);
801 case AsmToken::Dollar: {
803 SMLoc Start = Parser.getTok().getLoc(), End;
806 if (getParser().ParseExpression(Val, End))
808 return X86Operand::CreateImm(Val, Start, End);
813 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
814 /// has already been parsed if present.
815 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
817 // We have to disambiguate a parenthesized expression "(4+5)" from the start
818 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
819 // only way to do this without lookahead is to eat the '(' and see what is
821 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
822 if (getLexer().isNot(AsmToken::LParen)) {
824 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
826 // After parsing the base expression we could either have a parenthesized
827 // memory address or not. If not, return now. If so, eat the (.
828 if (getLexer().isNot(AsmToken::LParen)) {
829 // Unless we have a segment register, treat this as an immediate.
831 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
832 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
838 // Okay, we have a '('. We don't know if this is an expression or not, but
839 // so we have to eat the ( to see beyond it.
840 SMLoc LParenLoc = Parser.getTok().getLoc();
841 Parser.Lex(); // Eat the '('.
843 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
844 // Nothing to do here, fall into the code below with the '(' part of the
845 // memory operand consumed.
849 // It must be an parenthesized expression, parse it now.
850 if (getParser().ParseParenExpression(Disp, ExprEnd))
853 // After parsing the base expression we could either have a parenthesized
854 // memory address or not. If not, return now. If so, eat the (.
855 if (getLexer().isNot(AsmToken::LParen)) {
856 // Unless we have a segment register, treat this as an immediate.
858 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
859 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
867 // If we reached here, then we just ate the ( of the memory operand. Process
868 // the rest of the memory operand.
869 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
872 if (getLexer().is(AsmToken::Percent)) {
873 SMLoc StartLoc, EndLoc;
874 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
875 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
876 Error(StartLoc, "eiz and riz can only be used as index registers",
877 SMRange(StartLoc, EndLoc));
882 if (getLexer().is(AsmToken::Comma)) {
883 Parser.Lex(); // Eat the comma.
884 IndexLoc = Parser.getTok().getLoc();
886 // Following the comma we should have either an index register, or a scale
887 // value. We don't support the later form, but we want to parse it
890 // Not that even though it would be completely consistent to support syntax
891 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
892 if (getLexer().is(AsmToken::Percent)) {
894 if (ParseRegister(IndexReg, L, L)) return 0;
896 if (getLexer().isNot(AsmToken::RParen)) {
897 // Parse the scale amount:
898 // ::= ',' [scale-expression]
899 if (getLexer().isNot(AsmToken::Comma)) {
900 Error(Parser.getTok().getLoc(),
901 "expected comma in scale expression");
904 Parser.Lex(); // Eat the comma.
906 if (getLexer().isNot(AsmToken::RParen)) {
907 SMLoc Loc = Parser.getTok().getLoc();
910 if (getParser().ParseAbsoluteExpression(ScaleVal)){
911 Error(Loc, "expected scale expression");
915 // Validate the scale amount.
916 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
917 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
920 Scale = (unsigned)ScaleVal;
923 } else if (getLexer().isNot(AsmToken::RParen)) {
924 // A scale amount without an index is ignored.
926 SMLoc Loc = Parser.getTok().getLoc();
929 if (getParser().ParseAbsoluteExpression(Value))
933 Warning(Loc, "scale factor without index register is ignored");
938 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
939 if (getLexer().isNot(AsmToken::RParen)) {
940 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
943 SMLoc MemEnd = Parser.getTok().getLoc();
944 Parser.Lex(); // Eat the ')'.
946 // If we have both a base register and an index register make sure they are
947 // both 64-bit or 32-bit registers.
948 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
949 if (BaseReg != 0 && IndexReg != 0) {
950 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
951 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
952 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
953 IndexReg != X86::RIZ) {
954 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
957 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
958 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
959 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
960 IndexReg != X86::EIZ){
961 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
966 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
971 ParseInstruction(StringRef Name, SMLoc NameLoc,
972 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
973 StringRef PatchedName = Name;
975 // FIXME: Hack to recognize setneb as setne.
976 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
977 PatchedName != "setb" && PatchedName != "setnb")
978 PatchedName = PatchedName.substr(0, Name.size()-1);
980 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
981 const MCExpr *ExtraImmOp = 0;
982 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
983 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
984 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
985 bool IsVCMP = PatchedName[0] == 'v';
986 unsigned SSECCIdx = IsVCMP ? 4 : 3;
987 unsigned SSEComparisonCode = StringSwitch<unsigned>(
988 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
997 /* AVX only from here */
1001 .Case("false", 0x0B)
1002 .Case("neq_oq", 0x0C)
1006 .Case("eq_os", 0x10)
1007 .Case("lt_oq", 0x11)
1008 .Case("le_oq", 0x12)
1009 .Case("unord_s", 0x13)
1010 .Case("neq_us", 0x14)
1011 .Case("nlt_uq", 0x15)
1012 .Case("nle_uq", 0x16)
1013 .Case("ord_s", 0x17)
1014 .Case("eq_us", 0x18)
1015 .Case("nge_uq", 0x19)
1016 .Case("ngt_uq", 0x1A)
1017 .Case("false_os", 0x1B)
1018 .Case("neq_os", 0x1C)
1019 .Case("ge_oq", 0x1D)
1020 .Case("gt_oq", 0x1E)
1021 .Case("true_us", 0x1F)
1023 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1024 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1025 getParser().getContext());
1026 if (PatchedName.endswith("ss")) {
1027 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1028 } else if (PatchedName.endswith("sd")) {
1029 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1030 } else if (PatchedName.endswith("ps")) {
1031 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1033 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1034 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1039 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1041 if (ExtraImmOp && !isParsingIntelSyntax())
1042 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1044 // Determine whether this is an instruction prefix.
1046 Name == "lock" || Name == "rep" ||
1047 Name == "repe" || Name == "repz" ||
1048 Name == "repne" || Name == "repnz" ||
1049 Name == "rex64" || Name == "data16";
1052 // This does the actual operand parsing. Don't parse any more if we have a
1053 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1054 // just want to parse the "lock" as the first instruction and the "incl" as
1056 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1058 // Parse '*' modifier.
1059 if (getLexer().is(AsmToken::Star)) {
1060 SMLoc Loc = Parser.getTok().getLoc();
1061 Operands.push_back(X86Operand::CreateToken("*", Loc));
1062 Parser.Lex(); // Eat the star.
1065 // Read the first operand.
1066 if (X86Operand *Op = ParseOperand())
1067 Operands.push_back(Op);
1069 Parser.EatToEndOfStatement();
1073 while (getLexer().is(AsmToken::Comma)) {
1074 Parser.Lex(); // Eat the comma.
1076 // Parse and remember the operand.
1077 if (X86Operand *Op = ParseOperand())
1078 Operands.push_back(Op);
1080 Parser.EatToEndOfStatement();
1085 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1086 SMLoc Loc = getLexer().getLoc();
1087 Parser.EatToEndOfStatement();
1088 return Error(Loc, "unexpected token in argument list");
1092 if (getLexer().is(AsmToken::EndOfStatement))
1093 Parser.Lex(); // Consume the EndOfStatement
1094 else if (isPrefix && getLexer().is(AsmToken::Slash))
1095 Parser.Lex(); // Consume the prefix separator Slash
1097 if (ExtraImmOp && isParsingIntelSyntax())
1098 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1100 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1101 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1102 // documented form in various unofficial manuals, so a lot of code uses it.
1103 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1104 Operands.size() == 3) {
1105 X86Operand &Op = *(X86Operand*)Operands.back();
1106 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1107 isa<MCConstantExpr>(Op.Mem.Disp) &&
1108 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1109 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1110 SMLoc Loc = Op.getEndLoc();
1111 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1115 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1116 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1117 Operands.size() == 3) {
1118 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1119 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1120 isa<MCConstantExpr>(Op.Mem.Disp) &&
1121 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1122 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1123 SMLoc Loc = Op.getEndLoc();
1124 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1128 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1129 if (Name.startswith("ins") && Operands.size() == 3 &&
1130 (Name == "insb" || Name == "insw" || Name == "insl")) {
1131 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1132 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1133 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1134 Operands.pop_back();
1135 Operands.pop_back();
1141 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1142 if (Name.startswith("outs") && Operands.size() == 3 &&
1143 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1144 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1145 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1146 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1147 Operands.pop_back();
1148 Operands.pop_back();
1154 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1155 if (Name.startswith("movs") && Operands.size() == 3 &&
1156 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1157 (is64BitMode() && Name == "movsq"))) {
1158 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1159 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1160 if (isSrcOp(Op) && isDstOp(Op2)) {
1161 Operands.pop_back();
1162 Operands.pop_back();
1167 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1168 if (Name.startswith("lods") && Operands.size() == 3 &&
1169 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1170 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1171 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1172 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1173 if (isSrcOp(*Op1) && Op2->isReg()) {
1175 unsigned reg = Op2->getReg();
1176 bool isLods = Name == "lods";
1177 if (reg == X86::AL && (isLods || Name == "lodsb"))
1179 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1181 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1183 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1188 Operands.pop_back();
1189 Operands.pop_back();
1193 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1197 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1198 if (Name.startswith("stos") && Operands.size() == 3 &&
1199 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1200 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1201 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1202 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1203 if (isDstOp(*Op2) && Op1->isReg()) {
1205 unsigned reg = Op1->getReg();
1206 bool isStos = Name == "stos";
1207 if (reg == X86::AL && (isStos || Name == "stosb"))
1209 else if (reg == X86::AX && (isStos || Name == "stosw"))
1211 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1213 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1218 Operands.pop_back();
1219 Operands.pop_back();
1223 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1228 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1230 if ((Name.startswith("shr") || Name.startswith("sar") ||
1231 Name.startswith("shl") || Name.startswith("sal") ||
1232 Name.startswith("rcl") || Name.startswith("rcr") ||
1233 Name.startswith("rol") || Name.startswith("ror")) &&
1234 Operands.size() == 3) {
1235 if (isParsingIntelSyntax()) {
1237 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1238 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1239 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1241 Operands.pop_back();
1244 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1245 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1246 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1248 Operands.erase(Operands.begin() + 1);
1253 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1254 // instalias with an immediate operand yet.
1255 if (Name == "int" && Operands.size() == 2) {
1256 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1257 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1258 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1260 Operands.erase(Operands.begin() + 1);
1261 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1269 processInstruction(MCInst &Inst,
1270 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1271 switch (Inst.getOpcode()) {
1272 default: return false;
1273 case X86::AND16i16: {
1274 if (!Inst.getOperand(0).isImm() ||
1275 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1279 TmpInst.setOpcode(X86::AND16ri8);
1280 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1281 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1282 TmpInst.addOperand(Inst.getOperand(0));
1286 case X86::AND32i32: {
1287 if (!Inst.getOperand(0).isImm() ||
1288 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1292 TmpInst.setOpcode(X86::AND32ri8);
1293 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1294 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1295 TmpInst.addOperand(Inst.getOperand(0));
1299 case X86::AND64i32: {
1300 if (!Inst.getOperand(0).isImm() ||
1301 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1305 TmpInst.setOpcode(X86::AND64ri8);
1306 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1307 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1308 TmpInst.addOperand(Inst.getOperand(0));
1312 case X86::XOR16i16: {
1313 if (!Inst.getOperand(0).isImm() ||
1314 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1318 TmpInst.setOpcode(X86::XOR16ri8);
1319 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1320 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1321 TmpInst.addOperand(Inst.getOperand(0));
1325 case X86::XOR32i32: {
1326 if (!Inst.getOperand(0).isImm() ||
1327 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1331 TmpInst.setOpcode(X86::XOR32ri8);
1332 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1333 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1334 TmpInst.addOperand(Inst.getOperand(0));
1338 case X86::XOR64i32: {
1339 if (!Inst.getOperand(0).isImm() ||
1340 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1344 TmpInst.setOpcode(X86::XOR64ri8);
1345 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1346 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1347 TmpInst.addOperand(Inst.getOperand(0));
1351 case X86::OR16i16: {
1352 if (!Inst.getOperand(0).isImm() ||
1353 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1357 TmpInst.setOpcode(X86::OR16ri8);
1358 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1359 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1360 TmpInst.addOperand(Inst.getOperand(0));
1364 case X86::OR32i32: {
1365 if (!Inst.getOperand(0).isImm() ||
1366 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1370 TmpInst.setOpcode(X86::OR32ri8);
1371 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1372 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1373 TmpInst.addOperand(Inst.getOperand(0));
1377 case X86::OR64i32: {
1378 if (!Inst.getOperand(0).isImm() ||
1379 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1383 TmpInst.setOpcode(X86::OR64ri8);
1384 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1385 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1386 TmpInst.addOperand(Inst.getOperand(0));
1390 case X86::CMP16i16: {
1391 if (!Inst.getOperand(0).isImm() ||
1392 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1396 TmpInst.setOpcode(X86::CMP16ri8);
1397 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1398 TmpInst.addOperand(Inst.getOperand(0));
1402 case X86::CMP32i32: {
1403 if (!Inst.getOperand(0).isImm() ||
1404 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1408 TmpInst.setOpcode(X86::CMP32ri8);
1409 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1410 TmpInst.addOperand(Inst.getOperand(0));
1414 case X86::CMP64i32: {
1415 if (!Inst.getOperand(0).isImm() ||
1416 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1420 TmpInst.setOpcode(X86::CMP64ri8);
1421 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1422 TmpInst.addOperand(Inst.getOperand(0));
1426 case X86::ADD16i16: {
1427 if (!Inst.getOperand(0).isImm() ||
1428 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1432 TmpInst.setOpcode(X86::ADD16ri8);
1433 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1434 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1435 TmpInst.addOperand(Inst.getOperand(0));
1439 case X86::ADD32i32: {
1440 if (!Inst.getOperand(0).isImm() ||
1441 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1445 TmpInst.setOpcode(X86::ADD32ri8);
1446 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1447 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1448 TmpInst.addOperand(Inst.getOperand(0));
1452 case X86::ADD64i32: {
1453 if (!Inst.getOperand(0).isImm() ||
1454 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1458 TmpInst.setOpcode(X86::ADD64ri8);
1459 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1460 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1461 TmpInst.addOperand(Inst.getOperand(0));
1465 case X86::SUB16i16: {
1466 if (!Inst.getOperand(0).isImm() ||
1467 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1471 TmpInst.setOpcode(X86::SUB16ri8);
1472 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1473 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1474 TmpInst.addOperand(Inst.getOperand(0));
1478 case X86::SUB32i32: {
1479 if (!Inst.getOperand(0).isImm() ||
1480 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1484 TmpInst.setOpcode(X86::SUB32ri8);
1485 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1486 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1487 TmpInst.addOperand(Inst.getOperand(0));
1491 case X86::SUB64i32: {
1492 if (!Inst.getOperand(0).isImm() ||
1493 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1497 TmpInst.setOpcode(X86::SUB64ri8);
1498 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1499 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1500 TmpInst.addOperand(Inst.getOperand(0));
1508 MatchAndEmitInstruction(SMLoc IDLoc,
1509 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1511 assert(!Operands.empty() && "Unexpect empty operand list!");
1512 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1513 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1515 // First, handle aliases that expand to multiple instructions.
1516 // FIXME: This should be replaced with a real .td file alias mechanism.
1517 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1519 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1520 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1521 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1522 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1524 Inst.setOpcode(X86::WAIT);
1526 Out.EmitInstruction(Inst);
1529 StringSwitch<const char*>(Op->getToken())
1530 .Case("finit", "fninit")
1531 .Case("fsave", "fnsave")
1532 .Case("fstcw", "fnstcw")
1533 .Case("fstcww", "fnstcw")
1534 .Case("fstenv", "fnstenv")
1535 .Case("fstsw", "fnstsw")
1536 .Case("fstsww", "fnstsw")
1537 .Case("fclex", "fnclex")
1539 assert(Repl && "Unknown wait-prefixed instruction");
1541 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1544 bool WasOriginallyInvalidOperand = false;
1545 unsigned OrigErrorInfo;
1548 // First, try a direct match.
1549 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo,
1550 isParsingIntelSyntax())) {
1553 // Some instructions need post-processing to, for example, tweak which
1554 // encoding is selected. Loop on it while changes happen so the
1555 // individual transformations can chain off each other.
1556 while (processInstruction(Inst, Operands))
1560 Out.EmitInstruction(Inst);
1562 case Match_MissingFeature:
1563 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1565 case Match_ConversionFail:
1566 return Error(IDLoc, "unable to convert operands to instruction");
1567 case Match_InvalidOperand:
1568 WasOriginallyInvalidOperand = true;
1570 case Match_MnemonicFail:
1574 // FIXME: Ideally, we would only attempt suffix matches for things which are
1575 // valid prefixes, and we could just infer the right unambiguous
1576 // type. However, that requires substantially more matcher support than the
1579 // Change the operand to point to a temporary token.
1580 StringRef Base = Op->getToken();
1581 SmallString<16> Tmp;
1584 Op->setTokenValue(Tmp.str());
1586 // If this instruction starts with an 'f', then it is a floating point stack
1587 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1588 // 80-bit floating point, which use the suffixes s,l,t respectively.
1590 // Otherwise, we assume that this may be an integer instruction, which comes
1591 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1592 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1594 // Check for the various suffix matches.
1595 Tmp[Base.size()] = Suffixes[0];
1596 unsigned ErrorInfoIgnore;
1597 unsigned Match1, Match2, Match3, Match4;
1599 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1600 Tmp[Base.size()] = Suffixes[1];
1601 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1602 Tmp[Base.size()] = Suffixes[2];
1603 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1604 Tmp[Base.size()] = Suffixes[3];
1605 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1607 // Restore the old token.
1608 Op->setTokenValue(Base);
1610 // If exactly one matched, then we treat that as a successful match (and the
1611 // instruction will already have been filled in correctly, since the failing
1612 // matches won't have modified it).
1613 unsigned NumSuccessfulMatches =
1614 (Match1 == Match_Success) + (Match2 == Match_Success) +
1615 (Match3 == Match_Success) + (Match4 == Match_Success);
1616 if (NumSuccessfulMatches == 1) {
1618 Out.EmitInstruction(Inst);
1622 // Otherwise, the match failed, try to produce a decent error message.
1624 // If we had multiple suffix matches, then identify this as an ambiguous
1626 if (NumSuccessfulMatches > 1) {
1628 unsigned NumMatches = 0;
1629 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1630 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1631 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1632 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1634 SmallString<126> Msg;
1635 raw_svector_ostream OS(Msg);
1636 OS << "ambiguous instructions require an explicit suffix (could be ";
1637 for (unsigned i = 0; i != NumMatches; ++i) {
1640 if (i + 1 == NumMatches)
1642 OS << "'" << Base << MatchChars[i] << "'";
1645 Error(IDLoc, OS.str());
1649 // Okay, we know that none of the variants matched successfully.
1651 // If all of the instructions reported an invalid mnemonic, then the original
1652 // mnemonic was invalid.
1653 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1654 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1655 if (!WasOriginallyInvalidOperand) {
1656 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1660 // Recover location info for the operand if we know which was the problem.
1661 if (OrigErrorInfo != ~0U) {
1662 if (OrigErrorInfo >= Operands.size())
1663 return Error(IDLoc, "too few operands for instruction");
1665 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1666 if (Operand->getStartLoc().isValid()) {
1667 SMRange OperandRange = Operand->getLocRange();
1668 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1673 return Error(IDLoc, "invalid operand for instruction");
1676 // If one instruction matched with a missing feature, report this as a
1678 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1679 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1680 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1684 // If one instruction matched with an invalid operand, report this as an
1686 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1687 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1688 Error(IDLoc, "invalid operand for instruction");
1692 // If all of these were an outright failure, report it in a useless way.
1693 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1698 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1699 StringRef IDVal = DirectiveID.getIdentifier();
1700 if (IDVal == ".word")
1701 return ParseDirectiveWord(2, DirectiveID.getLoc());
1702 else if (IDVal.startswith(".code"))
1703 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1704 else if (IDVal.startswith(".intel_syntax")) {
1705 getParser().setAssemblerDialect(1);
1706 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1707 if(Parser.getTok().getString() == "noprefix") {
1708 // FIXME : Handle noprefix
1718 /// ParseDirectiveWord
1719 /// ::= .word [ expression (, expression)* ]
1720 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1721 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1723 const MCExpr *Value;
1724 if (getParser().ParseExpression(Value))
1727 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1729 if (getLexer().is(AsmToken::EndOfStatement))
1732 // FIXME: Improve diagnostic.
1733 if (getLexer().isNot(AsmToken::Comma))
1734 return Error(L, "unexpected token in directive");
1743 /// ParseDirectiveCode
1744 /// ::= .code32 | .code64
1745 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1746 if (IDVal == ".code32") {
1748 if (is64BitMode()) {
1750 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1752 } else if (IDVal == ".code64") {
1754 if (!is64BitMode()) {
1756 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1759 return Error(L, "unexpected directive " + IDVal);
1766 extern "C" void LLVMInitializeX86AsmLexer();
1768 // Force static initialization.
1769 extern "C" void LLVMInitializeX86AsmParser() {
1770 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1771 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1772 LLVMInitializeX86AsmLexer();
1775 #define GET_REGISTER_MATCHER
1776 #define GET_MATCHER_IMPLEMENTATION
1777 #include "X86GenAsmMatcher.inc"