1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Support/raw_ostream.h"
33 class X86AsmParser : public MCTargetAsmParser {
37 MCAsmParser &getParser() const { return Parser; }
39 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
41 bool Error(SMLoc L, const Twine &Msg,
42 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
43 bool matchingInlineAsm = false) {
44 if (matchingInlineAsm) return true;
45 return Parser.Error(L, Msg, Ranges);
48 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
53 X86Operand *ParseOperand();
54 X86Operand *ParseATTOperand();
55 X86Operand *ParseIntelOperand();
56 X86Operand *ParseIntelMemOperand();
57 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
58 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
60 bool ParseDirectiveWord(unsigned Size, SMLoc L);
61 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
63 bool processInstruction(MCInst &Inst,
64 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
66 bool MatchAndEmitInstruction(SMLoc IDLoc,
67 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
70 bool MatchInstruction(SMLoc IDLoc, unsigned &Kind,
71 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
72 SmallVectorImpl<MCInst> &MCInsts,
73 unsigned &OrigErrorInfo,
74 bool matchingInlineAsm = false);
76 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
77 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
78 bool isSrcOp(X86Operand &Op);
80 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
81 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
82 bool isDstOp(X86Operand &Op);
84 bool is64BitMode() const {
85 // FIXME: Can tablegen auto-generate this?
86 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
89 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
90 setAvailableFeatures(FB);
93 /// @name Auto-generated Matcher Functions
96 #define GET_ASSEMBLER_HEADER
97 #include "X86GenAsmMatcher.inc"
102 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
103 : MCTargetAsmParser(), STI(sti), Parser(parser) {
105 // Initialize the set of available features.
106 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
108 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
110 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
111 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
113 virtual bool ParseDirective(AsmToken DirectiveID);
115 bool isParsingIntelSyntax() {
116 return getParser().getAssemblerDialect();
119 } // end anonymous namespace
121 /// @name Auto-generated Match Functions
124 static unsigned MatchRegisterName(StringRef Name);
128 static bool isImmSExti16i8Value(uint64_t Value) {
129 return (( Value <= 0x000000000000007FULL)||
130 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
131 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
134 static bool isImmSExti32i8Value(uint64_t Value) {
135 return (( Value <= 0x000000000000007FULL)||
136 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
137 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
140 static bool isImmZExtu32u8Value(uint64_t Value) {
141 return (Value <= 0x00000000000000FFULL);
144 static bool isImmSExti64i8Value(uint64_t Value) {
145 return (( Value <= 0x000000000000007FULL)||
146 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
149 static bool isImmSExti64i32Value(uint64_t Value) {
150 return (( Value <= 0x000000007FFFFFFFULL)||
151 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
155 /// X86Operand - Instances of this class represent a parsed X86 machine
157 struct X86Operand : public MCParsedAsmOperand {
165 SMLoc StartLoc, EndLoc;
191 X86Operand(KindTy K, SMLoc Start, SMLoc End)
192 : Kind(K), StartLoc(Start), EndLoc(End) {}
194 /// getStartLoc - Get the location of the first token of this operand.
195 SMLoc getStartLoc() const { return StartLoc; }
196 /// getEndLoc - Get the location of the last token of this operand.
197 SMLoc getEndLoc() const { return EndLoc; }
198 /// getLocRange - Get the range between the first and last token of this
200 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
202 virtual void print(raw_ostream &OS) const {}
204 StringRef getToken() const {
205 assert(Kind == Token && "Invalid access!");
206 return StringRef(Tok.Data, Tok.Length);
208 void setTokenValue(StringRef Value) {
209 assert(Kind == Token && "Invalid access!");
210 Tok.Data = Value.data();
211 Tok.Length = Value.size();
214 unsigned getReg() const {
215 assert(Kind == Register && "Invalid access!");
219 const MCExpr *getImm() const {
220 assert(Kind == Immediate && "Invalid access!");
224 const MCExpr *getMemDisp() const {
225 assert(Kind == Memory && "Invalid access!");
228 unsigned getMemSegReg() const {
229 assert(Kind == Memory && "Invalid access!");
232 unsigned getMemBaseReg() const {
233 assert(Kind == Memory && "Invalid access!");
236 unsigned getMemIndexReg() const {
237 assert(Kind == Memory && "Invalid access!");
240 unsigned getMemScale() const {
241 assert(Kind == Memory && "Invalid access!");
245 bool isToken() const {return Kind == Token; }
247 bool isImm() const { return Kind == Immediate; }
249 bool isImmSExti16i8() const {
253 // If this isn't a constant expr, just assume it fits and let relaxation
255 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
259 // Otherwise, check the value is in a range that makes sense for this
261 return isImmSExti16i8Value(CE->getValue());
263 bool isImmSExti32i8() const {
267 // If this isn't a constant expr, just assume it fits and let relaxation
269 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
273 // Otherwise, check the value is in a range that makes sense for this
275 return isImmSExti32i8Value(CE->getValue());
277 bool isImmZExtu32u8() const {
281 // If this isn't a constant expr, just assume it fits and let relaxation
283 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
287 // Otherwise, check the value is in a range that makes sense for this
289 return isImmZExtu32u8Value(CE->getValue());
291 bool isImmSExti64i8() const {
295 // If this isn't a constant expr, just assume it fits and let relaxation
297 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
301 // Otherwise, check the value is in a range that makes sense for this
303 return isImmSExti64i8Value(CE->getValue());
305 bool isImmSExti64i32() const {
309 // If this isn't a constant expr, just assume it fits and let relaxation
311 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
315 // Otherwise, check the value is in a range that makes sense for this
317 return isImmSExti64i32Value(CE->getValue());
320 bool isMem() const { return Kind == Memory; }
321 bool isMem8() const {
322 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
324 bool isMem16() const {
325 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
327 bool isMem32() const {
328 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
330 bool isMem64() const {
331 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
333 bool isMem80() const {
334 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
336 bool isMem128() const {
337 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
339 bool isMem256() const {
340 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
343 bool isMemVX32() const {
344 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
345 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
347 bool isMemVY32() const {
348 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
349 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
351 bool isMemVX64() const {
352 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
353 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
355 bool isMemVY64() const {
356 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
357 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
360 bool isAbsMem() const {
361 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
362 !getMemIndexReg() && getMemScale() == 1;
365 bool isReg() const { return Kind == Register; }
367 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
368 // Add as immediates when possible.
369 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
370 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
372 Inst.addOperand(MCOperand::CreateExpr(Expr));
375 void addRegOperands(MCInst &Inst, unsigned N) const {
376 assert(N == 1 && "Invalid number of operands!");
377 Inst.addOperand(MCOperand::CreateReg(getReg()));
380 void addImmOperands(MCInst &Inst, unsigned N) const {
381 assert(N == 1 && "Invalid number of operands!");
382 addExpr(Inst, getImm());
385 void addMem8Operands(MCInst &Inst, unsigned N) const {
386 addMemOperands(Inst, N);
388 void addMem16Operands(MCInst &Inst, unsigned N) const {
389 addMemOperands(Inst, N);
391 void addMem32Operands(MCInst &Inst, unsigned N) const {
392 addMemOperands(Inst, N);
394 void addMem64Operands(MCInst &Inst, unsigned N) const {
395 addMemOperands(Inst, N);
397 void addMem80Operands(MCInst &Inst, unsigned N) const {
398 addMemOperands(Inst, N);
400 void addMem128Operands(MCInst &Inst, unsigned N) const {
401 addMemOperands(Inst, N);
403 void addMem256Operands(MCInst &Inst, unsigned N) const {
404 addMemOperands(Inst, N);
406 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
407 addMemOperands(Inst, N);
409 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
410 addMemOperands(Inst, N);
412 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
413 addMemOperands(Inst, N);
415 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
416 addMemOperands(Inst, N);
419 void addMemOperands(MCInst &Inst, unsigned N) const {
420 assert((N == 5) && "Invalid number of operands!");
421 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
422 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
423 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
424 addExpr(Inst, getMemDisp());
425 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
428 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
429 assert((N == 1) && "Invalid number of operands!");
430 // Add as immediates when possible.
431 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
432 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
434 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
437 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
438 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
439 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
440 Res->Tok.Data = Str.data();
441 Res->Tok.Length = Str.size();
445 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
446 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
447 Res->Reg.RegNo = RegNo;
451 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
452 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
457 /// Create an absolute memory operand.
458 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
459 SMLoc EndLoc, unsigned Size = 0) {
460 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
462 Res->Mem.Disp = Disp;
463 Res->Mem.BaseReg = 0;
464 Res->Mem.IndexReg = 0;
466 Res->Mem.Size = Size;
470 /// Create a generalized memory operand.
471 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
472 unsigned BaseReg, unsigned IndexReg,
473 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
475 // We should never just have a displacement, that should be parsed as an
476 // absolute memory operand.
477 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
479 // The scale should always be one of {1,2,4,8}.
480 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
482 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
483 Res->Mem.SegReg = SegReg;
484 Res->Mem.Disp = Disp;
485 Res->Mem.BaseReg = BaseReg;
486 Res->Mem.IndexReg = IndexReg;
487 Res->Mem.Scale = Scale;
488 Res->Mem.Size = Size;
493 } // end anonymous namespace.
495 bool X86AsmParser::isSrcOp(X86Operand &Op) {
496 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
498 return (Op.isMem() &&
499 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
500 isa<MCConstantExpr>(Op.Mem.Disp) &&
501 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
502 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
505 bool X86AsmParser::isDstOp(X86Operand &Op) {
506 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
509 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
510 isa<MCConstantExpr>(Op.Mem.Disp) &&
511 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
512 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
515 bool X86AsmParser::ParseRegister(unsigned &RegNo,
516 SMLoc &StartLoc, SMLoc &EndLoc) {
518 const AsmToken &PercentTok = Parser.getTok();
519 StartLoc = PercentTok.getLoc();
521 // If we encounter a %, ignore it. This code handles registers with and
522 // without the prefix, unprefixed registers can occur in cfi directives.
523 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
524 Parser.Lex(); // Eat percent token.
526 const AsmToken &Tok = Parser.getTok();
527 if (Tok.isNot(AsmToken::Identifier)) {
528 if (isParsingIntelSyntax()) return true;
529 return Error(StartLoc, "invalid register name",
530 SMRange(StartLoc, Tok.getEndLoc()));
533 RegNo = MatchRegisterName(Tok.getString());
535 // If the match failed, try the register name as lowercase.
537 RegNo = MatchRegisterName(Tok.getString().lower());
539 if (!is64BitMode()) {
540 // FIXME: This should be done using Requires<In32BitMode> and
541 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
543 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
545 if (RegNo == X86::RIZ ||
546 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
547 X86II::isX86_64NonExtLowByteReg(RegNo) ||
548 X86II::isX86_64ExtendedReg(RegNo))
549 return Error(StartLoc, "register %"
550 + Tok.getString() + " is only available in 64-bit mode",
551 SMRange(StartLoc, Tok.getEndLoc()));
554 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
555 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
557 EndLoc = Tok.getLoc();
558 Parser.Lex(); // Eat 'st'
560 // Check to see if we have '(4)' after %st.
561 if (getLexer().isNot(AsmToken::LParen))
566 const AsmToken &IntTok = Parser.getTok();
567 if (IntTok.isNot(AsmToken::Integer))
568 return Error(IntTok.getLoc(), "expected stack index");
569 switch (IntTok.getIntVal()) {
570 case 0: RegNo = X86::ST0; break;
571 case 1: RegNo = X86::ST1; break;
572 case 2: RegNo = X86::ST2; break;
573 case 3: RegNo = X86::ST3; break;
574 case 4: RegNo = X86::ST4; break;
575 case 5: RegNo = X86::ST5; break;
576 case 6: RegNo = X86::ST6; break;
577 case 7: RegNo = X86::ST7; break;
578 default: return Error(IntTok.getLoc(), "invalid stack index");
581 if (getParser().Lex().isNot(AsmToken::RParen))
582 return Error(Parser.getTok().getLoc(), "expected ')'");
584 EndLoc = Tok.getLoc();
585 Parser.Lex(); // Eat ')'
589 // If this is "db[0-7]", match it as an alias
591 if (RegNo == 0 && Tok.getString().size() == 3 &&
592 Tok.getString().startswith("db")) {
593 switch (Tok.getString()[2]) {
594 case '0': RegNo = X86::DR0; break;
595 case '1': RegNo = X86::DR1; break;
596 case '2': RegNo = X86::DR2; break;
597 case '3': RegNo = X86::DR3; break;
598 case '4': RegNo = X86::DR4; break;
599 case '5': RegNo = X86::DR5; break;
600 case '6': RegNo = X86::DR6; break;
601 case '7': RegNo = X86::DR7; break;
605 EndLoc = Tok.getLoc();
606 Parser.Lex(); // Eat it.
612 if (isParsingIntelSyntax()) return true;
613 return Error(StartLoc, "invalid register name",
614 SMRange(StartLoc, Tok.getEndLoc()));
617 EndLoc = Tok.getEndLoc();
618 Parser.Lex(); // Eat identifier token.
622 X86Operand *X86AsmParser::ParseOperand() {
623 if (isParsingIntelSyntax())
624 return ParseIntelOperand();
625 return ParseATTOperand();
628 /// getIntelMemOperandSize - Return intel memory operand size.
629 static unsigned getIntelMemOperandSize(StringRef OpStr) {
630 unsigned Size = StringSwitch<unsigned>(OpStr)
631 .Cases("BYTE", "byte", 8)
632 .Cases("WORD", "word", 16)
633 .Cases("DWORD", "dword", 32)
634 .Cases("QWORD", "qword", 64)
635 .Cases("XWORD", "xword", 80)
636 .Cases("XMMWORD", "xmmword", 128)
637 .Cases("YMMWORD", "ymmword", 256)
642 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
644 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
645 SMLoc Start = Parser.getTok().getLoc(), End;
647 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
648 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
651 if (getLexer().isNot(AsmToken::LBrac))
652 return ErrorOperand(Start, "Expected '[' token!");
655 if (getLexer().is(AsmToken::Identifier)) {
657 if (ParseRegister(BaseReg, Start, End)) {
658 // Handle '[' 'symbol' ']'
659 if (getParser().ParseExpression(Disp, End)) return 0;
660 if (getLexer().isNot(AsmToken::RBrac))
661 return ErrorOperand(Start, "Expected ']' token!");
663 return X86Operand::CreateMem(Disp, Start, End, Size);
665 } else if (getLexer().is(AsmToken::Integer)) {
666 int64_t Val = Parser.getTok().getIntVal();
668 SMLoc Loc = Parser.getTok().getLoc();
669 if (getLexer().is(AsmToken::RBrac)) {
670 // Handle '[' number ']'
672 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
674 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
676 return X86Operand::CreateMem(Disp, Start, End, Size);
677 } else if (getLexer().is(AsmToken::Star)) {
678 // Handle '[' Scale*IndexReg ']'
680 SMLoc IdxRegLoc = Parser.getTok().getLoc();
681 if (ParseRegister(IndexReg, IdxRegLoc, End))
682 return ErrorOperand(IdxRegLoc, "Expected register");
685 return ErrorOperand(Loc, "Unexpected token");
688 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
689 bool isPlus = getLexer().is(AsmToken::Plus);
691 SMLoc PlusLoc = Parser.getTok().getLoc();
692 if (getLexer().is(AsmToken::Integer)) {
693 int64_t Val = Parser.getTok().getIntVal();
695 if (getLexer().is(AsmToken::Star)) {
697 SMLoc IdxRegLoc = Parser.getTok().getLoc();
698 if (ParseRegister(IndexReg, IdxRegLoc, End))
699 return ErrorOperand(IdxRegLoc, "Expected register");
701 } else if (getLexer().is(AsmToken::RBrac)) {
702 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
703 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
705 return ErrorOperand(PlusLoc, "unexpected token after +");
706 } else if (getLexer().is(AsmToken::Identifier)) {
707 // This could be an index register or a displacement expression.
708 End = Parser.getTok().getLoc();
710 ParseRegister(IndexReg, Start, End);
711 else if (getParser().ParseExpression(Disp, End)) return 0;
715 if (getLexer().isNot(AsmToken::RBrac))
716 if (getParser().ParseExpression(Disp, End)) return 0;
718 End = Parser.getTok().getLoc();
719 if (getLexer().isNot(AsmToken::RBrac))
720 return ErrorOperand(End, "expected ']' token!");
722 End = Parser.getTok().getLoc();
725 if (!BaseReg && !IndexReg)
726 return X86Operand::CreateMem(Disp, Start, End, Size);
728 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
732 /// ParseIntelMemOperand - Parse intel style memory operand.
733 X86Operand *X86AsmParser::ParseIntelMemOperand() {
734 const AsmToken &Tok = Parser.getTok();
735 SMLoc Start = Parser.getTok().getLoc(), End;
738 unsigned Size = getIntelMemOperandSize(Tok.getString());
741 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
742 "Unexpected token!");
746 if (getLexer().is(AsmToken::LBrac))
747 return ParseIntelBracExpression(SegReg, Size);
749 if (!ParseRegister(SegReg, Start, End)) {
750 // Handel SegReg : [ ... ]
751 if (getLexer().isNot(AsmToken::Colon))
752 return ErrorOperand(Start, "Expected ':' token!");
753 Parser.Lex(); // Eat :
754 if (getLexer().isNot(AsmToken::LBrac))
755 return ErrorOperand(Start, "Expected '[' token!");
756 return ParseIntelBracExpression(SegReg, Size);
759 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
760 if (getParser().ParseExpression(Disp, End)) return 0;
761 return X86Operand::CreateMem(Disp, Start, End, Size);
764 X86Operand *X86AsmParser::ParseIntelOperand() {
765 SMLoc Start = Parser.getTok().getLoc(), End;
768 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
769 getLexer().is(AsmToken::Minus)) {
771 if (!getParser().ParseExpression(Val, End)) {
772 End = Parser.getTok().getLoc();
773 return X86Operand::CreateImm(Val, Start, End);
779 if (!ParseRegister(RegNo, Start, End)) {
780 End = Parser.getTok().getLoc();
781 return X86Operand::CreateReg(RegNo, Start, End);
785 return ParseIntelMemOperand();
788 X86Operand *X86AsmParser::ParseATTOperand() {
789 switch (getLexer().getKind()) {
791 // Parse a memory operand with no segment register.
792 return ParseMemOperand(0, Parser.getTok().getLoc());
793 case AsmToken::Percent: {
794 // Read the register.
797 if (ParseRegister(RegNo, Start, End)) return 0;
798 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
799 Error(Start, "%eiz and %riz can only be used as index registers",
800 SMRange(Start, End));
804 // If this is a segment register followed by a ':', then this is the start
805 // of a memory reference, otherwise this is a normal register reference.
806 if (getLexer().isNot(AsmToken::Colon))
807 return X86Operand::CreateReg(RegNo, Start, End);
810 getParser().Lex(); // Eat the colon.
811 return ParseMemOperand(RegNo, Start);
813 case AsmToken::Dollar: {
815 SMLoc Start = Parser.getTok().getLoc(), End;
818 if (getParser().ParseExpression(Val, End))
820 return X86Operand::CreateImm(Val, Start, End);
825 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
826 /// has already been parsed if present.
827 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
829 // We have to disambiguate a parenthesized expression "(4+5)" from the start
830 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
831 // only way to do this without lookahead is to eat the '(' and see what is
833 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
834 if (getLexer().isNot(AsmToken::LParen)) {
836 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
838 // After parsing the base expression we could either have a parenthesized
839 // memory address or not. If not, return now. If so, eat the (.
840 if (getLexer().isNot(AsmToken::LParen)) {
841 // Unless we have a segment register, treat this as an immediate.
843 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
844 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
850 // Okay, we have a '('. We don't know if this is an expression or not, but
851 // so we have to eat the ( to see beyond it.
852 SMLoc LParenLoc = Parser.getTok().getLoc();
853 Parser.Lex(); // Eat the '('.
855 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
856 // Nothing to do here, fall into the code below with the '(' part of the
857 // memory operand consumed.
861 // It must be an parenthesized expression, parse it now.
862 if (getParser().ParseParenExpression(Disp, ExprEnd))
865 // After parsing the base expression we could either have a parenthesized
866 // memory address or not. If not, return now. If so, eat the (.
867 if (getLexer().isNot(AsmToken::LParen)) {
868 // Unless we have a segment register, treat this as an immediate.
870 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
871 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
879 // If we reached here, then we just ate the ( of the memory operand. Process
880 // the rest of the memory operand.
881 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
884 if (getLexer().is(AsmToken::Percent)) {
885 SMLoc StartLoc, EndLoc;
886 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
887 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
888 Error(StartLoc, "eiz and riz can only be used as index registers",
889 SMRange(StartLoc, EndLoc));
894 if (getLexer().is(AsmToken::Comma)) {
895 Parser.Lex(); // Eat the comma.
896 IndexLoc = Parser.getTok().getLoc();
898 // Following the comma we should have either an index register, or a scale
899 // value. We don't support the later form, but we want to parse it
902 // Not that even though it would be completely consistent to support syntax
903 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
904 if (getLexer().is(AsmToken::Percent)) {
906 if (ParseRegister(IndexReg, L, L)) return 0;
908 if (getLexer().isNot(AsmToken::RParen)) {
909 // Parse the scale amount:
910 // ::= ',' [scale-expression]
911 if (getLexer().isNot(AsmToken::Comma)) {
912 Error(Parser.getTok().getLoc(),
913 "expected comma in scale expression");
916 Parser.Lex(); // Eat the comma.
918 if (getLexer().isNot(AsmToken::RParen)) {
919 SMLoc Loc = Parser.getTok().getLoc();
922 if (getParser().ParseAbsoluteExpression(ScaleVal)){
923 Error(Loc, "expected scale expression");
927 // Validate the scale amount.
928 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
929 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
932 Scale = (unsigned)ScaleVal;
935 } else if (getLexer().isNot(AsmToken::RParen)) {
936 // A scale amount without an index is ignored.
938 SMLoc Loc = Parser.getTok().getLoc();
941 if (getParser().ParseAbsoluteExpression(Value))
945 Warning(Loc, "scale factor without index register is ignored");
950 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
951 if (getLexer().isNot(AsmToken::RParen)) {
952 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
955 SMLoc MemEnd = Parser.getTok().getLoc();
956 Parser.Lex(); // Eat the ')'.
958 // If we have both a base register and an index register make sure they are
959 // both 64-bit or 32-bit registers.
960 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
961 if (BaseReg != 0 && IndexReg != 0) {
962 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
963 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
964 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
965 IndexReg != X86::RIZ) {
966 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
969 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
970 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
971 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
972 IndexReg != X86::EIZ){
973 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
978 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
983 ParseInstruction(StringRef Name, SMLoc NameLoc,
984 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
985 StringRef PatchedName = Name;
987 // FIXME: Hack to recognize setneb as setne.
988 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
989 PatchedName != "setb" && PatchedName != "setnb")
990 PatchedName = PatchedName.substr(0, Name.size()-1);
992 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
993 const MCExpr *ExtraImmOp = 0;
994 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
995 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
996 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
997 bool IsVCMP = PatchedName[0] == 'v';
998 unsigned SSECCIdx = IsVCMP ? 4 : 3;
999 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1000 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1004 .Case("unord", 0x03)
1009 /* AVX only from here */
1010 .Case("eq_uq", 0x08)
1013 .Case("false", 0x0B)
1014 .Case("neq_oq", 0x0C)
1018 .Case("eq_os", 0x10)
1019 .Case("lt_oq", 0x11)
1020 .Case("le_oq", 0x12)
1021 .Case("unord_s", 0x13)
1022 .Case("neq_us", 0x14)
1023 .Case("nlt_uq", 0x15)
1024 .Case("nle_uq", 0x16)
1025 .Case("ord_s", 0x17)
1026 .Case("eq_us", 0x18)
1027 .Case("nge_uq", 0x19)
1028 .Case("ngt_uq", 0x1A)
1029 .Case("false_os", 0x1B)
1030 .Case("neq_os", 0x1C)
1031 .Case("ge_oq", 0x1D)
1032 .Case("gt_oq", 0x1E)
1033 .Case("true_us", 0x1F)
1035 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1036 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1037 getParser().getContext());
1038 if (PatchedName.endswith("ss")) {
1039 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1040 } else if (PatchedName.endswith("sd")) {
1041 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1042 } else if (PatchedName.endswith("ps")) {
1043 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1045 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1046 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1051 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1053 if (ExtraImmOp && !isParsingIntelSyntax())
1054 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1056 // Determine whether this is an instruction prefix.
1058 Name == "lock" || Name == "rep" ||
1059 Name == "repe" || Name == "repz" ||
1060 Name == "repne" || Name == "repnz" ||
1061 Name == "rex64" || Name == "data16";
1064 // This does the actual operand parsing. Don't parse any more if we have a
1065 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1066 // just want to parse the "lock" as the first instruction and the "incl" as
1068 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1070 // Parse '*' modifier.
1071 if (getLexer().is(AsmToken::Star)) {
1072 SMLoc Loc = Parser.getTok().getLoc();
1073 Operands.push_back(X86Operand::CreateToken("*", Loc));
1074 Parser.Lex(); // Eat the star.
1077 // Read the first operand.
1078 if (X86Operand *Op = ParseOperand())
1079 Operands.push_back(Op);
1081 Parser.EatToEndOfStatement();
1085 while (getLexer().is(AsmToken::Comma)) {
1086 Parser.Lex(); // Eat the comma.
1088 // Parse and remember the operand.
1089 if (X86Operand *Op = ParseOperand())
1090 Operands.push_back(Op);
1092 Parser.EatToEndOfStatement();
1097 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1098 SMLoc Loc = getLexer().getLoc();
1099 Parser.EatToEndOfStatement();
1100 return Error(Loc, "unexpected token in argument list");
1104 if (getLexer().is(AsmToken::EndOfStatement))
1105 Parser.Lex(); // Consume the EndOfStatement
1106 else if (isPrefix && getLexer().is(AsmToken::Slash))
1107 Parser.Lex(); // Consume the prefix separator Slash
1109 if (ExtraImmOp && isParsingIntelSyntax())
1110 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1112 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1113 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1114 // documented form in various unofficial manuals, so a lot of code uses it.
1115 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1116 Operands.size() == 3) {
1117 X86Operand &Op = *(X86Operand*)Operands.back();
1118 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1119 isa<MCConstantExpr>(Op.Mem.Disp) &&
1120 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1121 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1122 SMLoc Loc = Op.getEndLoc();
1123 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1127 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1128 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1129 Operands.size() == 3) {
1130 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1131 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1132 isa<MCConstantExpr>(Op.Mem.Disp) &&
1133 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1134 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1135 SMLoc Loc = Op.getEndLoc();
1136 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1140 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1141 if (Name.startswith("ins") && Operands.size() == 3 &&
1142 (Name == "insb" || Name == "insw" || Name == "insl")) {
1143 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1144 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1145 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1146 Operands.pop_back();
1147 Operands.pop_back();
1153 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1154 if (Name.startswith("outs") && Operands.size() == 3 &&
1155 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1156 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1157 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1158 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1159 Operands.pop_back();
1160 Operands.pop_back();
1166 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1167 if (Name.startswith("movs") && Operands.size() == 3 &&
1168 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1169 (is64BitMode() && Name == "movsq"))) {
1170 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1171 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1172 if (isSrcOp(Op) && isDstOp(Op2)) {
1173 Operands.pop_back();
1174 Operands.pop_back();
1179 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1180 if (Name.startswith("lods") && Operands.size() == 3 &&
1181 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1182 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1183 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1184 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1185 if (isSrcOp(*Op1) && Op2->isReg()) {
1187 unsigned reg = Op2->getReg();
1188 bool isLods = Name == "lods";
1189 if (reg == X86::AL && (isLods || Name == "lodsb"))
1191 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1193 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1195 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1200 Operands.pop_back();
1201 Operands.pop_back();
1205 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1209 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1210 if (Name.startswith("stos") && Operands.size() == 3 &&
1211 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1212 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1213 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1214 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1215 if (isDstOp(*Op2) && Op1->isReg()) {
1217 unsigned reg = Op1->getReg();
1218 bool isStos = Name == "stos";
1219 if (reg == X86::AL && (isStos || Name == "stosb"))
1221 else if (reg == X86::AX && (isStos || Name == "stosw"))
1223 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1225 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1230 Operands.pop_back();
1231 Operands.pop_back();
1235 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1240 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1242 if ((Name.startswith("shr") || Name.startswith("sar") ||
1243 Name.startswith("shl") || Name.startswith("sal") ||
1244 Name.startswith("rcl") || Name.startswith("rcr") ||
1245 Name.startswith("rol") || Name.startswith("ror")) &&
1246 Operands.size() == 3) {
1247 if (isParsingIntelSyntax()) {
1249 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1250 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1251 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1253 Operands.pop_back();
1256 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1257 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1258 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1260 Operands.erase(Operands.begin() + 1);
1265 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1266 // instalias with an immediate operand yet.
1267 if (Name == "int" && Operands.size() == 2) {
1268 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1269 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1270 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1272 Operands.erase(Operands.begin() + 1);
1273 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1281 processInstruction(MCInst &Inst,
1282 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1283 switch (Inst.getOpcode()) {
1284 default: return false;
1285 case X86::AND16i16: {
1286 if (!Inst.getOperand(0).isImm() ||
1287 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1291 TmpInst.setOpcode(X86::AND16ri8);
1292 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1293 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1294 TmpInst.addOperand(Inst.getOperand(0));
1298 case X86::AND32i32: {
1299 if (!Inst.getOperand(0).isImm() ||
1300 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1304 TmpInst.setOpcode(X86::AND32ri8);
1305 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1306 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1307 TmpInst.addOperand(Inst.getOperand(0));
1311 case X86::AND64i32: {
1312 if (!Inst.getOperand(0).isImm() ||
1313 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1317 TmpInst.setOpcode(X86::AND64ri8);
1318 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1319 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1320 TmpInst.addOperand(Inst.getOperand(0));
1324 case X86::XOR16i16: {
1325 if (!Inst.getOperand(0).isImm() ||
1326 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1330 TmpInst.setOpcode(X86::XOR16ri8);
1331 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1332 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1333 TmpInst.addOperand(Inst.getOperand(0));
1337 case X86::XOR32i32: {
1338 if (!Inst.getOperand(0).isImm() ||
1339 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1343 TmpInst.setOpcode(X86::XOR32ri8);
1344 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1345 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1346 TmpInst.addOperand(Inst.getOperand(0));
1350 case X86::XOR64i32: {
1351 if (!Inst.getOperand(0).isImm() ||
1352 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1356 TmpInst.setOpcode(X86::XOR64ri8);
1357 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1358 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1359 TmpInst.addOperand(Inst.getOperand(0));
1363 case X86::OR16i16: {
1364 if (!Inst.getOperand(0).isImm() ||
1365 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1369 TmpInst.setOpcode(X86::OR16ri8);
1370 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1371 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1372 TmpInst.addOperand(Inst.getOperand(0));
1376 case X86::OR32i32: {
1377 if (!Inst.getOperand(0).isImm() ||
1378 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1382 TmpInst.setOpcode(X86::OR32ri8);
1383 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1384 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1385 TmpInst.addOperand(Inst.getOperand(0));
1389 case X86::OR64i32: {
1390 if (!Inst.getOperand(0).isImm() ||
1391 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1395 TmpInst.setOpcode(X86::OR64ri8);
1396 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1397 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1398 TmpInst.addOperand(Inst.getOperand(0));
1402 case X86::CMP16i16: {
1403 if (!Inst.getOperand(0).isImm() ||
1404 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1408 TmpInst.setOpcode(X86::CMP16ri8);
1409 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1410 TmpInst.addOperand(Inst.getOperand(0));
1414 case X86::CMP32i32: {
1415 if (!Inst.getOperand(0).isImm() ||
1416 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1420 TmpInst.setOpcode(X86::CMP32ri8);
1421 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1422 TmpInst.addOperand(Inst.getOperand(0));
1426 case X86::CMP64i32: {
1427 if (!Inst.getOperand(0).isImm() ||
1428 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1432 TmpInst.setOpcode(X86::CMP64ri8);
1433 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1434 TmpInst.addOperand(Inst.getOperand(0));
1438 case X86::ADD16i16: {
1439 if (!Inst.getOperand(0).isImm() ||
1440 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1444 TmpInst.setOpcode(X86::ADD16ri8);
1445 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1446 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1447 TmpInst.addOperand(Inst.getOperand(0));
1451 case X86::ADD32i32: {
1452 if (!Inst.getOperand(0).isImm() ||
1453 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1457 TmpInst.setOpcode(X86::ADD32ri8);
1458 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1459 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1460 TmpInst.addOperand(Inst.getOperand(0));
1464 case X86::ADD64i32: {
1465 if (!Inst.getOperand(0).isImm() ||
1466 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1470 TmpInst.setOpcode(X86::ADD64ri8);
1471 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1472 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1473 TmpInst.addOperand(Inst.getOperand(0));
1477 case X86::SUB16i16: {
1478 if (!Inst.getOperand(0).isImm() ||
1479 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1483 TmpInst.setOpcode(X86::SUB16ri8);
1484 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1485 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1486 TmpInst.addOperand(Inst.getOperand(0));
1490 case X86::SUB32i32: {
1491 if (!Inst.getOperand(0).isImm() ||
1492 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1496 TmpInst.setOpcode(X86::SUB32ri8);
1497 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1498 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1499 TmpInst.addOperand(Inst.getOperand(0));
1503 case X86::SUB64i32: {
1504 if (!Inst.getOperand(0).isImm() ||
1505 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1509 TmpInst.setOpcode(X86::SUB64ri8);
1510 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1511 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1512 TmpInst.addOperand(Inst.getOperand(0));
1520 MatchAndEmitInstruction(SMLoc IDLoc,
1521 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1525 SmallVector<MCInst, 2> Insts;
1527 bool Error = MatchInstruction(IDLoc, Kind, Operands, Insts,
1530 for (unsigned i = 0, e = Insts.size(); i != e; ++i)
1531 Out.EmitInstruction(Insts[i]);
1536 MatchInstruction(SMLoc IDLoc, unsigned &Kind,
1537 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1538 SmallVectorImpl<MCInst> &MCInsts, unsigned &OrigErrorInfo,
1539 bool matchingInlineAsm) {
1540 assert(!Operands.empty() && "Unexpect empty operand list!");
1541 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1542 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1543 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1545 // First, handle aliases that expand to multiple instructions.
1546 // FIXME: This should be replaced with a real .td file alias mechanism.
1547 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1549 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1550 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1551 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1552 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1554 Inst.setOpcode(X86::WAIT);
1556 MCInsts.push_back(Inst);
1559 StringSwitch<const char*>(Op->getToken())
1560 .Case("finit", "fninit")
1561 .Case("fsave", "fnsave")
1562 .Case("fstcw", "fnstcw")
1563 .Case("fstcww", "fnstcw")
1564 .Case("fstenv", "fnstenv")
1565 .Case("fstsw", "fnstsw")
1566 .Case("fstsww", "fnstsw")
1567 .Case("fclex", "fnclex")
1569 assert(Repl && "Unknown wait-prefixed instruction");
1571 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1574 bool WasOriginallyInvalidOperand = false;
1577 // First, try a direct match.
1578 switch (MatchInstructionImpl(Operands, Kind, Inst, OrigErrorInfo,
1579 isParsingIntelSyntax())) {
1582 // Some instructions need post-processing to, for example, tweak which
1583 // encoding is selected. Loop on it while changes happen so the
1584 // individual transformations can chain off each other.
1585 while (processInstruction(Inst, Operands))
1589 MCInsts.push_back(Inst);
1591 case Match_MissingFeature:
1592 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1593 EmptyRanges, matchingInlineAsm);
1595 case Match_InvalidOperand:
1596 WasOriginallyInvalidOperand = true;
1598 case Match_MnemonicFail:
1602 // FIXME: Ideally, we would only attempt suffix matches for things which are
1603 // valid prefixes, and we could just infer the right unambiguous
1604 // type. However, that requires substantially more matcher support than the
1607 // Change the operand to point to a temporary token.
1608 StringRef Base = Op->getToken();
1609 SmallString<16> Tmp;
1612 Op->setTokenValue(Tmp.str());
1614 // If this instruction starts with an 'f', then it is a floating point stack
1615 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1616 // 80-bit floating point, which use the suffixes s,l,t respectively.
1618 // Otherwise, we assume that this may be an integer instruction, which comes
1619 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1620 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1622 // Check for the various suffix matches.
1623 Tmp[Base.size()] = Suffixes[0];
1624 unsigned ErrorInfoIgnore;
1625 unsigned Match1, Match2, Match3, Match4;
1628 Match1 = MatchInstructionImpl(Operands, tKind, Inst, ErrorInfoIgnore);
1629 if (Match1 == Match_Success) Kind = tKind;
1630 Tmp[Base.size()] = Suffixes[1];
1631 Match2 = MatchInstructionImpl(Operands, tKind, Inst, ErrorInfoIgnore);
1632 if (Match2 == Match_Success) Kind = tKind;
1633 Tmp[Base.size()] = Suffixes[2];
1634 Match3 = MatchInstructionImpl(Operands, tKind, Inst, ErrorInfoIgnore);
1635 if (Match3 == Match_Success) Kind = tKind;
1636 Tmp[Base.size()] = Suffixes[3];
1637 Match4 = MatchInstructionImpl(Operands, tKind, Inst, ErrorInfoIgnore);
1638 if (Match4 == Match_Success) Kind = tKind;
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 MCInsts.push_back(Inst);
1655 // Otherwise, the match failed, try to produce a decent error message.
1657 // If we had multiple suffix matches, then identify this as an ambiguous
1659 if (NumSuccessfulMatches > 1) {
1661 unsigned NumMatches = 0;
1662 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1663 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1664 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1665 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1667 SmallString<126> Msg;
1668 raw_svector_ostream OS(Msg);
1669 OS << "ambiguous instructions require an explicit suffix (could be ";
1670 for (unsigned i = 0; i != NumMatches; ++i) {
1673 if (i + 1 == NumMatches)
1675 OS << "'" << Base << MatchChars[i] << "'";
1678 Error(IDLoc, OS.str(), EmptyRanges, matchingInlineAsm);
1682 // Okay, we know that none of the variants matched successfully.
1684 // If all of the instructions reported an invalid mnemonic, then the original
1685 // mnemonic was invalid.
1686 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1687 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1688 if (!WasOriginallyInvalidOperand) {
1689 ArrayRef<SMRange> Ranges = matchingInlineAsm ? EmptyRanges :
1691 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1692 Ranges, matchingInlineAsm);
1695 // Recover location info for the operand if we know which was the problem.
1696 if (OrigErrorInfo != ~0U) {
1697 if (OrigErrorInfo >= Operands.size())
1698 return Error(IDLoc, "too few operands for instruction",
1699 EmptyRanges, matchingInlineAsm);
1701 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1702 if (Operand->getStartLoc().isValid()) {
1703 SMRange OperandRange = Operand->getLocRange();
1704 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1705 OperandRange, matchingInlineAsm);
1709 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1713 // If one instruction matched with a missing feature, report this as a
1715 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1716 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1717 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1718 EmptyRanges, matchingInlineAsm);
1722 // If one instruction matched with an invalid operand, report this as an
1724 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1725 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1726 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1731 // If all of these were an outright failure, report it in a useless way.
1732 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1733 EmptyRanges, matchingInlineAsm);
1738 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1739 StringRef IDVal = DirectiveID.getIdentifier();
1740 if (IDVal == ".word")
1741 return ParseDirectiveWord(2, DirectiveID.getLoc());
1742 else if (IDVal.startswith(".code"))
1743 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1744 else if (IDVal.startswith(".att_syntax")) {
1745 getParser().setAssemblerDialect(0);
1747 } else if (IDVal.startswith(".intel_syntax")) {
1748 getParser().setAssemblerDialect(1);
1749 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1750 if(Parser.getTok().getString() == "noprefix") {
1751 // FIXME : Handle noprefix
1761 /// ParseDirectiveWord
1762 /// ::= .word [ expression (, expression)* ]
1763 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1764 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1766 const MCExpr *Value;
1767 if (getParser().ParseExpression(Value))
1770 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1772 if (getLexer().is(AsmToken::EndOfStatement))
1775 // FIXME: Improve diagnostic.
1776 if (getLexer().isNot(AsmToken::Comma))
1777 return Error(L, "unexpected token in directive");
1786 /// ParseDirectiveCode
1787 /// ::= .code32 | .code64
1788 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1789 if (IDVal == ".code32") {
1791 if (is64BitMode()) {
1793 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1795 } else if (IDVal == ".code64") {
1797 if (!is64BitMode()) {
1799 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1802 return Error(L, "unexpected directive " + IDVal);
1809 extern "C" void LLVMInitializeX86AsmLexer();
1811 // Force static initialization.
1812 extern "C" void LLVMInitializeX86AsmParser() {
1813 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1814 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1815 LLVMInitializeX86AsmLexer();
1818 #define GET_REGISTER_MATCHER
1819 #define GET_MATCHER_IMPLEMENTATION
1820 #include "X86GenAsmMatcher.inc"