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 {
39 MCAsmParser &getParser() const { return Parser; }
41 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
43 bool Error(SMLoc L, const Twine &Msg,
44 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>()) {
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 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
71 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
72 bool isSrcOp(X86Operand &Op);
74 /// isDstOp - Returns true if operand is either %es:(%rdi) in 64bit mode
75 /// or %es:(%edi) in 32bit mode.
76 bool isDstOp(X86Operand &Op);
78 bool is64BitMode() const {
79 // FIXME: Can tablegen auto-generate this?
80 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
83 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
84 setAvailableFeatures(FB);
87 /// @name Auto-generated Matcher Functions
90 #define GET_ASSEMBLER_HEADER
91 #include "X86GenAsmMatcher.inc"
96 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
97 : MCTargetAsmParser(), STI(sti), Parser(parser), IntelSyntax(false) {
99 // Initialize the set of available features.
100 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
102 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
104 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
105 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
107 virtual bool ParseDirective(AsmToken DirectiveID);
109 bool isParsingIntelSyntax() {
110 return IntelSyntax || getParser().getAssemblerDialect();
113 } // end anonymous namespace
115 /// @name Auto-generated Match Functions
118 static unsigned MatchRegisterName(StringRef Name);
122 static bool isImmSExti16i8Value(uint64_t Value) {
123 return (( Value <= 0x000000000000007FULL)||
124 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
125 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
128 static bool isImmSExti32i8Value(uint64_t Value) {
129 return (( Value <= 0x000000000000007FULL)||
130 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
131 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
134 static bool isImmZExtu32u8Value(uint64_t Value) {
135 return (Value <= 0x00000000000000FFULL);
138 static bool isImmSExti64i8Value(uint64_t Value) {
139 return (( Value <= 0x000000000000007FULL)||
140 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
143 static bool isImmSExti64i32Value(uint64_t Value) {
144 return (( Value <= 0x000000007FFFFFFFULL)||
145 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
149 /// X86Operand - Instances of this class represent a parsed X86 machine
151 struct X86Operand : public MCParsedAsmOperand {
159 SMLoc StartLoc, EndLoc;
185 X86Operand(KindTy K, SMLoc Start, SMLoc End)
186 : Kind(K), StartLoc(Start), EndLoc(End) {}
188 /// getStartLoc - Get the location of the first token of this operand.
189 SMLoc getStartLoc() const { return StartLoc; }
190 /// getEndLoc - Get the location of the last token of this operand.
191 SMLoc getEndLoc() const { return EndLoc; }
193 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
195 virtual void print(raw_ostream &OS) const {}
197 StringRef getToken() const {
198 assert(Kind == Token && "Invalid access!");
199 return StringRef(Tok.Data, Tok.Length);
201 void setTokenValue(StringRef Value) {
202 assert(Kind == Token && "Invalid access!");
203 Tok.Data = Value.data();
204 Tok.Length = Value.size();
207 unsigned getReg() const {
208 assert(Kind == Register && "Invalid access!");
212 const MCExpr *getImm() const {
213 assert(Kind == Immediate && "Invalid access!");
217 const MCExpr *getMemDisp() const {
218 assert(Kind == Memory && "Invalid access!");
221 unsigned getMemSegReg() const {
222 assert(Kind == Memory && "Invalid access!");
225 unsigned getMemBaseReg() const {
226 assert(Kind == Memory && "Invalid access!");
229 unsigned getMemIndexReg() const {
230 assert(Kind == Memory && "Invalid access!");
233 unsigned getMemScale() const {
234 assert(Kind == Memory && "Invalid access!");
238 bool isToken() const {return Kind == Token; }
240 bool isImm() const { return Kind == Immediate; }
242 bool isImmSExti16i8() const {
246 // If this isn't a constant expr, just assume it fits and let relaxation
248 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
252 // Otherwise, check the value is in a range that makes sense for this
254 return isImmSExti16i8Value(CE->getValue());
256 bool isImmSExti32i8() const {
260 // If this isn't a constant expr, just assume it fits and let relaxation
262 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
266 // Otherwise, check the value is in a range that makes sense for this
268 return isImmSExti32i8Value(CE->getValue());
270 bool isImmZExtu32u8() const {
274 // If this isn't a constant expr, just assume it fits and let relaxation
276 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
280 // Otherwise, check the value is in a range that makes sense for this
282 return isImmZExtu32u8Value(CE->getValue());
284 bool isImmSExti64i8() const {
288 // If this isn't a constant expr, just assume it fits and let relaxation
290 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
294 // Otherwise, check the value is in a range that makes sense for this
296 return isImmSExti64i8Value(CE->getValue());
298 bool isImmSExti64i32() const {
302 // If this isn't a constant expr, just assume it fits and let relaxation
304 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
308 // Otherwise, check the value is in a range that makes sense for this
310 return isImmSExti64i32Value(CE->getValue());
313 bool isMem() const { return Kind == Memory; }
314 bool isMem8() const {
315 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
317 bool isMem16() const {
318 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
320 bool isMem32() const {
321 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
323 bool isMem64() const {
324 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
326 bool isMem80() const {
327 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
329 bool isMem128() const {
330 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
332 bool isMem256() const {
333 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
336 bool isAbsMem() const {
337 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
338 !getMemIndexReg() && getMemScale() == 1;
341 bool isReg() const { return Kind == Register; }
343 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
344 // Add as immediates when possible.
345 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
346 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
348 Inst.addOperand(MCOperand::CreateExpr(Expr));
351 void addRegOperands(MCInst &Inst, unsigned N) const {
352 assert(N == 1 && "Invalid number of operands!");
353 Inst.addOperand(MCOperand::CreateReg(getReg()));
356 void addImmOperands(MCInst &Inst, unsigned N) const {
357 assert(N == 1 && "Invalid number of operands!");
358 addExpr(Inst, getImm());
361 void addMem8Operands(MCInst &Inst, unsigned N) const {
362 addMemOperands(Inst, N);
364 void addMem16Operands(MCInst &Inst, unsigned N) const {
365 addMemOperands(Inst, N);
367 void addMem32Operands(MCInst &Inst, unsigned N) const {
368 addMemOperands(Inst, N);
370 void addMem64Operands(MCInst &Inst, unsigned N) const {
371 addMemOperands(Inst, N);
373 void addMem80Operands(MCInst &Inst, unsigned N) const {
374 addMemOperands(Inst, N);
376 void addMem128Operands(MCInst &Inst, unsigned N) const {
377 addMemOperands(Inst, N);
379 void addMem256Operands(MCInst &Inst, unsigned N) const {
380 addMemOperands(Inst, N);
383 void addMemOperands(MCInst &Inst, unsigned N) const {
384 assert((N == 5) && "Invalid number of operands!");
385 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
386 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
387 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
388 addExpr(Inst, getMemDisp());
389 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
392 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
393 assert((N == 1) && "Invalid number of operands!");
394 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
397 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
398 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
399 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
400 Res->Tok.Data = Str.data();
401 Res->Tok.Length = Str.size();
405 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
406 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
407 Res->Reg.RegNo = RegNo;
411 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
412 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
417 /// Create an absolute memory operand.
418 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
419 SMLoc EndLoc, unsigned Size = 0) {
420 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
422 Res->Mem.Disp = Disp;
423 Res->Mem.BaseReg = 0;
424 Res->Mem.IndexReg = 0;
426 Res->Mem.Size = Size;
430 /// Create a generalized memory operand.
431 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
432 unsigned BaseReg, unsigned IndexReg,
433 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
435 // We should never just have a displacement, that should be parsed as an
436 // absolute memory operand.
437 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
439 // The scale should always be one of {1,2,4,8}.
440 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
442 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
443 Res->Mem.SegReg = SegReg;
444 Res->Mem.Disp = Disp;
445 Res->Mem.BaseReg = BaseReg;
446 Res->Mem.IndexReg = IndexReg;
447 Res->Mem.Scale = Scale;
448 Res->Mem.Size = Size;
453 } // end anonymous namespace.
455 bool X86AsmParser::isSrcOp(X86Operand &Op) {
456 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
458 return (Op.isMem() &&
459 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
460 isa<MCConstantExpr>(Op.Mem.Disp) &&
461 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
462 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
465 bool X86AsmParser::isDstOp(X86Operand &Op) {
466 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
468 return Op.isMem() && Op.Mem.SegReg == X86::ES &&
469 isa<MCConstantExpr>(Op.Mem.Disp) &&
470 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
471 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
474 bool X86AsmParser::ParseRegister(unsigned &RegNo,
475 SMLoc &StartLoc, SMLoc &EndLoc) {
477 if (!isParsingIntelSyntax()) {
478 const AsmToken &TokPercent = Parser.getTok();
479 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
480 StartLoc = TokPercent.getLoc();
481 Parser.Lex(); // Eat percent token.
484 const AsmToken &Tok = Parser.getTok();
485 if (Tok.isNot(AsmToken::Identifier)) {
486 if (isParsingIntelSyntax()) return true;
487 return Error(StartLoc, "invalid register name",
488 SMRange(StartLoc, Tok.getEndLoc()));
491 RegNo = MatchRegisterName(Tok.getString());
493 // If the match failed, try the register name as lowercase.
495 RegNo = MatchRegisterName(Tok.getString().lower());
497 if (!is64BitMode()) {
498 // FIXME: This should be done using Requires<In32BitMode> and
499 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
501 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
503 if (RegNo == X86::RIZ ||
504 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
505 X86II::isX86_64NonExtLowByteReg(RegNo) ||
506 X86II::isX86_64ExtendedReg(RegNo))
507 return Error(StartLoc, "register %"
508 + Tok.getString() + " is only available in 64-bit mode",
509 SMRange(StartLoc, Tok.getEndLoc()));
512 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
513 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
515 EndLoc = Tok.getLoc();
516 Parser.Lex(); // Eat 'st'
518 // Check to see if we have '(4)' after %st.
519 if (getLexer().isNot(AsmToken::LParen))
524 const AsmToken &IntTok = Parser.getTok();
525 if (IntTok.isNot(AsmToken::Integer))
526 return Error(IntTok.getLoc(), "expected stack index");
527 switch (IntTok.getIntVal()) {
528 case 0: RegNo = X86::ST0; break;
529 case 1: RegNo = X86::ST1; break;
530 case 2: RegNo = X86::ST2; break;
531 case 3: RegNo = X86::ST3; break;
532 case 4: RegNo = X86::ST4; break;
533 case 5: RegNo = X86::ST5; break;
534 case 6: RegNo = X86::ST6; break;
535 case 7: RegNo = X86::ST7; break;
536 default: return Error(IntTok.getLoc(), "invalid stack index");
539 if (getParser().Lex().isNot(AsmToken::RParen))
540 return Error(Parser.getTok().getLoc(), "expected ')'");
542 EndLoc = Tok.getLoc();
543 Parser.Lex(); // Eat ')'
547 // If this is "db[0-7]", match it as an alias
549 if (RegNo == 0 && Tok.getString().size() == 3 &&
550 Tok.getString().startswith("db")) {
551 switch (Tok.getString()[2]) {
552 case '0': RegNo = X86::DR0; break;
553 case '1': RegNo = X86::DR1; break;
554 case '2': RegNo = X86::DR2; break;
555 case '3': RegNo = X86::DR3; break;
556 case '4': RegNo = X86::DR4; break;
557 case '5': RegNo = X86::DR5; break;
558 case '6': RegNo = X86::DR6; break;
559 case '7': RegNo = X86::DR7; break;
563 EndLoc = Tok.getLoc();
564 Parser.Lex(); // Eat it.
570 if (isParsingIntelSyntax()) return true;
571 return Error(StartLoc, "invalid register name",
572 SMRange(StartLoc, Tok.getEndLoc()));
575 EndLoc = Tok.getEndLoc();
576 Parser.Lex(); // Eat identifier token.
580 X86Operand *X86AsmParser::ParseOperand() {
581 if (isParsingIntelSyntax())
582 return ParseIntelOperand();
583 return ParseATTOperand();
586 /// getIntelMemOperandSize - Return intel memory operand size.
587 static unsigned getIntelMemOperandSize(StringRef OpStr) {
589 if (OpStr == "BYTE") Size = 8;
590 if (OpStr == "WORD") Size = 16;
591 if (OpStr == "DWORD") Size = 32;
592 if (OpStr == "QWORD") Size = 64;
593 if (OpStr == "XWORD") Size = 80;
594 if (OpStr == "XMMWORD") Size = 128;
595 if (OpStr == "YMMWORD") Size = 256;
599 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
601 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
602 SMLoc Start = Parser.getTok().getLoc(), End;
604 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
605 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
608 if (getLexer().isNot(AsmToken::LBrac))
609 return ErrorOperand(Start, "Expected '[' token!");
612 if (getLexer().is(AsmToken::Identifier)) {
614 if (ParseRegister(BaseReg, Start, End)) {
615 // Handle '[' 'symbol' ']'
616 if (getParser().ParseExpression(Disp, End)) return 0;
617 if (getLexer().isNot(AsmToken::RBrac))
618 return ErrorOperand(Start, "Expected ']' token!");
620 return X86Operand::CreateMem(Disp, Start, End, Size);
622 } else if (getLexer().is(AsmToken::Integer)) {
623 int64_t Val = Parser.getTok().getIntVal();
625 SMLoc Loc = Parser.getTok().getLoc();
626 if (getLexer().is(AsmToken::RBrac)) {
627 // Handle '[' number ']'
629 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
631 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
633 return X86Operand::CreateMem(Disp, Start, End, Size);
634 } else if (getLexer().is(AsmToken::Star)) {
635 // Handle '[' Scale*IndexReg ']'
637 SMLoc IdxRegLoc = Parser.getTok().getLoc();
638 if (ParseRegister(IndexReg, IdxRegLoc, End))
639 return ErrorOperand(IdxRegLoc, "Expected register");
642 return ErrorOperand(Loc, "Unepxeted token");
645 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
646 bool isPlus = getLexer().is(AsmToken::Plus);
648 SMLoc PlusLoc = Parser.getTok().getLoc();
649 if (getLexer().is(AsmToken::Integer)) {
650 int64_t Val = Parser.getTok().getIntVal();
652 if (getLexer().is(AsmToken::Star)) {
654 SMLoc IdxRegLoc = Parser.getTok().getLoc();
655 if (ParseRegister(IndexReg, IdxRegLoc, End))
656 return ErrorOperand(IdxRegLoc, "Expected register");
658 } else if (getLexer().is(AsmToken::RBrac)) {
659 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
660 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
662 return ErrorOperand(PlusLoc, "unexpected token after +");
663 } else if (getLexer().is(AsmToken::Identifier)) {
664 // This could be an index register or a displacement expression.
665 End = Parser.getTok().getLoc();
667 ParseRegister(IndexReg, Start, End);
668 else if (getParser().ParseExpression(Disp, End)) return 0;
672 if (getLexer().isNot(AsmToken::RBrac))
673 if (getParser().ParseExpression(Disp, End)) return 0;
675 End = Parser.getTok().getLoc();
676 if (getLexer().isNot(AsmToken::RBrac))
677 return ErrorOperand(End, "expected ']' token!");
679 End = Parser.getTok().getLoc();
682 if (!BaseReg && !IndexReg)
683 return X86Operand::CreateMem(Disp, Start, End, Size);
685 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
689 /// ParseIntelMemOperand - Parse intel style memory operand.
690 X86Operand *X86AsmParser::ParseIntelMemOperand() {
691 const AsmToken &Tok = Parser.getTok();
692 SMLoc Start = Parser.getTok().getLoc(), End;
695 unsigned Size = getIntelMemOperandSize(Tok.getString());
698 assert (Tok.getString() == "PTR" && "Unexpected token!");
702 if (getLexer().is(AsmToken::LBrac))
703 return ParseIntelBracExpression(SegReg, Size);
705 if (!ParseRegister(SegReg, Start, End)) {
706 // Handel SegReg : [ ... ]
707 if (getLexer().isNot(AsmToken::Colon))
708 return ErrorOperand(Start, "Expected ':' token!");
709 Parser.Lex(); // Eat :
710 if (getLexer().isNot(AsmToken::LBrac))
711 return ErrorOperand(Start, "Expected '[' token!");
712 return ParseIntelBracExpression(SegReg, Size);
715 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
716 if (getParser().ParseExpression(Disp, End)) return 0;
717 return X86Operand::CreateMem(Disp, Start, End, Size);
720 X86Operand *X86AsmParser::ParseIntelOperand() {
721 SMLoc Start = Parser.getTok().getLoc(), End;
724 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
725 getLexer().is(AsmToken::Minus)) {
727 if (!getParser().ParseExpression(Val, End)) {
728 End = Parser.getTok().getLoc();
729 return X86Operand::CreateImm(Val, Start, End);
735 if (!ParseRegister(RegNo, Start, End)) {
736 End = Parser.getTok().getLoc();
737 return X86Operand::CreateReg(RegNo, Start, End);
741 return ParseIntelMemOperand();
744 X86Operand *X86AsmParser::ParseATTOperand() {
745 switch (getLexer().getKind()) {
747 // Parse a memory operand with no segment register.
748 return ParseMemOperand(0, Parser.getTok().getLoc());
749 case AsmToken::Percent: {
750 // Read the register.
753 if (ParseRegister(RegNo, Start, End)) return 0;
754 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
755 Error(Start, "%eiz and %riz can only be used as index registers",
756 SMRange(Start, End));
760 // If this is a segment register followed by a ':', then this is the start
761 // of a memory reference, otherwise this is a normal register reference.
762 if (getLexer().isNot(AsmToken::Colon))
763 return X86Operand::CreateReg(RegNo, Start, End);
766 getParser().Lex(); // Eat the colon.
767 return ParseMemOperand(RegNo, Start);
769 case AsmToken::Dollar: {
771 SMLoc Start = Parser.getTok().getLoc(), End;
774 if (getParser().ParseExpression(Val, End))
776 return X86Operand::CreateImm(Val, Start, End);
781 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
782 /// has already been parsed if present.
783 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
785 // We have to disambiguate a parenthesized expression "(4+5)" from the start
786 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
787 // only way to do this without lookahead is to eat the '(' and see what is
789 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
790 if (getLexer().isNot(AsmToken::LParen)) {
792 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
794 // After parsing the base expression we could either have a parenthesized
795 // memory address or not. If not, return now. If so, eat the (.
796 if (getLexer().isNot(AsmToken::LParen)) {
797 // Unless we have a segment register, treat this as an immediate.
799 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
800 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
806 // Okay, we have a '('. We don't know if this is an expression or not, but
807 // so we have to eat the ( to see beyond it.
808 SMLoc LParenLoc = Parser.getTok().getLoc();
809 Parser.Lex(); // Eat the '('.
811 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
812 // Nothing to do here, fall into the code below with the '(' part of the
813 // memory operand consumed.
817 // It must be an parenthesized expression, parse it now.
818 if (getParser().ParseParenExpression(Disp, ExprEnd))
821 // After parsing the base expression we could either have a parenthesized
822 // memory address or not. If not, return now. If so, eat the (.
823 if (getLexer().isNot(AsmToken::LParen)) {
824 // Unless we have a segment register, treat this as an immediate.
826 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
827 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
835 // If we reached here, then we just ate the ( of the memory operand. Process
836 // the rest of the memory operand.
837 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
839 if (getLexer().is(AsmToken::Percent)) {
840 SMLoc StartLoc, EndLoc;
841 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
842 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
843 Error(StartLoc, "eiz and riz can only be used as index registers",
844 SMRange(StartLoc, EndLoc));
849 if (getLexer().is(AsmToken::Comma)) {
850 Parser.Lex(); // Eat the comma.
852 // Following the comma we should have either an index register, or a scale
853 // value. We don't support the later form, but we want to parse it
856 // Not that even though it would be completely consistent to support syntax
857 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
858 if (getLexer().is(AsmToken::Percent)) {
860 if (ParseRegister(IndexReg, L, L)) return 0;
862 if (getLexer().isNot(AsmToken::RParen)) {
863 // Parse the scale amount:
864 // ::= ',' [scale-expression]
865 if (getLexer().isNot(AsmToken::Comma)) {
866 Error(Parser.getTok().getLoc(),
867 "expected comma in scale expression");
870 Parser.Lex(); // Eat the comma.
872 if (getLexer().isNot(AsmToken::RParen)) {
873 SMLoc Loc = Parser.getTok().getLoc();
876 if (getParser().ParseAbsoluteExpression(ScaleVal))
879 // Validate the scale amount.
880 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
881 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
884 Scale = (unsigned)ScaleVal;
887 } else if (getLexer().isNot(AsmToken::RParen)) {
888 // A scale amount without an index is ignored.
890 SMLoc Loc = Parser.getTok().getLoc();
893 if (getParser().ParseAbsoluteExpression(Value))
897 Warning(Loc, "scale factor without index register is ignored");
902 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
903 if (getLexer().isNot(AsmToken::RParen)) {
904 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
907 SMLoc MemEnd = Parser.getTok().getLoc();
908 Parser.Lex(); // Eat the ')'.
910 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
915 ParseInstruction(StringRef Name, SMLoc NameLoc,
916 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
917 StringRef PatchedName = Name;
919 // FIXME: Hack to recognize setneb as setne.
920 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
921 PatchedName != "setb" && PatchedName != "setnb")
922 PatchedName = PatchedName.substr(0, Name.size()-1);
924 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
925 const MCExpr *ExtraImmOp = 0;
926 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
927 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
928 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
929 bool IsVCMP = PatchedName.startswith("vcmp");
930 unsigned SSECCIdx = IsVCMP ? 4 : 3;
931 unsigned SSEComparisonCode = StringSwitch<unsigned>(
932 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
945 .Case("neq_oq", 0x0C)
952 .Case("unord_s", 0x13)
953 .Case("neq_us", 0x14)
954 .Case("nlt_uq", 0x15)
955 .Case("nle_uq", 0x16)
958 .Case("nge_uq", 0x19)
959 .Case("ngt_uq", 0x1A)
960 .Case("false_os", 0x1B)
961 .Case("neq_os", 0x1C)
964 .Case("true_us", 0x1F)
966 if (SSEComparisonCode != ~0U) {
967 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
968 getParser().getContext());
969 if (PatchedName.endswith("ss")) {
970 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
971 } else if (PatchedName.endswith("sd")) {
972 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
973 } else if (PatchedName.endswith("ps")) {
974 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
976 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
977 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
982 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
985 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
988 // Determine whether this is an instruction prefix.
990 Name == "lock" || Name == "rep" ||
991 Name == "repe" || Name == "repz" ||
992 Name == "repne" || Name == "repnz" ||
993 Name == "rex64" || Name == "data16";
996 // This does the actual operand parsing. Don't parse any more if we have a
997 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
998 // just want to parse the "lock" as the first instruction and the "incl" as
1000 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1002 // Parse '*' modifier.
1003 if (getLexer().is(AsmToken::Star)) {
1004 SMLoc Loc = Parser.getTok().getLoc();
1005 Operands.push_back(X86Operand::CreateToken("*", Loc));
1006 Parser.Lex(); // Eat the star.
1009 // Read the first operand.
1010 if (X86Operand *Op = ParseOperand())
1011 Operands.push_back(Op);
1013 Parser.EatToEndOfStatement();
1017 while (getLexer().is(AsmToken::Comma)) {
1018 Parser.Lex(); // Eat the comma.
1020 // Parse and remember the operand.
1021 if (X86Operand *Op = ParseOperand())
1022 Operands.push_back(Op);
1024 Parser.EatToEndOfStatement();
1029 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1030 SMLoc Loc = getLexer().getLoc();
1031 Parser.EatToEndOfStatement();
1032 return Error(Loc, "unexpected token in argument list");
1036 if (getLexer().is(AsmToken::EndOfStatement))
1037 Parser.Lex(); // Consume the EndOfStatement
1038 else if (isPrefix && getLexer().is(AsmToken::Slash))
1039 Parser.Lex(); // Consume the prefix separator Slash
1041 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1042 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1043 // documented form in various unofficial manuals, so a lot of code uses it.
1044 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1045 Operands.size() == 3) {
1046 X86Operand &Op = *(X86Operand*)Operands.back();
1047 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1048 isa<MCConstantExpr>(Op.Mem.Disp) &&
1049 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1050 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1051 SMLoc Loc = Op.getEndLoc();
1052 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1056 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1057 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1058 Operands.size() == 3) {
1059 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1060 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1061 isa<MCConstantExpr>(Op.Mem.Disp) &&
1062 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1063 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1064 SMLoc Loc = Op.getEndLoc();
1065 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1069 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1070 if (Name.startswith("ins") && Operands.size() == 3 &&
1071 (Name == "insb" || Name == "insw" || Name == "insl")) {
1072 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1073 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1074 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1075 Operands.pop_back();
1076 Operands.pop_back();
1082 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1083 if (Name.startswith("outs") && Operands.size() == 3 &&
1084 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1085 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1086 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1087 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1088 Operands.pop_back();
1089 Operands.pop_back();
1095 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1096 if (Name.startswith("movs") && Operands.size() == 3 &&
1097 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1098 (is64BitMode() && Name == "movsq"))) {
1099 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1100 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1101 if (isSrcOp(Op) && isDstOp(Op2)) {
1102 Operands.pop_back();
1103 Operands.pop_back();
1108 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1109 if (Name.startswith("lods") && Operands.size() == 3 &&
1110 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1111 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1112 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1113 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1114 if (isSrcOp(*Op1) && Op2->isReg()) {
1116 unsigned reg = Op2->getReg();
1117 bool isLods = Name == "lods";
1118 if (reg == X86::AL && (isLods || Name == "lodsb"))
1120 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1122 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1124 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1129 Operands.pop_back();
1130 Operands.pop_back();
1134 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1138 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1139 if (Name.startswith("stos") && Operands.size() == 3 &&
1140 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1141 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1142 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1143 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1144 if (isDstOp(*Op2) && Op1->isReg()) {
1146 unsigned reg = Op1->getReg();
1147 bool isStos = Name == "stos";
1148 if (reg == X86::AL && (isStos || Name == "stosb"))
1150 else if (reg == X86::AX && (isStos || Name == "stosw"))
1152 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1154 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1159 Operands.pop_back();
1160 Operands.pop_back();
1164 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1169 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1171 if ((Name.startswith("shr") || Name.startswith("sar") ||
1172 Name.startswith("shl") || Name.startswith("sal") ||
1173 Name.startswith("rcl") || Name.startswith("rcr") ||
1174 Name.startswith("rol") || Name.startswith("ror")) &&
1175 Operands.size() == 3) {
1176 if (isParsingIntelSyntax()) {
1178 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1179 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1180 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1182 Operands.pop_back();
1185 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1186 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1187 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1189 Operands.erase(Operands.begin() + 1);
1194 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1195 // instalias with an immediate operand yet.
1196 if (Name == "int" && Operands.size() == 2) {
1197 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1198 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1199 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1201 Operands.erase(Operands.begin() + 1);
1202 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1210 processInstruction(MCInst &Inst,
1211 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1212 switch (Inst.getOpcode()) {
1213 default: return false;
1214 case X86::AND16i16: {
1215 if (!Inst.getOperand(0).isImm() ||
1216 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1220 TmpInst.setOpcode(X86::AND16ri8);
1221 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1222 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1223 TmpInst.addOperand(Inst.getOperand(0));
1227 case X86::AND32i32: {
1228 if (!Inst.getOperand(0).isImm() ||
1229 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1233 TmpInst.setOpcode(X86::AND32ri8);
1234 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1235 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1236 TmpInst.addOperand(Inst.getOperand(0));
1240 case X86::AND64i32: {
1241 if (!Inst.getOperand(0).isImm() ||
1242 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1246 TmpInst.setOpcode(X86::AND64ri8);
1247 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1248 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1249 TmpInst.addOperand(Inst.getOperand(0));
1253 case X86::XOR16i16: {
1254 if (!Inst.getOperand(0).isImm() ||
1255 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1259 TmpInst.setOpcode(X86::XOR16ri8);
1260 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1261 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1262 TmpInst.addOperand(Inst.getOperand(0));
1266 case X86::XOR32i32: {
1267 if (!Inst.getOperand(0).isImm() ||
1268 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1272 TmpInst.setOpcode(X86::XOR32ri8);
1273 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1274 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1275 TmpInst.addOperand(Inst.getOperand(0));
1279 case X86::XOR64i32: {
1280 if (!Inst.getOperand(0).isImm() ||
1281 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1285 TmpInst.setOpcode(X86::XOR64ri8);
1286 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1287 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1288 TmpInst.addOperand(Inst.getOperand(0));
1292 case X86::OR16i16: {
1293 if (!Inst.getOperand(0).isImm() ||
1294 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1298 TmpInst.setOpcode(X86::OR16ri8);
1299 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1300 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1301 TmpInst.addOperand(Inst.getOperand(0));
1305 case X86::OR32i32: {
1306 if (!Inst.getOperand(0).isImm() ||
1307 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1311 TmpInst.setOpcode(X86::OR32ri8);
1312 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1313 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1314 TmpInst.addOperand(Inst.getOperand(0));
1318 case X86::OR64i32: {
1319 if (!Inst.getOperand(0).isImm() ||
1320 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1324 TmpInst.setOpcode(X86::OR64ri8);
1325 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1326 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1327 TmpInst.addOperand(Inst.getOperand(0));
1331 case X86::CMP16i16: {
1332 if (!Inst.getOperand(0).isImm() ||
1333 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1337 TmpInst.setOpcode(X86::CMP16ri8);
1338 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1339 TmpInst.addOperand(Inst.getOperand(0));
1343 case X86::CMP32i32: {
1344 if (!Inst.getOperand(0).isImm() ||
1345 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1349 TmpInst.setOpcode(X86::CMP32ri8);
1350 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1351 TmpInst.addOperand(Inst.getOperand(0));
1355 case X86::CMP64i32: {
1356 if (!Inst.getOperand(0).isImm() ||
1357 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1361 TmpInst.setOpcode(X86::CMP64ri8);
1362 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1363 TmpInst.addOperand(Inst.getOperand(0));
1367 case X86::ADD16i16: {
1368 if (!Inst.getOperand(0).isImm() ||
1369 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1373 TmpInst.setOpcode(X86::ADD16ri8);
1374 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1375 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1376 TmpInst.addOperand(Inst.getOperand(0));
1380 case X86::ADD32i32: {
1381 if (!Inst.getOperand(0).isImm() ||
1382 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1386 TmpInst.setOpcode(X86::ADD32ri8);
1387 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1388 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1389 TmpInst.addOperand(Inst.getOperand(0));
1393 case X86::ADD64i32: {
1394 if (!Inst.getOperand(0).isImm() ||
1395 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1399 TmpInst.setOpcode(X86::ADD64ri8);
1400 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1401 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1402 TmpInst.addOperand(Inst.getOperand(0));
1406 case X86::SUB16i16: {
1407 if (!Inst.getOperand(0).isImm() ||
1408 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1412 TmpInst.setOpcode(X86::SUB16ri8);
1413 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1414 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1415 TmpInst.addOperand(Inst.getOperand(0));
1419 case X86::SUB32i32: {
1420 if (!Inst.getOperand(0).isImm() ||
1421 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1425 TmpInst.setOpcode(X86::SUB32ri8);
1426 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1427 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1428 TmpInst.addOperand(Inst.getOperand(0));
1432 case X86::SUB64i32: {
1433 if (!Inst.getOperand(0).isImm() ||
1434 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1438 TmpInst.setOpcode(X86::SUB64ri8);
1439 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1440 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1441 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")) {
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"