1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Support/raw_ostream.h"
33 class X86AsmParser : public MCTargetAsmParser {
37 MCAsmParser &getParser() const { return Parser; }
39 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
41 bool Error(SMLoc L, const Twine &Msg,
42 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
43 bool MatchingInlineAsm = false) {
44 if (MatchingInlineAsm) return true;
45 return Parser.Error(L, Msg, Ranges);
48 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
53 X86Operand *ParseOperand();
54 X86Operand *ParseATTOperand();
55 X86Operand *ParseIntelOperand();
56 X86Operand *ParseIntelMemOperand(unsigned SegReg, SMLoc StartLoc);
57 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
58 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
60 bool ParseDirectiveWord(unsigned Size, SMLoc L);
61 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
63 bool processInstruction(MCInst &Inst,
64 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
66 bool MatchAndEmitInstruction(SMLoc IDLoc,
67 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
69 bool MatchInstruction(SMLoc IDLoc,
70 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
71 MCStreamer &Out, unsigned &Opcode,
72 unsigned &OrigErrorInfo, bool MatchingInlineAsm = false);
74 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
75 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
76 bool isSrcOp(X86Operand &Op);
78 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
79 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
80 bool isDstOp(X86Operand &Op);
82 bool is64BitMode() const {
83 // FIXME: Can tablegen auto-generate this?
84 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
87 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
88 setAvailableFeatures(FB);
91 /// @name Auto-generated Matcher Functions
94 #define GET_ASSEMBLER_HEADER
95 #include "X86GenAsmMatcher.inc"
100 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
101 : MCTargetAsmParser(), STI(sti), Parser(parser) {
103 // Initialize the set of available features.
104 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
106 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
108 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
109 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
111 virtual bool ParseDirective(AsmToken DirectiveID);
113 bool isParsingIntelSyntax() {
114 return getParser().getAssemblerDialect();
117 } // end anonymous namespace
119 /// @name Auto-generated Match Functions
122 static unsigned MatchRegisterName(StringRef Name);
126 static bool isImmSExti16i8Value(uint64_t Value) {
127 return (( Value <= 0x000000000000007FULL)||
128 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
129 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
132 static bool isImmSExti32i8Value(uint64_t Value) {
133 return (( Value <= 0x000000000000007FULL)||
134 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
135 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
138 static bool isImmZExtu32u8Value(uint64_t Value) {
139 return (Value <= 0x00000000000000FFULL);
142 static bool isImmSExti64i8Value(uint64_t Value) {
143 return (( Value <= 0x000000000000007FULL)||
144 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
147 static bool isImmSExti64i32Value(uint64_t Value) {
148 return (( Value <= 0x000000007FFFFFFFULL)||
149 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
153 /// X86Operand - Instances of this class represent a parsed X86 machine
155 struct X86Operand : public MCParsedAsmOperand {
163 SMLoc StartLoc, EndLoc;
189 X86Operand(KindTy K, SMLoc Start, SMLoc End)
190 : Kind(K), StartLoc(Start), EndLoc(End) {}
192 /// getStartLoc - Get the location of the first token of this operand.
193 SMLoc getStartLoc() const { return StartLoc; }
194 /// getEndLoc - Get the location of the last token of this operand.
195 SMLoc getEndLoc() const { return EndLoc; }
196 /// getLocRange - Get the range between the first and last token of this
198 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
200 virtual void print(raw_ostream &OS) const {}
202 StringRef getToken() const {
203 assert(Kind == Token && "Invalid access!");
204 return StringRef(Tok.Data, Tok.Length);
206 void setTokenValue(StringRef Value) {
207 assert(Kind == Token && "Invalid access!");
208 Tok.Data = Value.data();
209 Tok.Length = Value.size();
212 unsigned getReg() const {
213 assert(Kind == Register && "Invalid access!");
217 const MCExpr *getImm() const {
218 assert(Kind == Immediate && "Invalid access!");
222 const MCExpr *getMemDisp() const {
223 assert(Kind == Memory && "Invalid access!");
226 unsigned getMemSegReg() const {
227 assert(Kind == Memory && "Invalid access!");
230 unsigned getMemBaseReg() const {
231 assert(Kind == Memory && "Invalid access!");
234 unsigned getMemIndexReg() const {
235 assert(Kind == Memory && "Invalid access!");
238 unsigned getMemScale() const {
239 assert(Kind == Memory && "Invalid access!");
243 bool isToken() const {return Kind == Token; }
245 bool isImm() const { return Kind == Immediate; }
247 bool isImmSExti16i8() const {
251 // If this isn't a constant expr, just assume it fits and let relaxation
253 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
257 // Otherwise, check the value is in a range that makes sense for this
259 return isImmSExti16i8Value(CE->getValue());
261 bool isImmSExti32i8() const {
265 // If this isn't a constant expr, just assume it fits and let relaxation
267 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
271 // Otherwise, check the value is in a range that makes sense for this
273 return isImmSExti32i8Value(CE->getValue());
275 bool isImmZExtu32u8() const {
279 // If this isn't a constant expr, just assume it fits and let relaxation
281 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
285 // Otherwise, check the value is in a range that makes sense for this
287 return isImmZExtu32u8Value(CE->getValue());
289 bool isImmSExti64i8() const {
293 // If this isn't a constant expr, just assume it fits and let relaxation
295 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
299 // Otherwise, check the value is in a range that makes sense for this
301 return isImmSExti64i8Value(CE->getValue());
303 bool isImmSExti64i32() const {
307 // If this isn't a constant expr, just assume it fits and let relaxation
309 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
313 // Otherwise, check the value is in a range that makes sense for this
315 return isImmSExti64i32Value(CE->getValue());
318 bool isMem() const { return Kind == Memory; }
319 bool isMem8() const {
320 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
322 bool isMem16() const {
323 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
325 bool isMem32() const {
326 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
328 bool isMem64() const {
329 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
331 bool isMem80() const {
332 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
334 bool isMem128() const {
335 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
337 bool isMem256() const {
338 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
341 bool isMemVX32() const {
342 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
343 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
345 bool isMemVY32() const {
346 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
347 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
349 bool isMemVX64() const {
350 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
351 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
353 bool isMemVY64() const {
354 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
355 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
358 bool isAbsMem() const {
359 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
360 !getMemIndexReg() && getMemScale() == 1;
363 bool isReg() const { return Kind == Register; }
365 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
366 // Add as immediates when possible.
367 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
368 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
370 Inst.addOperand(MCOperand::CreateExpr(Expr));
373 void addRegOperands(MCInst &Inst, unsigned N) const {
374 assert(N == 1 && "Invalid number of operands!");
375 Inst.addOperand(MCOperand::CreateReg(getReg()));
378 void addImmOperands(MCInst &Inst, unsigned N) const {
379 assert(N == 1 && "Invalid number of operands!");
380 addExpr(Inst, getImm());
383 void addMem8Operands(MCInst &Inst, unsigned N) const {
384 addMemOperands(Inst, N);
386 void addMem16Operands(MCInst &Inst, unsigned N) const {
387 addMemOperands(Inst, N);
389 void addMem32Operands(MCInst &Inst, unsigned N) const {
390 addMemOperands(Inst, N);
392 void addMem64Operands(MCInst &Inst, unsigned N) const {
393 addMemOperands(Inst, N);
395 void addMem80Operands(MCInst &Inst, unsigned N) const {
396 addMemOperands(Inst, N);
398 void addMem128Operands(MCInst &Inst, unsigned N) const {
399 addMemOperands(Inst, N);
401 void addMem256Operands(MCInst &Inst, unsigned N) const {
402 addMemOperands(Inst, N);
404 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
405 addMemOperands(Inst, N);
407 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
408 addMemOperands(Inst, N);
410 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
411 addMemOperands(Inst, N);
413 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
414 addMemOperands(Inst, N);
417 void addMemOperands(MCInst &Inst, unsigned N) const {
418 assert((N == 5) && "Invalid number of operands!");
419 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
420 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
421 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
422 addExpr(Inst, getMemDisp());
423 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
426 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
427 assert((N == 1) && "Invalid number of operands!");
428 // Add as immediates when possible.
429 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
430 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
432 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
435 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
436 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
437 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
438 Res->Tok.Data = Str.data();
439 Res->Tok.Length = Str.size();
443 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
444 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
445 Res->Reg.RegNo = RegNo;
449 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
450 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
455 /// Create an absolute memory operand.
456 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
457 SMLoc EndLoc, unsigned Size = 0) {
458 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
460 Res->Mem.Disp = Disp;
461 Res->Mem.BaseReg = 0;
462 Res->Mem.IndexReg = 0;
464 Res->Mem.Size = Size;
468 /// Create a generalized memory operand.
469 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
470 unsigned BaseReg, unsigned IndexReg,
471 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
473 // We should never just have a displacement, that should be parsed as an
474 // absolute memory operand.
475 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
477 // The scale should always be one of {1,2,4,8}.
478 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
480 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
481 Res->Mem.SegReg = SegReg;
482 Res->Mem.Disp = Disp;
483 Res->Mem.BaseReg = BaseReg;
484 Res->Mem.IndexReg = IndexReg;
485 Res->Mem.Scale = Scale;
486 Res->Mem.Size = Size;
491 } // end anonymous namespace.
493 bool X86AsmParser::isSrcOp(X86Operand &Op) {
494 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
496 return (Op.isMem() &&
497 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
498 isa<MCConstantExpr>(Op.Mem.Disp) &&
499 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
500 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
503 bool X86AsmParser::isDstOp(X86Operand &Op) {
504 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
507 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
508 isa<MCConstantExpr>(Op.Mem.Disp) &&
509 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
510 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
513 bool X86AsmParser::ParseRegister(unsigned &RegNo,
514 SMLoc &StartLoc, SMLoc &EndLoc) {
516 const AsmToken &PercentTok = Parser.getTok();
517 StartLoc = PercentTok.getLoc();
519 // If we encounter a %, ignore it. This code handles registers with and
520 // without the prefix, unprefixed registers can occur in cfi directives.
521 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
522 Parser.Lex(); // Eat percent token.
524 const AsmToken &Tok = Parser.getTok();
525 if (Tok.isNot(AsmToken::Identifier)) {
526 if (isParsingIntelSyntax()) return true;
527 return Error(StartLoc, "invalid register name",
528 SMRange(StartLoc, Tok.getEndLoc()));
531 RegNo = MatchRegisterName(Tok.getString());
533 // If the match failed, try the register name as lowercase.
535 RegNo = MatchRegisterName(Tok.getString().lower());
537 if (!is64BitMode()) {
538 // FIXME: This should be done using Requires<In32BitMode> and
539 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
541 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
543 if (RegNo == X86::RIZ ||
544 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
545 X86II::isX86_64NonExtLowByteReg(RegNo) ||
546 X86II::isX86_64ExtendedReg(RegNo))
547 return Error(StartLoc, "register %"
548 + Tok.getString() + " is only available in 64-bit mode",
549 SMRange(StartLoc, Tok.getEndLoc()));
552 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
553 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
555 EndLoc = Tok.getLoc();
556 Parser.Lex(); // Eat 'st'
558 // Check to see if we have '(4)' after %st.
559 if (getLexer().isNot(AsmToken::LParen))
564 const AsmToken &IntTok = Parser.getTok();
565 if (IntTok.isNot(AsmToken::Integer))
566 return Error(IntTok.getLoc(), "expected stack index");
567 switch (IntTok.getIntVal()) {
568 case 0: RegNo = X86::ST0; break;
569 case 1: RegNo = X86::ST1; break;
570 case 2: RegNo = X86::ST2; break;
571 case 3: RegNo = X86::ST3; break;
572 case 4: RegNo = X86::ST4; break;
573 case 5: RegNo = X86::ST5; break;
574 case 6: RegNo = X86::ST6; break;
575 case 7: RegNo = X86::ST7; break;
576 default: return Error(IntTok.getLoc(), "invalid stack index");
579 if (getParser().Lex().isNot(AsmToken::RParen))
580 return Error(Parser.getTok().getLoc(), "expected ')'");
582 EndLoc = Tok.getLoc();
583 Parser.Lex(); // Eat ')'
587 // If this is "db[0-7]", match it as an alias
589 if (RegNo == 0 && Tok.getString().size() == 3 &&
590 Tok.getString().startswith("db")) {
591 switch (Tok.getString()[2]) {
592 case '0': RegNo = X86::DR0; break;
593 case '1': RegNo = X86::DR1; break;
594 case '2': RegNo = X86::DR2; break;
595 case '3': RegNo = X86::DR3; break;
596 case '4': RegNo = X86::DR4; break;
597 case '5': RegNo = X86::DR5; break;
598 case '6': RegNo = X86::DR6; break;
599 case '7': RegNo = X86::DR7; break;
603 EndLoc = Tok.getLoc();
604 Parser.Lex(); // Eat it.
610 if (isParsingIntelSyntax()) return true;
611 return Error(StartLoc, "invalid register name",
612 SMRange(StartLoc, Tok.getEndLoc()));
615 EndLoc = Tok.getEndLoc();
616 Parser.Lex(); // Eat identifier token.
620 X86Operand *X86AsmParser::ParseOperand() {
621 if (isParsingIntelSyntax())
622 return ParseIntelOperand();
623 return ParseATTOperand();
626 /// getIntelMemOperandSize - Return intel memory operand size.
627 static unsigned getIntelMemOperandSize(StringRef OpStr) {
628 unsigned Size = StringSwitch<unsigned>(OpStr)
629 .Cases("BYTE", "byte", 8)
630 .Cases("WORD", "word", 16)
631 .Cases("DWORD", "dword", 32)
632 .Cases("QWORD", "qword", 64)
633 .Cases("XWORD", "xword", 80)
634 .Cases("XMMWORD", "xmmword", 128)
635 .Cases("YMMWORD", "ymmword", 256)
640 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
642 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
643 SMLoc Start = Parser.getTok().getLoc(), End;
645 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
646 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
649 if (getLexer().isNot(AsmToken::LBrac))
650 return ErrorOperand(Start, "Expected '[' token!");
653 if (getLexer().is(AsmToken::Identifier)) {
655 if (ParseRegister(BaseReg, Start, End)) {
656 // Handle '[' 'symbol' ']'
657 if (getParser().ParseExpression(Disp, End)) return 0;
658 if (getLexer().isNot(AsmToken::RBrac))
659 return ErrorOperand(Start, "Expected ']' token!");
661 return X86Operand::CreateMem(Disp, Start, End, Size);
663 } else if (getLexer().is(AsmToken::Integer)) {
664 int64_t Val = Parser.getTok().getIntVal();
666 SMLoc Loc = Parser.getTok().getLoc();
667 if (getLexer().is(AsmToken::RBrac)) {
668 // Handle '[' number ']'
670 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
672 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
674 return X86Operand::CreateMem(Disp, Start, End, Size);
675 } else if (getLexer().is(AsmToken::Star)) {
676 // Handle '[' Scale*IndexReg ']'
678 SMLoc IdxRegLoc = Parser.getTok().getLoc();
679 if (ParseRegister(IndexReg, IdxRegLoc, End))
680 return ErrorOperand(IdxRegLoc, "Expected register");
683 return ErrorOperand(Loc, "Unexpected token");
686 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
687 bool isPlus = getLexer().is(AsmToken::Plus);
689 SMLoc PlusLoc = Parser.getTok().getLoc();
690 if (getLexer().is(AsmToken::Integer)) {
691 int64_t Val = Parser.getTok().getIntVal();
693 if (getLexer().is(AsmToken::Star)) {
695 SMLoc IdxRegLoc = Parser.getTok().getLoc();
696 if (ParseRegister(IndexReg, IdxRegLoc, End))
697 return ErrorOperand(IdxRegLoc, "Expected register");
699 } else if (getLexer().is(AsmToken::RBrac)) {
700 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
701 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
703 return ErrorOperand(PlusLoc, "unexpected token after +");
704 } else if (getLexer().is(AsmToken::Identifier)) {
705 // This could be an index register or a displacement expression.
706 End = Parser.getTok().getLoc();
708 ParseRegister(IndexReg, Start, End);
709 else if (getParser().ParseExpression(Disp, End)) return 0;
713 if (getLexer().isNot(AsmToken::RBrac))
714 if (getParser().ParseExpression(Disp, End)) return 0;
716 End = Parser.getTok().getLoc();
717 if (getLexer().isNot(AsmToken::RBrac))
718 return ErrorOperand(End, "expected ']' token!");
720 End = Parser.getTok().getLoc();
723 if (!BaseReg && !IndexReg)
724 return X86Operand::CreateMem(Disp, Start, End, Size);
726 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
730 /// ParseIntelMemOperand - Parse intel style memory operand.
731 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
732 const AsmToken &Tok = Parser.getTok();
735 unsigned Size = getIntelMemOperandSize(Tok.getString());
738 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
739 "Unexpected token!");
743 if (getLexer().is(AsmToken::LBrac))
744 return ParseIntelBracExpression(SegReg, Size);
746 if (!ParseRegister(SegReg, Start, End)) {
747 // Handel SegReg : [ ... ]
748 if (getLexer().isNot(AsmToken::Colon))
749 return ErrorOperand(Start, "Expected ':' token!");
750 Parser.Lex(); // Eat :
751 if (getLexer().isNot(AsmToken::LBrac))
752 return ErrorOperand(Start, "Expected '[' token!");
753 return ParseIntelBracExpression(SegReg, Size);
756 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
757 if (getParser().ParseExpression(Disp, End)) return 0;
758 return X86Operand::CreateMem(Disp, Start, End, Size);
761 X86Operand *X86AsmParser::ParseIntelOperand() {
762 SMLoc Start = Parser.getTok().getLoc(), End;
765 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
766 getLexer().is(AsmToken::Minus)) {
768 if (!getParser().ParseExpression(Val, End)) {
769 End = Parser.getTok().getLoc();
770 return X86Operand::CreateImm(Val, Start, End);
776 if (!ParseRegister(RegNo, Start, End)) {
777 // If this is a segment register followed by a ':', then this is the start
778 // of a memory reference, otherwise this is a normal register reference.
779 if (getLexer().isNot(AsmToken::Colon))
780 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
782 getParser().Lex(); // Eat the colon.
783 return ParseIntelMemOperand(RegNo, Start);
787 return ParseIntelMemOperand(0, Start);
790 X86Operand *X86AsmParser::ParseATTOperand() {
791 switch (getLexer().getKind()) {
793 // Parse a memory operand with no segment register.
794 return ParseMemOperand(0, Parser.getTok().getLoc());
795 case AsmToken::Percent: {
796 // Read the register.
799 if (ParseRegister(RegNo, Start, End)) return 0;
800 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
801 Error(Start, "%eiz and %riz can only be used as index registers",
802 SMRange(Start, End));
806 // If this is a segment register followed by a ':', then this is the start
807 // of a memory reference, otherwise this is a normal register reference.
808 if (getLexer().isNot(AsmToken::Colon))
809 return X86Operand::CreateReg(RegNo, Start, End);
812 getParser().Lex(); // Eat the colon.
813 return ParseMemOperand(RegNo, Start);
815 case AsmToken::Dollar: {
817 SMLoc Start = Parser.getTok().getLoc(), End;
820 if (getParser().ParseExpression(Val, End))
822 return X86Operand::CreateImm(Val, Start, End);
827 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
828 /// has already been parsed if present.
829 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
831 // We have to disambiguate a parenthesized expression "(4+5)" from the start
832 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
833 // only way to do this without lookahead is to eat the '(' and see what is
835 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
836 if (getLexer().isNot(AsmToken::LParen)) {
838 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
840 // After parsing the base expression we could either have a parenthesized
841 // memory address or not. If not, return now. If so, eat the (.
842 if (getLexer().isNot(AsmToken::LParen)) {
843 // Unless we have a segment register, treat this as an immediate.
845 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
846 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
852 // Okay, we have a '('. We don't know if this is an expression or not, but
853 // so we have to eat the ( to see beyond it.
854 SMLoc LParenLoc = Parser.getTok().getLoc();
855 Parser.Lex(); // Eat the '('.
857 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
858 // Nothing to do here, fall into the code below with the '(' part of the
859 // memory operand consumed.
863 // It must be an parenthesized expression, parse it now.
864 if (getParser().ParseParenExpression(Disp, ExprEnd))
867 // After parsing the base expression we could either have a parenthesized
868 // memory address or not. If not, return now. If so, eat the (.
869 if (getLexer().isNot(AsmToken::LParen)) {
870 // Unless we have a segment register, treat this as an immediate.
872 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
873 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
881 // If we reached here, then we just ate the ( of the memory operand. Process
882 // the rest of the memory operand.
883 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
886 if (getLexer().is(AsmToken::Percent)) {
887 SMLoc StartLoc, EndLoc;
888 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
889 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
890 Error(StartLoc, "eiz and riz can only be used as index registers",
891 SMRange(StartLoc, EndLoc));
896 if (getLexer().is(AsmToken::Comma)) {
897 Parser.Lex(); // Eat the comma.
898 IndexLoc = Parser.getTok().getLoc();
900 // Following the comma we should have either an index register, or a scale
901 // value. We don't support the later form, but we want to parse it
904 // Not that even though it would be completely consistent to support syntax
905 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
906 if (getLexer().is(AsmToken::Percent)) {
908 if (ParseRegister(IndexReg, L, L)) return 0;
910 if (getLexer().isNot(AsmToken::RParen)) {
911 // Parse the scale amount:
912 // ::= ',' [scale-expression]
913 if (getLexer().isNot(AsmToken::Comma)) {
914 Error(Parser.getTok().getLoc(),
915 "expected comma in scale expression");
918 Parser.Lex(); // Eat the comma.
920 if (getLexer().isNot(AsmToken::RParen)) {
921 SMLoc Loc = Parser.getTok().getLoc();
924 if (getParser().ParseAbsoluteExpression(ScaleVal)){
925 Error(Loc, "expected scale expression");
929 // Validate the scale amount.
930 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
931 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
934 Scale = (unsigned)ScaleVal;
937 } else if (getLexer().isNot(AsmToken::RParen)) {
938 // A scale amount without an index is ignored.
940 SMLoc Loc = Parser.getTok().getLoc();
943 if (getParser().ParseAbsoluteExpression(Value))
947 Warning(Loc, "scale factor without index register is ignored");
952 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
953 if (getLexer().isNot(AsmToken::RParen)) {
954 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
957 SMLoc MemEnd = Parser.getTok().getLoc();
958 Parser.Lex(); // Eat the ')'.
960 // If we have both a base register and an index register make sure they are
961 // both 64-bit or 32-bit registers.
962 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
963 if (BaseReg != 0 && IndexReg != 0) {
964 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
965 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
966 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
967 IndexReg != X86::RIZ) {
968 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
971 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
972 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
973 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
974 IndexReg != X86::EIZ){
975 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
980 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
985 ParseInstruction(StringRef Name, SMLoc NameLoc,
986 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
987 StringRef PatchedName = Name;
989 // FIXME: Hack to recognize setneb as setne.
990 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
991 PatchedName != "setb" && PatchedName != "setnb")
992 PatchedName = PatchedName.substr(0, Name.size()-1);
994 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
995 const MCExpr *ExtraImmOp = 0;
996 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
997 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
998 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
999 bool IsVCMP = PatchedName[0] == 'v';
1000 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1001 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1002 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1006 .Case("unord", 0x03)
1011 /* AVX only from here */
1012 .Case("eq_uq", 0x08)
1015 .Case("false", 0x0B)
1016 .Case("neq_oq", 0x0C)
1020 .Case("eq_os", 0x10)
1021 .Case("lt_oq", 0x11)
1022 .Case("le_oq", 0x12)
1023 .Case("unord_s", 0x13)
1024 .Case("neq_us", 0x14)
1025 .Case("nlt_uq", 0x15)
1026 .Case("nle_uq", 0x16)
1027 .Case("ord_s", 0x17)
1028 .Case("eq_us", 0x18)
1029 .Case("nge_uq", 0x19)
1030 .Case("ngt_uq", 0x1A)
1031 .Case("false_os", 0x1B)
1032 .Case("neq_os", 0x1C)
1033 .Case("ge_oq", 0x1D)
1034 .Case("gt_oq", 0x1E)
1035 .Case("true_us", 0x1F)
1037 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1038 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1039 getParser().getContext());
1040 if (PatchedName.endswith("ss")) {
1041 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1042 } else if (PatchedName.endswith("sd")) {
1043 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1044 } else if (PatchedName.endswith("ps")) {
1045 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1047 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1048 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1053 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1055 if (ExtraImmOp && !isParsingIntelSyntax())
1056 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1058 // Determine whether this is an instruction prefix.
1060 Name == "lock" || Name == "rep" ||
1061 Name == "repe" || Name == "repz" ||
1062 Name == "repne" || Name == "repnz" ||
1063 Name == "rex64" || Name == "data16";
1066 // This does the actual operand parsing. Don't parse any more if we have a
1067 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1068 // just want to parse the "lock" as the first instruction and the "incl" as
1070 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1072 // Parse '*' modifier.
1073 if (getLexer().is(AsmToken::Star)) {
1074 SMLoc Loc = Parser.getTok().getLoc();
1075 Operands.push_back(X86Operand::CreateToken("*", Loc));
1076 Parser.Lex(); // Eat the star.
1079 // Read the first operand.
1080 if (X86Operand *Op = ParseOperand())
1081 Operands.push_back(Op);
1083 Parser.EatToEndOfStatement();
1087 while (getLexer().is(AsmToken::Comma)) {
1088 Parser.Lex(); // Eat the comma.
1090 // Parse and remember the operand.
1091 if (X86Operand *Op = ParseOperand())
1092 Operands.push_back(Op);
1094 Parser.EatToEndOfStatement();
1099 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1100 SMLoc Loc = getLexer().getLoc();
1101 Parser.EatToEndOfStatement();
1102 return Error(Loc, "unexpected token in argument list");
1106 if (getLexer().is(AsmToken::EndOfStatement))
1107 Parser.Lex(); // Consume the EndOfStatement
1108 else if (isPrefix && getLexer().is(AsmToken::Slash))
1109 Parser.Lex(); // Consume the prefix separator Slash
1111 if (ExtraImmOp && isParsingIntelSyntax())
1112 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1114 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1115 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1116 // documented form in various unofficial manuals, so a lot of code uses it.
1117 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1118 Operands.size() == 3) {
1119 X86Operand &Op = *(X86Operand*)Operands.back();
1120 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1121 isa<MCConstantExpr>(Op.Mem.Disp) &&
1122 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1123 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1124 SMLoc Loc = Op.getEndLoc();
1125 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1129 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1130 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1131 Operands.size() == 3) {
1132 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1133 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1134 isa<MCConstantExpr>(Op.Mem.Disp) &&
1135 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1136 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1137 SMLoc Loc = Op.getEndLoc();
1138 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1142 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1143 if (Name.startswith("ins") && Operands.size() == 3 &&
1144 (Name == "insb" || Name == "insw" || Name == "insl")) {
1145 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1146 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1147 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1148 Operands.pop_back();
1149 Operands.pop_back();
1155 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1156 if (Name.startswith("outs") && Operands.size() == 3 &&
1157 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1158 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1159 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1160 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1161 Operands.pop_back();
1162 Operands.pop_back();
1168 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1169 if (Name.startswith("movs") && Operands.size() == 3 &&
1170 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1171 (is64BitMode() && Name == "movsq"))) {
1172 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1173 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1174 if (isSrcOp(Op) && isDstOp(Op2)) {
1175 Operands.pop_back();
1176 Operands.pop_back();
1181 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1182 if (Name.startswith("lods") && Operands.size() == 3 &&
1183 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1184 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1185 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1186 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1187 if (isSrcOp(*Op1) && Op2->isReg()) {
1189 unsigned reg = Op2->getReg();
1190 bool isLods = Name == "lods";
1191 if (reg == X86::AL && (isLods || Name == "lodsb"))
1193 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1195 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1197 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1202 Operands.pop_back();
1203 Operands.pop_back();
1207 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1211 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1212 if (Name.startswith("stos") && Operands.size() == 3 &&
1213 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1214 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1215 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1216 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1217 if (isDstOp(*Op2) && Op1->isReg()) {
1219 unsigned reg = Op1->getReg();
1220 bool isStos = Name == "stos";
1221 if (reg == X86::AL && (isStos || Name == "stosb"))
1223 else if (reg == X86::AX && (isStos || Name == "stosw"))
1225 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1227 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1232 Operands.pop_back();
1233 Operands.pop_back();
1237 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1242 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1244 if ((Name.startswith("shr") || Name.startswith("sar") ||
1245 Name.startswith("shl") || Name.startswith("sal") ||
1246 Name.startswith("rcl") || Name.startswith("rcr") ||
1247 Name.startswith("rol") || Name.startswith("ror")) &&
1248 Operands.size() == 3) {
1249 if (isParsingIntelSyntax()) {
1251 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1252 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1253 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1255 Operands.pop_back();
1258 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1259 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1260 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1262 Operands.erase(Operands.begin() + 1);
1267 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1268 // instalias with an immediate operand yet.
1269 if (Name == "int" && Operands.size() == 2) {
1270 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1271 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1272 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1274 Operands.erase(Operands.begin() + 1);
1275 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1283 processInstruction(MCInst &Inst,
1284 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1285 switch (Inst.getOpcode()) {
1286 default: return false;
1287 case X86::AND16i16: {
1288 if (!Inst.getOperand(0).isImm() ||
1289 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1293 TmpInst.setOpcode(X86::AND16ri8);
1294 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1295 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1296 TmpInst.addOperand(Inst.getOperand(0));
1300 case X86::AND32i32: {
1301 if (!Inst.getOperand(0).isImm() ||
1302 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1306 TmpInst.setOpcode(X86::AND32ri8);
1307 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1308 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1309 TmpInst.addOperand(Inst.getOperand(0));
1313 case X86::AND64i32: {
1314 if (!Inst.getOperand(0).isImm() ||
1315 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1319 TmpInst.setOpcode(X86::AND64ri8);
1320 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1321 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1322 TmpInst.addOperand(Inst.getOperand(0));
1326 case X86::XOR16i16: {
1327 if (!Inst.getOperand(0).isImm() ||
1328 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1332 TmpInst.setOpcode(X86::XOR16ri8);
1333 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1334 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1335 TmpInst.addOperand(Inst.getOperand(0));
1339 case X86::XOR32i32: {
1340 if (!Inst.getOperand(0).isImm() ||
1341 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1345 TmpInst.setOpcode(X86::XOR32ri8);
1346 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1347 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1348 TmpInst.addOperand(Inst.getOperand(0));
1352 case X86::XOR64i32: {
1353 if (!Inst.getOperand(0).isImm() ||
1354 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1358 TmpInst.setOpcode(X86::XOR64ri8);
1359 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1360 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1361 TmpInst.addOperand(Inst.getOperand(0));
1365 case X86::OR16i16: {
1366 if (!Inst.getOperand(0).isImm() ||
1367 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1371 TmpInst.setOpcode(X86::OR16ri8);
1372 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1373 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1374 TmpInst.addOperand(Inst.getOperand(0));
1378 case X86::OR32i32: {
1379 if (!Inst.getOperand(0).isImm() ||
1380 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1384 TmpInst.setOpcode(X86::OR32ri8);
1385 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1386 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1387 TmpInst.addOperand(Inst.getOperand(0));
1391 case X86::OR64i32: {
1392 if (!Inst.getOperand(0).isImm() ||
1393 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1397 TmpInst.setOpcode(X86::OR64ri8);
1398 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1399 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1400 TmpInst.addOperand(Inst.getOperand(0));
1404 case X86::CMP16i16: {
1405 if (!Inst.getOperand(0).isImm() ||
1406 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1410 TmpInst.setOpcode(X86::CMP16ri8);
1411 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1412 TmpInst.addOperand(Inst.getOperand(0));
1416 case X86::CMP32i32: {
1417 if (!Inst.getOperand(0).isImm() ||
1418 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1422 TmpInst.setOpcode(X86::CMP32ri8);
1423 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1424 TmpInst.addOperand(Inst.getOperand(0));
1428 case X86::CMP64i32: {
1429 if (!Inst.getOperand(0).isImm() ||
1430 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1434 TmpInst.setOpcode(X86::CMP64ri8);
1435 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1436 TmpInst.addOperand(Inst.getOperand(0));
1440 case X86::ADD16i16: {
1441 if (!Inst.getOperand(0).isImm() ||
1442 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1446 TmpInst.setOpcode(X86::ADD16ri8);
1447 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1448 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1449 TmpInst.addOperand(Inst.getOperand(0));
1453 case X86::ADD32i32: {
1454 if (!Inst.getOperand(0).isImm() ||
1455 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1459 TmpInst.setOpcode(X86::ADD32ri8);
1460 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1461 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1462 TmpInst.addOperand(Inst.getOperand(0));
1466 case X86::ADD64i32: {
1467 if (!Inst.getOperand(0).isImm() ||
1468 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1472 TmpInst.setOpcode(X86::ADD64ri8);
1473 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1474 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1475 TmpInst.addOperand(Inst.getOperand(0));
1479 case X86::SUB16i16: {
1480 if (!Inst.getOperand(0).isImm() ||
1481 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1485 TmpInst.setOpcode(X86::SUB16ri8);
1486 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1487 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1488 TmpInst.addOperand(Inst.getOperand(0));
1492 case X86::SUB32i32: {
1493 if (!Inst.getOperand(0).isImm() ||
1494 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1498 TmpInst.setOpcode(X86::SUB32ri8);
1499 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1500 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1501 TmpInst.addOperand(Inst.getOperand(0));
1505 case X86::SUB64i32: {
1506 if (!Inst.getOperand(0).isImm() ||
1507 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1511 TmpInst.setOpcode(X86::SUB64ri8);
1512 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1513 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1514 TmpInst.addOperand(Inst.getOperand(0));
1522 MatchAndEmitInstruction(SMLoc IDLoc,
1523 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1527 bool Error = MatchInstruction(IDLoc, Operands, Out, Opcode, ErrorInfo);
1532 MatchInstruction(SMLoc IDLoc,
1533 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1534 MCStreamer &Out, unsigned &Opcode, unsigned &OrigErrorInfo,
1535 bool MatchingInlineAsm) {
1536 assert(!Operands.empty() && "Unexpect empty operand list!");
1537 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1538 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1539 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1541 // First, handle aliases that expand to multiple instructions.
1542 // FIXME: This should be replaced with a real .td file alias mechanism.
1543 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1545 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1546 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1547 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1548 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1550 Inst.setOpcode(X86::WAIT);
1552 if (!MatchingInlineAsm)
1553 Out.EmitInstruction(Inst);
1556 StringSwitch<const char*>(Op->getToken())
1557 .Case("finit", "fninit")
1558 .Case("fsave", "fnsave")
1559 .Case("fstcw", "fnstcw")
1560 .Case("fstcww", "fnstcw")
1561 .Case("fstenv", "fnstenv")
1562 .Case("fstsw", "fnstsw")
1563 .Case("fstsww", "fnstsw")
1564 .Case("fclex", "fnclex")
1566 assert(Repl && "Unknown wait-prefixed instruction");
1568 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1571 bool WasOriginallyInvalidOperand = false;
1574 // First, try a direct match.
1575 switch (MatchInstructionImpl(Operands, Inst,
1576 OrigErrorInfo, MatchingInlineAsm,
1577 isParsingIntelSyntax())) {
1580 // Some instructions need post-processing to, for example, tweak which
1581 // encoding is selected. Loop on it while changes happen so the
1582 // individual transformations can chain off each other.
1583 if (!MatchingInlineAsm)
1584 while (processInstruction(Inst, Operands))
1588 if (!MatchingInlineAsm)
1589 Out.EmitInstruction(Inst);
1590 Opcode = Inst.getOpcode();
1592 case Match_MissingFeature:
1593 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1594 EmptyRanges, MatchingInlineAsm);
1596 case Match_InvalidOperand:
1597 WasOriginallyInvalidOperand = true;
1599 case Match_MnemonicFail:
1603 // FIXME: Ideally, we would only attempt suffix matches for things which are
1604 // valid prefixes, and we could just infer the right unambiguous
1605 // type. However, that requires substantially more matcher support than the
1608 // Change the operand to point to a temporary token.
1609 StringRef Base = Op->getToken();
1610 SmallString<16> Tmp;
1613 Op->setTokenValue(Tmp.str());
1615 // If this instruction starts with an 'f', then it is a floating point stack
1616 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1617 // 80-bit floating point, which use the suffixes s,l,t respectively.
1619 // Otherwise, we assume that this may be an integer instruction, which comes
1620 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1621 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1623 // Check for the various suffix matches.
1624 Tmp[Base.size()] = Suffixes[0];
1625 unsigned ErrorInfoIgnore;
1626 unsigned Match1, Match2, Match3, Match4;
1628 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1629 isParsingIntelSyntax());
1630 Tmp[Base.size()] = Suffixes[1];
1631 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1632 isParsingIntelSyntax());
1633 Tmp[Base.size()] = Suffixes[2];
1634 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1635 isParsingIntelSyntax());
1636 Tmp[Base.size()] = Suffixes[3];
1637 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1638 isParsingIntelSyntax());
1640 // Restore the old token.
1641 Op->setTokenValue(Base);
1643 // If exactly one matched, then we treat that as a successful match (and the
1644 // instruction will already have been filled in correctly, since the failing
1645 // matches won't have modified it).
1646 unsigned NumSuccessfulMatches =
1647 (Match1 == Match_Success) + (Match2 == Match_Success) +
1648 (Match3 == Match_Success) + (Match4 == Match_Success);
1649 if (NumSuccessfulMatches == 1) {
1651 if (!MatchingInlineAsm)
1652 Out.EmitInstruction(Inst);
1653 Opcode = Inst.getOpcode();
1654 // FIXME: Handle the map and constraints.
1658 // Otherwise, the match failed, try to produce a decent error message.
1660 // If we had multiple suffix matches, then identify this as an ambiguous
1662 if (NumSuccessfulMatches > 1) {
1664 unsigned NumMatches = 0;
1665 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1666 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1667 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1668 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1670 SmallString<126> Msg;
1671 raw_svector_ostream OS(Msg);
1672 OS << "ambiguous instructions require an explicit suffix (could be ";
1673 for (unsigned i = 0; i != NumMatches; ++i) {
1676 if (i + 1 == NumMatches)
1678 OS << "'" << Base << MatchChars[i] << "'";
1681 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1685 // Okay, we know that none of the variants matched successfully.
1687 // If all of the instructions reported an invalid mnemonic, then the original
1688 // mnemonic was invalid.
1689 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1690 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1691 if (!WasOriginallyInvalidOperand) {
1692 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1694 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1695 Ranges, MatchingInlineAsm);
1698 // Recover location info for the operand if we know which was the problem.
1699 if (OrigErrorInfo != ~0U) {
1700 if (OrigErrorInfo >= Operands.size())
1701 return Error(IDLoc, "too few operands for instruction",
1702 EmptyRanges, MatchingInlineAsm);
1704 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1705 if (Operand->getStartLoc().isValid()) {
1706 SMRange OperandRange = Operand->getLocRange();
1707 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1708 OperandRange, MatchingInlineAsm);
1712 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1716 // If one instruction matched with a missing feature, report this as a
1718 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1719 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1720 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1721 EmptyRanges, MatchingInlineAsm);
1725 // If one instruction matched with an invalid operand, report this as an
1727 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1728 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1729 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1734 // If all of these were an outright failure, report it in a useless way.
1735 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1736 EmptyRanges, MatchingInlineAsm);
1741 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1742 StringRef IDVal = DirectiveID.getIdentifier();
1743 if (IDVal == ".word")
1744 return ParseDirectiveWord(2, DirectiveID.getLoc());
1745 else if (IDVal.startswith(".code"))
1746 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1747 else if (IDVal.startswith(".att_syntax")) {
1748 getParser().setAssemblerDialect(0);
1750 } else if (IDVal.startswith(".intel_syntax")) {
1751 getParser().setAssemblerDialect(1);
1752 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1753 if(Parser.getTok().getString() == "noprefix") {
1754 // FIXME : Handle noprefix
1764 /// ParseDirectiveWord
1765 /// ::= .word [ expression (, expression)* ]
1766 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1767 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1769 const MCExpr *Value;
1770 if (getParser().ParseExpression(Value))
1773 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1775 if (getLexer().is(AsmToken::EndOfStatement))
1778 // FIXME: Improve diagnostic.
1779 if (getLexer().isNot(AsmToken::Comma))
1780 return Error(L, "unexpected token in directive");
1789 /// ParseDirectiveCode
1790 /// ::= .code32 | .code64
1791 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1792 if (IDVal == ".code32") {
1794 if (is64BitMode()) {
1796 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1798 } else if (IDVal == ".code64") {
1800 if (!is64BitMode()) {
1802 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1805 return Error(L, "unexpected directive " + IDVal);
1812 extern "C" void LLVMInitializeX86AsmLexer();
1814 // Force static initialization.
1815 extern "C" void LLVMInitializeX86AsmParser() {
1816 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1817 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1818 LLVMInitializeX86AsmLexer();
1821 #define GET_REGISTER_MATCHER
1822 #define GET_MATCHER_IMPLEMENTATION
1823 #include "X86GenAsmMatcher.inc"