1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
34 class X86AsmParser : public MCTargetAsmParser {
38 MCAsmParser &getParser() const { return Parser; }
40 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
42 bool Error(SMLoc L, const Twine &Msg,
43 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) {
44 return Parser.Error(L, Msg, Ranges);
47 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
52 X86Operand *ParseOperand();
53 X86Operand *ParseATTOperand();
54 X86Operand *ParseIntelOperand();
55 X86Operand *ParseIntelMemOperand();
56 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
57 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
59 bool ParseDirectiveWord(unsigned Size, SMLoc L);
60 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
62 bool processInstruction(MCInst &Inst,
63 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
65 bool MatchAndEmitInstruction(SMLoc IDLoc,
66 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
69 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
70 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
71 bool isSrcOp(X86Operand &Op);
73 /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
74 /// or %es:(%edi) in 32bit mode.
75 bool isDstOp(X86Operand &Op);
77 bool is64BitMode() const {
78 // FIXME: Can tablegen auto-generate this?
79 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
82 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
83 setAvailableFeatures(FB);
86 /// @name Auto-generated Matcher Functions
89 #define GET_ASSEMBLER_HEADER
90 #include "X86GenAsmMatcher.inc"
95 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
96 : MCTargetAsmParser(), STI(sti), Parser(parser) {
98 // Initialize the set of available features.
99 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
101 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
103 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
104 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
106 virtual bool ParseDirective(AsmToken DirectiveID);
108 bool isParsingIntelSyntax() {
109 return getParser().getAssemblerDialect();
112 } // end anonymous namespace
114 /// @name Auto-generated Match Functions
117 static unsigned MatchRegisterName(StringRef Name);
121 static bool isImmSExti16i8Value(uint64_t Value) {
122 return (( Value <= 0x000000000000007FULL)||
123 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
124 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
127 static bool isImmSExti32i8Value(uint64_t Value) {
128 return (( Value <= 0x000000000000007FULL)||
129 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
130 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
133 static bool isImmZExtu32u8Value(uint64_t Value) {
134 return (Value <= 0x00000000000000FFULL);
137 static bool isImmSExti64i8Value(uint64_t Value) {
138 return (( Value <= 0x000000000000007FULL)||
139 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
142 static bool isImmSExti64i32Value(uint64_t Value) {
143 return (( Value <= 0x000000007FFFFFFFULL)||
144 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
148 /// X86Operand - Instances of this class represent a parsed X86 machine
150 struct X86Operand : public MCParsedAsmOperand {
158 SMLoc StartLoc, EndLoc;
184 X86Operand(KindTy K, SMLoc Start, SMLoc End)
185 : Kind(K), StartLoc(Start), EndLoc(End) {}
187 /// getStartLoc - Get the location of the first token of this operand.
188 SMLoc getStartLoc() const { return StartLoc; }
189 /// getEndLoc - Get the location of the last token of this operand.
190 SMLoc getEndLoc() const { return EndLoc; }
192 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
194 virtual void print(raw_ostream &OS) const {}
196 StringRef getToken() const {
197 assert(Kind == Token && "Invalid access!");
198 return StringRef(Tok.Data, Tok.Length);
200 void setTokenValue(StringRef Value) {
201 assert(Kind == Token && "Invalid access!");
202 Tok.Data = Value.data();
203 Tok.Length = Value.size();
206 unsigned getReg() const {
207 assert(Kind == Register && "Invalid access!");
211 const MCExpr *getImm() const {
212 assert(Kind == Immediate && "Invalid access!");
216 const MCExpr *getMemDisp() const {
217 assert(Kind == Memory && "Invalid access!");
220 unsigned getMemSegReg() const {
221 assert(Kind == Memory && "Invalid access!");
224 unsigned getMemBaseReg() const {
225 assert(Kind == Memory && "Invalid access!");
228 unsigned getMemIndexReg() const {
229 assert(Kind == Memory && "Invalid access!");
232 unsigned getMemScale() const {
233 assert(Kind == Memory && "Invalid access!");
237 bool isToken() const {return Kind == Token; }
239 bool isImm() const { return Kind == Immediate; }
241 bool isImmSExti16i8() const {
245 // If this isn't a constant expr, just assume it fits and let relaxation
247 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
251 // Otherwise, check the value is in a range that makes sense for this
253 return isImmSExti16i8Value(CE->getValue());
255 bool isImmSExti32i8() const {
259 // If this isn't a constant expr, just assume it fits and let relaxation
261 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
265 // Otherwise, check the value is in a range that makes sense for this
267 return isImmSExti32i8Value(CE->getValue());
269 bool isImmZExtu32u8() const {
273 // If this isn't a constant expr, just assume it fits and let relaxation
275 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
279 // Otherwise, check the value is in a range that makes sense for this
281 return isImmZExtu32u8Value(CE->getValue());
283 bool isImmSExti64i8() const {
287 // If this isn't a constant expr, just assume it fits and let relaxation
289 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
293 // Otherwise, check the value is in a range that makes sense for this
295 return isImmSExti64i8Value(CE->getValue());
297 bool isImmSExti64i32() const {
301 // If this isn't a constant expr, just assume it fits and let relaxation
303 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
307 // Otherwise, check the value is in a range that makes sense for this
309 return isImmSExti64i32Value(CE->getValue());
312 bool isMem() const { return Kind == Memory; }
313 bool isMem8() const {
314 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
316 bool isMem16() const {
317 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
319 bool isMem32() const {
320 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
322 bool isMem64() const {
323 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
325 bool isMem80() const {
326 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
328 bool isMem128() const {
329 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
331 bool isMem256() const {
332 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
335 bool isAbsMem() const {
336 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
337 !getMemIndexReg() && getMemScale() == 1;
340 bool isReg() const { return Kind == Register; }
342 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
343 // Add as immediates when possible.
344 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
345 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
347 Inst.addOperand(MCOperand::CreateExpr(Expr));
350 void addRegOperands(MCInst &Inst, unsigned N) const {
351 assert(N == 1 && "Invalid number of operands!");
352 Inst.addOperand(MCOperand::CreateReg(getReg()));
355 void addImmOperands(MCInst &Inst, unsigned N) const {
356 assert(N == 1 && "Invalid number of operands!");
357 addExpr(Inst, getImm());
360 void addMem8Operands(MCInst &Inst, unsigned N) const {
361 addMemOperands(Inst, N);
363 void addMem16Operands(MCInst &Inst, unsigned N) const {
364 addMemOperands(Inst, N);
366 void addMem32Operands(MCInst &Inst, unsigned N) const {
367 addMemOperands(Inst, N);
369 void addMem64Operands(MCInst &Inst, unsigned N) const {
370 addMemOperands(Inst, N);
372 void addMem80Operands(MCInst &Inst, unsigned N) const {
373 addMemOperands(Inst, N);
375 void addMem128Operands(MCInst &Inst, unsigned N) const {
376 addMemOperands(Inst, N);
378 void addMem256Operands(MCInst &Inst, unsigned N) const {
379 addMemOperands(Inst, N);
382 void addMemOperands(MCInst &Inst, unsigned N) const {
383 assert((N == 5) && "Invalid number of operands!");
384 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
385 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
386 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
387 addExpr(Inst, getMemDisp());
388 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
391 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
392 assert((N == 1) && "Invalid number of operands!");
393 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
396 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
397 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
398 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
399 Res->Tok.Data = Str.data();
400 Res->Tok.Length = Str.size();
404 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
405 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
406 Res->Reg.RegNo = RegNo;
410 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
411 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
416 /// Create an absolute memory operand.
417 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
418 SMLoc EndLoc, unsigned Size = 0) {
419 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
421 Res->Mem.Disp = Disp;
422 Res->Mem.BaseReg = 0;
423 Res->Mem.IndexReg = 0;
425 Res->Mem.Size = Size;
429 /// Create a generalized memory operand.
430 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
431 unsigned BaseReg, unsigned IndexReg,
432 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
434 // We should never just have a displacement, that should be parsed as an
435 // absolute memory operand.
436 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
438 // The scale should always be one of {1,2,4,8}.
439 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
441 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
442 Res->Mem.SegReg = SegReg;
443 Res->Mem.Disp = Disp;
444 Res->Mem.BaseReg = BaseReg;
445 Res->Mem.IndexReg = IndexReg;
446 Res->Mem.Scale = Scale;
447 Res->Mem.Size = Size;
452 } // end anonymous namespace.
454 bool X86AsmParser::isSrcOp(X86Operand &Op) {
455 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
457 return (Op.isMem() &&
458 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
459 isa<MCConstantExpr>(Op.Mem.Disp) &&
460 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
461 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
464 bool X86AsmParser::isDstOp(X86Operand &Op) {
465 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
467 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
468 isa<MCConstantExpr>(Op.Mem.Disp) &&
469 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
470 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
473 bool X86AsmParser::ParseRegister(unsigned &RegNo,
474 SMLoc &StartLoc, SMLoc &EndLoc) {
476 if (!isParsingIntelSyntax()) {
477 const AsmToken &TokPercent = Parser.getTok();
478 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
479 StartLoc = TokPercent.getLoc();
480 Parser.Lex(); // Eat percent token.
483 const AsmToken &Tok = Parser.getTok();
484 if (Tok.isNot(AsmToken::Identifier)) {
485 if (isParsingIntelSyntax()) return true;
486 return Error(StartLoc, "invalid register name",
487 SMRange(StartLoc, Tok.getEndLoc()));
490 RegNo = MatchRegisterName(Tok.getString());
492 // If the match failed, try the register name as lowercase.
494 RegNo = MatchRegisterName(Tok.getString().lower());
496 if (!is64BitMode()) {
497 // FIXME: This should be done using Requires<In32BitMode> and
498 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
500 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
502 if (RegNo == X86::RIZ ||
503 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
504 X86II::isX86_64NonExtLowByteReg(RegNo) ||
505 X86II::isX86_64ExtendedReg(RegNo))
506 return Error(StartLoc, "register %"
507 + Tok.getString() + " is only available in 64-bit mode",
508 SMRange(StartLoc, Tok.getEndLoc()));
511 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
512 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
514 EndLoc = Tok.getLoc();
515 Parser.Lex(); // Eat 'st'
517 // Check to see if we have '(4)' after %st.
518 if (getLexer().isNot(AsmToken::LParen))
523 const AsmToken &IntTok = Parser.getTok();
524 if (IntTok.isNot(AsmToken::Integer))
525 return Error(IntTok.getLoc(), "expected stack index");
526 switch (IntTok.getIntVal()) {
527 case 0: RegNo = X86::ST0; break;
528 case 1: RegNo = X86::ST1; break;
529 case 2: RegNo = X86::ST2; break;
530 case 3: RegNo = X86::ST3; break;
531 case 4: RegNo = X86::ST4; break;
532 case 5: RegNo = X86::ST5; break;
533 case 6: RegNo = X86::ST6; break;
534 case 7: RegNo = X86::ST7; break;
535 default: return Error(IntTok.getLoc(), "invalid stack index");
538 if (getParser().Lex().isNot(AsmToken::RParen))
539 return Error(Parser.getTok().getLoc(), "expected ')'");
541 EndLoc = Tok.getLoc();
542 Parser.Lex(); // Eat ')'
546 // If this is "db[0-7]", match it as an alias
548 if (RegNo == 0 && Tok.getString().size() == 3 &&
549 Tok.getString().startswith("db")) {
550 switch (Tok.getString()[2]) {
551 case '0': RegNo = X86::DR0; break;
552 case '1': RegNo = X86::DR1; break;
553 case '2': RegNo = X86::DR2; break;
554 case '3': RegNo = X86::DR3; break;
555 case '4': RegNo = X86::DR4; break;
556 case '5': RegNo = X86::DR5; break;
557 case '6': RegNo = X86::DR6; break;
558 case '7': RegNo = X86::DR7; break;
562 EndLoc = Tok.getLoc();
563 Parser.Lex(); // Eat it.
569 if (isParsingIntelSyntax()) return true;
570 return Error(StartLoc, "invalid register name",
571 SMRange(StartLoc, Tok.getEndLoc()));
574 EndLoc = Tok.getEndLoc();
575 Parser.Lex(); // Eat identifier token.
579 X86Operand *X86AsmParser::ParseOperand() {
580 if (isParsingIntelSyntax())
581 return ParseIntelOperand();
582 return ParseATTOperand();
585 /// getIntelMemOperandSize - Return intel memory operand size.
586 static unsigned getIntelMemOperandSize(StringRef OpStr) {
588 if (OpStr == "BYTE") Size = 8;
589 if (OpStr == "WORD") Size = 16;
590 if (OpStr == "DWORD") Size = 32;
591 if (OpStr == "QWORD") Size = 64;
592 if (OpStr == "XWORD") Size = 80;
593 if (OpStr == "XMMWORD") Size = 128;
594 if (OpStr == "YMMWORD") Size = 256;
598 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
600 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
601 SMLoc Start = Parser.getTok().getLoc(), End;
603 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
604 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
607 if (getLexer().isNot(AsmToken::LBrac))
608 return ErrorOperand(Start, "Expected '[' token!");
611 if (getLexer().is(AsmToken::Identifier)) {
613 if (ParseRegister(BaseReg, Start, End)) {
614 // Handle '[' 'symbol' ']'
615 if (getParser().ParseExpression(Disp, End)) return 0;
616 if (getLexer().isNot(AsmToken::RBrac))
617 return ErrorOperand(Start, "Expected ']' token!");
619 return X86Operand::CreateMem(Disp, Start, End, Size);
621 } else if (getLexer().is(AsmToken::Integer)) {
622 int64_t Val = Parser.getTok().getIntVal();
624 SMLoc Loc = Parser.getTok().getLoc();
625 if (getLexer().is(AsmToken::RBrac)) {
626 // Handle '[' number ']'
628 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
630 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
632 return X86Operand::CreateMem(Disp, Start, End, Size);
633 } else if (getLexer().is(AsmToken::Star)) {
634 // Handle '[' Scale*IndexReg ']'
636 SMLoc IdxRegLoc = Parser.getTok().getLoc();
637 if (ParseRegister(IndexReg, IdxRegLoc, End))
638 return ErrorOperand(IdxRegLoc, "Expected register");
641 return ErrorOperand(Loc, "Unepxeted token");
644 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
645 bool isPlus = getLexer().is(AsmToken::Plus);
647 SMLoc PlusLoc = Parser.getTok().getLoc();
648 if (getLexer().is(AsmToken::Integer)) {
649 int64_t Val = Parser.getTok().getIntVal();
651 if (getLexer().is(AsmToken::Star)) {
653 SMLoc IdxRegLoc = Parser.getTok().getLoc();
654 if (ParseRegister(IndexReg, IdxRegLoc, End))
655 return ErrorOperand(IdxRegLoc, "Expected register");
657 } else if (getLexer().is(AsmToken::RBrac)) {
658 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
659 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
661 return ErrorOperand(PlusLoc, "unexpected token after +");
662 } else if (getLexer().is(AsmToken::Identifier)) {
663 // This could be an index register or a displacement expression.
664 End = Parser.getTok().getLoc();
666 ParseRegister(IndexReg, Start, End);
667 else if (getParser().ParseExpression(Disp, End)) return 0;
671 if (getLexer().isNot(AsmToken::RBrac))
672 if (getParser().ParseExpression(Disp, End)) return 0;
674 End = Parser.getTok().getLoc();
675 if (getLexer().isNot(AsmToken::RBrac))
676 return ErrorOperand(End, "expected ']' token!");
678 End = Parser.getTok().getLoc();
681 if (!BaseReg && !IndexReg)
682 return X86Operand::CreateMem(Disp, Start, End, Size);
684 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
688 /// ParseIntelMemOperand - Parse intel style memory operand.
689 X86Operand *X86AsmParser::ParseIntelMemOperand() {
690 const AsmToken &Tok = Parser.getTok();
691 SMLoc Start = Parser.getTok().getLoc(), End;
694 unsigned Size = getIntelMemOperandSize(Tok.getString());
697 assert (Tok.getString() == "PTR" && "Unexpected token!");
701 if (getLexer().is(AsmToken::LBrac))
702 return ParseIntelBracExpression(SegReg, Size);
704 if (!ParseRegister(SegReg, Start, End)) {
705 // Handel SegReg : [ ... ]
706 if (getLexer().isNot(AsmToken::Colon))
707 return ErrorOperand(Start, "Expected ':' token!");
708 Parser.Lex(); // Eat :
709 if (getLexer().isNot(AsmToken::LBrac))
710 return ErrorOperand(Start, "Expected '[' token!");
711 return ParseIntelBracExpression(SegReg, Size);
714 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
715 if (getParser().ParseExpression(Disp, End)) return 0;
716 return X86Operand::CreateMem(Disp, Start, End, Size);
719 X86Operand *X86AsmParser::ParseIntelOperand() {
720 SMLoc Start = Parser.getTok().getLoc(), End;
723 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
724 getLexer().is(AsmToken::Minus)) {
726 if (!getParser().ParseExpression(Val, End)) {
727 End = Parser.getTok().getLoc();
728 return X86Operand::CreateImm(Val, Start, End);
734 if (!ParseRegister(RegNo, Start, End)) {
735 End = Parser.getTok().getLoc();
736 return X86Operand::CreateReg(RegNo, Start, End);
740 return ParseIntelMemOperand();
743 X86Operand *X86AsmParser::ParseATTOperand() {
744 switch (getLexer().getKind()) {
746 // Parse a memory operand with no segment register.
747 return ParseMemOperand(0, Parser.getTok().getLoc());
748 case AsmToken::Percent: {
749 // Read the register.
752 if (ParseRegister(RegNo, Start, End)) return 0;
753 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
754 Error(Start, "%eiz and %riz can only be used as index registers",
755 SMRange(Start, End));
759 // If this is a segment register followed by a ':', then this is the start
760 // of a memory reference, otherwise this is a normal register reference.
761 if (getLexer().isNot(AsmToken::Colon))
762 return X86Operand::CreateReg(RegNo, Start, End);
765 getParser().Lex(); // Eat the colon.
766 return ParseMemOperand(RegNo, Start);
768 case AsmToken::Dollar: {
770 SMLoc Start = Parser.getTok().getLoc(), End;
773 if (getParser().ParseExpression(Val, End))
775 return X86Operand::CreateImm(Val, Start, End);
780 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
781 /// has already been parsed if present.
782 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
784 // We have to disambiguate a parenthesized expression "(4+5)" from the start
785 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
786 // only way to do this without lookahead is to eat the '(' and see what is
788 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
789 if (getLexer().isNot(AsmToken::LParen)) {
791 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
793 // After parsing the base expression we could either have a parenthesized
794 // memory address or not. If not, return now. If so, eat the (.
795 if (getLexer().isNot(AsmToken::LParen)) {
796 // Unless we have a segment register, treat this as an immediate.
798 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
799 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
805 // Okay, we have a '('. We don't know if this is an expression or not, but
806 // so we have to eat the ( to see beyond it.
807 SMLoc LParenLoc = Parser.getTok().getLoc();
808 Parser.Lex(); // Eat the '('.
810 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
811 // Nothing to do here, fall into the code below with the '(' part of the
812 // memory operand consumed.
816 // It must be an parenthesized expression, parse it now.
817 if (getParser().ParseParenExpression(Disp, ExprEnd))
820 // After parsing the base expression we could either have a parenthesized
821 // memory address or not. If not, return now. If so, eat the (.
822 if (getLexer().isNot(AsmToken::LParen)) {
823 // Unless we have a segment register, treat this as an immediate.
825 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
826 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
834 // If we reached here, then we just ate the ( of the memory operand. Process
835 // the rest of the memory operand.
836 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
838 if (getLexer().is(AsmToken::Percent)) {
839 SMLoc StartLoc, EndLoc;
840 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
841 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
842 Error(StartLoc, "eiz and riz can only be used as index registers",
843 SMRange(StartLoc, EndLoc));
848 if (getLexer().is(AsmToken::Comma)) {
849 Parser.Lex(); // Eat the comma.
851 // Following the comma we should have either an index register, or a scale
852 // value. We don't support the later form, but we want to parse it
855 // Not that even though it would be completely consistent to support syntax
856 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
857 if (getLexer().is(AsmToken::Percent)) {
859 if (ParseRegister(IndexReg, L, L)) return 0;
861 if (getLexer().isNot(AsmToken::RParen)) {
862 // Parse the scale amount:
863 // ::= ',' [scale-expression]
864 if (getLexer().isNot(AsmToken::Comma)) {
865 Error(Parser.getTok().getLoc(),
866 "expected comma in scale expression");
869 Parser.Lex(); // Eat the comma.
871 if (getLexer().isNot(AsmToken::RParen)) {
872 SMLoc Loc = Parser.getTok().getLoc();
875 if (getParser().ParseAbsoluteExpression(ScaleVal))
878 // Validate the scale amount.
879 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
880 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
883 Scale = (unsigned)ScaleVal;
886 } else if (getLexer().isNot(AsmToken::RParen)) {
887 // A scale amount without an index is ignored.
889 SMLoc Loc = Parser.getTok().getLoc();
892 if (getParser().ParseAbsoluteExpression(Value))
896 Warning(Loc, "scale factor without index register is ignored");
901 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
902 if (getLexer().isNot(AsmToken::RParen)) {
903 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
906 SMLoc MemEnd = Parser.getTok().getLoc();
907 Parser.Lex(); // Eat the ')'.
909 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
914 ParseInstruction(StringRef Name, SMLoc NameLoc,
915 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
916 StringRef PatchedName = Name;
918 // FIXME: Hack to recognize setneb as setne.
919 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
920 PatchedName != "setb" && PatchedName != "setnb")
921 PatchedName = PatchedName.substr(0, Name.size()-1);
923 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
924 const MCExpr *ExtraImmOp = 0;
925 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
926 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
927 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
928 bool IsVCMP = PatchedName.startswith("vcmp");
929 unsigned SSECCIdx = IsVCMP ? 4 : 3;
930 unsigned SSEComparisonCode = StringSwitch<unsigned>(
931 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
944 .Case("neq_oq", 0x0C)
951 .Case("unord_s", 0x13)
952 .Case("neq_us", 0x14)
953 .Case("nlt_uq", 0x15)
954 .Case("nle_uq", 0x16)
957 .Case("nge_uq", 0x19)
958 .Case("ngt_uq", 0x1A)
959 .Case("false_os", 0x1B)
960 .Case("neq_os", 0x1C)
963 .Case("true_us", 0x1F)
965 if (SSEComparisonCode != ~0U) {
966 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
967 getParser().getContext());
968 if (PatchedName.endswith("ss")) {
969 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
970 } else if (PatchedName.endswith("sd")) {
971 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
972 } else if (PatchedName.endswith("ps")) {
973 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
975 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
976 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
981 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
983 if (ExtraImmOp && !isParsingIntelSyntax())
984 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
986 // Determine whether this is an instruction prefix.
988 Name == "lock" || Name == "rep" ||
989 Name == "repe" || Name == "repz" ||
990 Name == "repne" || Name == "repnz" ||
991 Name == "rex64" || Name == "data16";
994 // This does the actual operand parsing. Don't parse any more if we have a
995 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
996 // just want to parse the "lock" as the first instruction and the "incl" as
998 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1000 // Parse '*' modifier.
1001 if (getLexer().is(AsmToken::Star)) {
1002 SMLoc Loc = Parser.getTok().getLoc();
1003 Operands.push_back(X86Operand::CreateToken("*", Loc));
1004 Parser.Lex(); // Eat the star.
1007 // Read the first operand.
1008 if (X86Operand *Op = ParseOperand())
1009 Operands.push_back(Op);
1011 Parser.EatToEndOfStatement();
1015 while (getLexer().is(AsmToken::Comma)) {
1016 Parser.Lex(); // Eat the comma.
1018 // Parse and remember the operand.
1019 if (X86Operand *Op = ParseOperand())
1020 Operands.push_back(Op);
1022 Parser.EatToEndOfStatement();
1027 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1028 SMLoc Loc = getLexer().getLoc();
1029 Parser.EatToEndOfStatement();
1030 return Error(Loc, "unexpected token in argument list");
1034 if (getLexer().is(AsmToken::EndOfStatement))
1035 Parser.Lex(); // Consume the EndOfStatement
1036 else if (isPrefix && getLexer().is(AsmToken::Slash))
1037 Parser.Lex(); // Consume the prefix separator Slash
1039 if (ExtraImmOp && isParsingIntelSyntax())
1040 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1042 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1043 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1044 // documented form in various unofficial manuals, so a lot of code uses it.
1045 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1046 Operands.size() == 3) {
1047 X86Operand &Op = *(X86Operand*)Operands.back();
1048 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1049 isa<MCConstantExpr>(Op.Mem.Disp) &&
1050 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1051 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1052 SMLoc Loc = Op.getEndLoc();
1053 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1057 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1058 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1059 Operands.size() == 3) {
1060 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1061 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1062 isa<MCConstantExpr>(Op.Mem.Disp) &&
1063 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1064 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1065 SMLoc Loc = Op.getEndLoc();
1066 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1070 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1071 if (Name.startswith("ins") && Operands.size() == 3 &&
1072 (Name == "insb" || Name == "insw" || Name == "insl")) {
1073 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1074 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1075 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1076 Operands.pop_back();
1077 Operands.pop_back();
1083 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1084 if (Name.startswith("outs") && Operands.size() == 3 &&
1085 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1086 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1087 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1088 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1089 Operands.pop_back();
1090 Operands.pop_back();
1096 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1097 if (Name.startswith("movs") && Operands.size() == 3 &&
1098 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1099 (is64BitMode() && Name == "movsq"))) {
1100 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1101 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1102 if (isSrcOp(Op) && isDstOp(Op2)) {
1103 Operands.pop_back();
1104 Operands.pop_back();
1109 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1110 if (Name.startswith("lods") && Operands.size() == 3 &&
1111 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1112 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1113 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1114 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1115 if (isSrcOp(*Op1) && Op2->isReg()) {
1117 unsigned reg = Op2->getReg();
1118 bool isLods = Name == "lods";
1119 if (reg == X86::AL && (isLods || Name == "lodsb"))
1121 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1123 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1125 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1130 Operands.pop_back();
1131 Operands.pop_back();
1135 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1139 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1140 if (Name.startswith("stos") && Operands.size() == 3 &&
1141 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1142 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1143 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1144 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1145 if (isDstOp(*Op2) && Op1->isReg()) {
1147 unsigned reg = Op1->getReg();
1148 bool isStos = Name == "stos";
1149 if (reg == X86::AL && (isStos || Name == "stosb"))
1151 else if (reg == X86::AX && (isStos || Name == "stosw"))
1153 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1155 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1160 Operands.pop_back();
1161 Operands.pop_back();
1165 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1170 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1172 if ((Name.startswith("shr") || Name.startswith("sar") ||
1173 Name.startswith("shl") || Name.startswith("sal") ||
1174 Name.startswith("rcl") || Name.startswith("rcr") ||
1175 Name.startswith("rol") || Name.startswith("ror")) &&
1176 Operands.size() == 3) {
1177 if (isParsingIntelSyntax()) {
1179 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1180 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1181 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1183 Operands.pop_back();
1186 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1187 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1188 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1190 Operands.erase(Operands.begin() + 1);
1195 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1196 // instalias with an immediate operand yet.
1197 if (Name == "int" && Operands.size() == 2) {
1198 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1199 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1200 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1202 Operands.erase(Operands.begin() + 1);
1203 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1211 processInstruction(MCInst &Inst,
1212 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1213 switch (Inst.getOpcode()) {
1214 default: return false;
1215 case X86::AND16i16: {
1216 if (!Inst.getOperand(0).isImm() ||
1217 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1221 TmpInst.setOpcode(X86::AND16ri8);
1222 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1223 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1224 TmpInst.addOperand(Inst.getOperand(0));
1228 case X86::AND32i32: {
1229 if (!Inst.getOperand(0).isImm() ||
1230 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1234 TmpInst.setOpcode(X86::AND32ri8);
1235 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1236 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1237 TmpInst.addOperand(Inst.getOperand(0));
1241 case X86::AND64i32: {
1242 if (!Inst.getOperand(0).isImm() ||
1243 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1247 TmpInst.setOpcode(X86::AND64ri8);
1248 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1249 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1250 TmpInst.addOperand(Inst.getOperand(0));
1254 case X86::XOR16i16: {
1255 if (!Inst.getOperand(0).isImm() ||
1256 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1260 TmpInst.setOpcode(X86::XOR16ri8);
1261 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1262 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1263 TmpInst.addOperand(Inst.getOperand(0));
1267 case X86::XOR32i32: {
1268 if (!Inst.getOperand(0).isImm() ||
1269 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1273 TmpInst.setOpcode(X86::XOR32ri8);
1274 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1275 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1276 TmpInst.addOperand(Inst.getOperand(0));
1280 case X86::XOR64i32: {
1281 if (!Inst.getOperand(0).isImm() ||
1282 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1286 TmpInst.setOpcode(X86::XOR64ri8);
1287 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1288 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1289 TmpInst.addOperand(Inst.getOperand(0));
1293 case X86::OR16i16: {
1294 if (!Inst.getOperand(0).isImm() ||
1295 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1299 TmpInst.setOpcode(X86::OR16ri8);
1300 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1301 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1302 TmpInst.addOperand(Inst.getOperand(0));
1306 case X86::OR32i32: {
1307 if (!Inst.getOperand(0).isImm() ||
1308 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1312 TmpInst.setOpcode(X86::OR32ri8);
1313 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1314 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1315 TmpInst.addOperand(Inst.getOperand(0));
1319 case X86::OR64i32: {
1320 if (!Inst.getOperand(0).isImm() ||
1321 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1325 TmpInst.setOpcode(X86::OR64ri8);
1326 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1327 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1328 TmpInst.addOperand(Inst.getOperand(0));
1332 case X86::CMP16i16: {
1333 if (!Inst.getOperand(0).isImm() ||
1334 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1338 TmpInst.setOpcode(X86::CMP16ri8);
1339 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1340 TmpInst.addOperand(Inst.getOperand(0));
1344 case X86::CMP32i32: {
1345 if (!Inst.getOperand(0).isImm() ||
1346 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1350 TmpInst.setOpcode(X86::CMP32ri8);
1351 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1352 TmpInst.addOperand(Inst.getOperand(0));
1356 case X86::CMP64i32: {
1357 if (!Inst.getOperand(0).isImm() ||
1358 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1362 TmpInst.setOpcode(X86::CMP64ri8);
1363 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1364 TmpInst.addOperand(Inst.getOperand(0));
1368 case X86::ADD16i16: {
1369 if (!Inst.getOperand(0).isImm() ||
1370 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1374 TmpInst.setOpcode(X86::ADD16ri8);
1375 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1376 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1377 TmpInst.addOperand(Inst.getOperand(0));
1381 case X86::ADD32i32: {
1382 if (!Inst.getOperand(0).isImm() ||
1383 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1387 TmpInst.setOpcode(X86::ADD32ri8);
1388 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1389 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1390 TmpInst.addOperand(Inst.getOperand(0));
1394 case X86::ADD64i32: {
1395 if (!Inst.getOperand(0).isImm() ||
1396 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1400 TmpInst.setOpcode(X86::ADD64ri8);
1401 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1402 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1403 TmpInst.addOperand(Inst.getOperand(0));
1407 case X86::SUB16i16: {
1408 if (!Inst.getOperand(0).isImm() ||
1409 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1413 TmpInst.setOpcode(X86::SUB16ri8);
1414 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1415 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1416 TmpInst.addOperand(Inst.getOperand(0));
1420 case X86::SUB32i32: {
1421 if (!Inst.getOperand(0).isImm() ||
1422 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1426 TmpInst.setOpcode(X86::SUB32ri8);
1427 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1428 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1429 TmpInst.addOperand(Inst.getOperand(0));
1433 case X86::SUB64i32: {
1434 if (!Inst.getOperand(0).isImm() ||
1435 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1439 TmpInst.setOpcode(X86::SUB64ri8);
1440 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1441 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1442 TmpInst.addOperand(Inst.getOperand(0));
1450 MatchAndEmitInstruction(SMLoc IDLoc,
1451 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1453 assert(!Operands.empty() && "Unexpect empty operand list!");
1454 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1455 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1457 // First, handle aliases that expand to multiple instructions.
1458 // FIXME: This should be replaced with a real .td file alias mechanism.
1459 // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
1461 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1462 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1463 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1464 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1466 Inst.setOpcode(X86::WAIT);
1468 Out.EmitInstruction(Inst);
1471 StringSwitch<const char*>(Op->getToken())
1472 .Case("finit", "fninit")
1473 .Case("fsave", "fnsave")
1474 .Case("fstcw", "fnstcw")
1475 .Case("fstcww", "fnstcw")
1476 .Case("fstenv", "fnstenv")
1477 .Case("fstsw", "fnstsw")
1478 .Case("fstsww", "fnstsw")
1479 .Case("fclex", "fnclex")
1481 assert(Repl && "Unknown wait-prefixed instruction");
1483 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1486 bool WasOriginallyInvalidOperand = false;
1487 unsigned OrigErrorInfo;
1490 // First, try a direct match.
1491 switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo,
1492 isParsingIntelSyntax())) {
1495 // Some instructions need post-processing to, for example, tweak which
1496 // encoding is selected. Loop on it while changes happen so the
1497 // individual transformations can chain off each other.
1498 while (processInstruction(Inst, Operands))
1502 Out.EmitInstruction(Inst);
1504 case Match_MissingFeature:
1505 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1507 case Match_ConversionFail:
1508 return Error(IDLoc, "unable to convert operands to instruction");
1509 case Match_InvalidOperand:
1510 WasOriginallyInvalidOperand = true;
1512 case Match_MnemonicFail:
1516 // FIXME: Ideally, we would only attempt suffix matches for things which are
1517 // valid prefixes, and we could just infer the right unambiguous
1518 // type. However, that requires substantially more matcher support than the
1521 // Change the operand to point to a temporary token.
1522 StringRef Base = Op->getToken();
1523 SmallString<16> Tmp;
1526 Op->setTokenValue(Tmp.str());
1528 // If this instruction starts with an 'f', then it is a floating point stack
1529 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1530 // 80-bit floating point, which use the suffixes s,l,t respectively.
1532 // Otherwise, we assume that this may be an integer instruction, which comes
1533 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1534 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1536 // Check for the various suffix matches.
1537 Tmp[Base.size()] = Suffixes[0];
1538 unsigned ErrorInfoIgnore;
1539 unsigned Match1, Match2, Match3, Match4;
1541 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1542 Tmp[Base.size()] = Suffixes[1];
1543 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1544 Tmp[Base.size()] = Suffixes[2];
1545 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1546 Tmp[Base.size()] = Suffixes[3];
1547 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
1549 // Restore the old token.
1550 Op->setTokenValue(Base);
1552 // If exactly one matched, then we treat that as a successful match (and the
1553 // instruction will already have been filled in correctly, since the failing
1554 // matches won't have modified it).
1555 unsigned NumSuccessfulMatches =
1556 (Match1 == Match_Success) + (Match2 == Match_Success) +
1557 (Match3 == Match_Success) + (Match4 == Match_Success);
1558 if (NumSuccessfulMatches == 1) {
1560 Out.EmitInstruction(Inst);
1564 // Otherwise, the match failed, try to produce a decent error message.
1566 // If we had multiple suffix matches, then identify this as an ambiguous
1568 if (NumSuccessfulMatches > 1) {
1570 unsigned NumMatches = 0;
1571 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1572 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1573 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1574 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1576 SmallString<126> Msg;
1577 raw_svector_ostream OS(Msg);
1578 OS << "ambiguous instructions require an explicit suffix (could be ";
1579 for (unsigned i = 0; i != NumMatches; ++i) {
1582 if (i + 1 == NumMatches)
1584 OS << "'" << Base << MatchChars[i] << "'";
1587 Error(IDLoc, OS.str());
1591 // Okay, we know that none of the variants matched successfully.
1593 // If all of the instructions reported an invalid mnemonic, then the original
1594 // mnemonic was invalid.
1595 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1596 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1597 if (!WasOriginallyInvalidOperand) {
1598 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1602 // Recover location info for the operand if we know which was the problem.
1603 if (OrigErrorInfo != ~0U) {
1604 if (OrigErrorInfo >= Operands.size())
1605 return Error(IDLoc, "too few operands for instruction");
1607 X86Operand *Operand = (X86Operand*)Operands[OrigErrorInfo];
1608 if (Operand->getStartLoc().isValid()) {
1609 SMRange OperandRange = Operand->getLocRange();
1610 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1615 return Error(IDLoc, "invalid operand for instruction");
1618 // If one instruction matched with a missing feature, report this as a
1620 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1621 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1622 Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1626 // If one instruction matched with an invalid operand, report this as an
1628 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1629 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1630 Error(IDLoc, "invalid operand for instruction");
1634 // If all of these were an outright failure, report it in a useless way.
1635 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
1640 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1641 StringRef IDVal = DirectiveID.getIdentifier();
1642 if (IDVal == ".word")
1643 return ParseDirectiveWord(2, DirectiveID.getLoc());
1644 else if (IDVal.startswith(".code"))
1645 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1646 else if (IDVal.startswith(".intel_syntax")) {
1647 getParser().setAssemblerDialect(1);
1648 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1649 if(Parser.getTok().getString() == "noprefix") {
1650 // FIXME : Handle noprefix
1660 /// ParseDirectiveWord
1661 /// ::= .word [ expression (, expression)* ]
1662 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1663 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1665 const MCExpr *Value;
1666 if (getParser().ParseExpression(Value))
1669 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1671 if (getLexer().is(AsmToken::EndOfStatement))
1674 // FIXME: Improve diagnostic.
1675 if (getLexer().isNot(AsmToken::Comma))
1676 return Error(L, "unexpected token in directive");
1685 /// ParseDirectiveCode
1686 /// ::= .code32 | .code64
1687 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1688 if (IDVal == ".code32") {
1690 if (is64BitMode()) {
1692 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1694 } else if (IDVal == ".code64") {
1696 if (!is64BitMode()) {
1698 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1701 return Error(L, "unexpected directive " + IDVal);
1708 extern "C" void LLVMInitializeX86AsmLexer();
1710 // Force static initialization.
1711 extern "C" void LLVMInitializeX86AsmParser() {
1712 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1713 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1714 LLVMInitializeX86AsmLexer();
1717 #define GET_REGISTER_MATCHER
1718 #define GET_MATCHER_IMPLEMENTATION
1719 #include "X86GenAsmMatcher.inc"