1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/MC/MCRegisterInfo.h"
16 #include "llvm/MC/MCSubtargetInfo.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Support/raw_ostream.h"
33 class X86AsmParser : public MCTargetAsmParser {
37 MCAsmParser &getParser() const { return Parser; }
39 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
41 bool Error(SMLoc L, const Twine &Msg,
42 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
43 bool MatchingInlineAsm = false) {
44 if (MatchingInlineAsm) return true;
45 return Parser.Error(L, Msg, Ranges);
48 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
53 X86Operand *ParseOperand();
54 X86Operand *ParseATTOperand();
55 X86Operand *ParseIntelOperand();
56 X86Operand *ParseIntelMemOperand(unsigned SegReg, SMLoc StartLoc);
57 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
58 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
60 bool ParseDirectiveWord(unsigned Size, SMLoc L);
61 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
63 bool processInstruction(MCInst &Inst,
64 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
66 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
67 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
68 MCStreamer &Out, unsigned &ErrorInfo,
69 bool MatchingInlineAsm);
71 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
72 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
73 bool isSrcOp(X86Operand &Op);
75 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
76 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
77 bool isDstOp(X86Operand &Op);
79 bool is64BitMode() const {
80 // FIXME: Can tablegen auto-generate this?
81 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
84 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
85 setAvailableFeatures(FB);
88 /// @name Auto-generated Matcher Functions
91 #define GET_ASSEMBLER_HEADER
92 #include "X86GenAsmMatcher.inc"
97 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
98 : MCTargetAsmParser(), STI(sti), Parser(parser) {
100 // Initialize the set of available features.
101 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
103 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
105 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
106 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
108 virtual bool ParseDirective(AsmToken DirectiveID);
110 bool isParsingIntelSyntax() {
111 return getParser().getAssemblerDialect();
114 } // end anonymous namespace
116 /// @name Auto-generated Match Functions
119 static unsigned MatchRegisterName(StringRef Name);
123 static bool isImmSExti16i8Value(uint64_t Value) {
124 return (( Value <= 0x000000000000007FULL)||
125 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
126 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
129 static bool isImmSExti32i8Value(uint64_t Value) {
130 return (( Value <= 0x000000000000007FULL)||
131 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
132 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
135 static bool isImmZExtu32u8Value(uint64_t Value) {
136 return (Value <= 0x00000000000000FFULL);
139 static bool isImmSExti64i8Value(uint64_t Value) {
140 return (( Value <= 0x000000000000007FULL)||
141 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
144 static bool isImmSExti64i32Value(uint64_t Value) {
145 return (( Value <= 0x000000007FFFFFFFULL)||
146 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
150 /// X86Operand - Instances of this class represent a parsed X86 machine
152 struct X86Operand : public MCParsedAsmOperand {
160 SMLoc StartLoc, EndLoc;
186 X86Operand(KindTy K, SMLoc Start, SMLoc End)
187 : Kind(K), StartLoc(Start), EndLoc(End) {}
189 /// getStartLoc - Get the location of the first token of this operand.
190 SMLoc getStartLoc() const { return StartLoc; }
191 /// getEndLoc - Get the location of the last token of this operand.
192 SMLoc getEndLoc() const { return EndLoc; }
193 /// getLocRange - Get the range between the first and last token of this
195 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
197 virtual void print(raw_ostream &OS) const {}
199 StringRef getToken() const {
200 assert(Kind == Token && "Invalid access!");
201 return StringRef(Tok.Data, Tok.Length);
203 void setTokenValue(StringRef Value) {
204 assert(Kind == Token && "Invalid access!");
205 Tok.Data = Value.data();
206 Tok.Length = Value.size();
209 unsigned getReg() const {
210 assert(Kind == Register && "Invalid access!");
214 const MCExpr *getImm() const {
215 assert(Kind == Immediate && "Invalid access!");
219 const MCExpr *getMemDisp() const {
220 assert(Kind == Memory && "Invalid access!");
223 unsigned getMemSegReg() const {
224 assert(Kind == Memory && "Invalid access!");
227 unsigned getMemBaseReg() const {
228 assert(Kind == Memory && "Invalid access!");
231 unsigned getMemIndexReg() const {
232 assert(Kind == Memory && "Invalid access!");
235 unsigned getMemScale() const {
236 assert(Kind == Memory && "Invalid access!");
240 bool isToken() const {return Kind == Token; }
242 bool isImm() const { return Kind == Immediate; }
244 bool isImmSExti16i8() const {
248 // If this isn't a constant expr, just assume it fits and let relaxation
250 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
254 // Otherwise, check the value is in a range that makes sense for this
256 return isImmSExti16i8Value(CE->getValue());
258 bool isImmSExti32i8() const {
262 // If this isn't a constant expr, just assume it fits and let relaxation
264 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
268 // Otherwise, check the value is in a range that makes sense for this
270 return isImmSExti32i8Value(CE->getValue());
272 bool isImmZExtu32u8() const {
276 // If this isn't a constant expr, just assume it fits and let relaxation
278 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
282 // Otherwise, check the value is in a range that makes sense for this
284 return isImmZExtu32u8Value(CE->getValue());
286 bool isImmSExti64i8() const {
290 // If this isn't a constant expr, just assume it fits and let relaxation
292 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
296 // Otherwise, check the value is in a range that makes sense for this
298 return isImmSExti64i8Value(CE->getValue());
300 bool isImmSExti64i32() const {
304 // If this isn't a constant expr, just assume it fits and let relaxation
306 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
310 // Otherwise, check the value is in a range that makes sense for this
312 return isImmSExti64i32Value(CE->getValue());
315 bool isMem() const { return Kind == Memory; }
316 bool isMem8() const {
317 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
319 bool isMem16() const {
320 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
322 bool isMem32() const {
323 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
325 bool isMem64() const {
326 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
328 bool isMem80() const {
329 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
331 bool isMem128() const {
332 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
334 bool isMem256() const {
335 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
338 bool isMemVX32() const {
339 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
340 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
342 bool isMemVY32() const {
343 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
344 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
346 bool isMemVX64() const {
347 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
348 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
350 bool isMemVY64() const {
351 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
352 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
355 bool isAbsMem() const {
356 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
357 !getMemIndexReg() && getMemScale() == 1;
360 bool isReg() const { return Kind == Register; }
362 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
363 // Add as immediates when possible.
364 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
365 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
367 Inst.addOperand(MCOperand::CreateExpr(Expr));
370 void addRegOperands(MCInst &Inst, unsigned N) const {
371 assert(N == 1 && "Invalid number of operands!");
372 Inst.addOperand(MCOperand::CreateReg(getReg()));
375 void addImmOperands(MCInst &Inst, unsigned N) const {
376 assert(N == 1 && "Invalid number of operands!");
377 addExpr(Inst, getImm());
380 void addMem8Operands(MCInst &Inst, unsigned N) const {
381 addMemOperands(Inst, N);
383 void addMem16Operands(MCInst &Inst, unsigned N) const {
384 addMemOperands(Inst, N);
386 void addMem32Operands(MCInst &Inst, unsigned N) const {
387 addMemOperands(Inst, N);
389 void addMem64Operands(MCInst &Inst, unsigned N) const {
390 addMemOperands(Inst, N);
392 void addMem80Operands(MCInst &Inst, unsigned N) const {
393 addMemOperands(Inst, N);
395 void addMem128Operands(MCInst &Inst, unsigned N) const {
396 addMemOperands(Inst, N);
398 void addMem256Operands(MCInst &Inst, unsigned N) const {
399 addMemOperands(Inst, N);
401 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
402 addMemOperands(Inst, N);
404 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
405 addMemOperands(Inst, N);
407 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
408 addMemOperands(Inst, N);
410 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
411 addMemOperands(Inst, N);
414 void addMemOperands(MCInst &Inst, unsigned N) const {
415 assert((N == 5) && "Invalid number of operands!");
416 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
417 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
418 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
419 addExpr(Inst, getMemDisp());
420 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
423 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
424 assert((N == 1) && "Invalid number of operands!");
425 // Add as immediates when possible.
426 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
427 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
429 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
432 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
433 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
434 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
435 Res->Tok.Data = Str.data();
436 Res->Tok.Length = Str.size();
440 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
441 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
442 Res->Reg.RegNo = RegNo;
446 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
447 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
452 /// Create an absolute memory operand.
453 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
454 SMLoc EndLoc, unsigned Size = 0) {
455 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
457 Res->Mem.Disp = Disp;
458 Res->Mem.BaseReg = 0;
459 Res->Mem.IndexReg = 0;
461 Res->Mem.Size = Size;
465 /// Create a generalized memory operand.
466 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
467 unsigned BaseReg, unsigned IndexReg,
468 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
470 // We should never just have a displacement, that should be parsed as an
471 // absolute memory operand.
472 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
474 // The scale should always be one of {1,2,4,8}.
475 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
477 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
478 Res->Mem.SegReg = SegReg;
479 Res->Mem.Disp = Disp;
480 Res->Mem.BaseReg = BaseReg;
481 Res->Mem.IndexReg = IndexReg;
482 Res->Mem.Scale = Scale;
483 Res->Mem.Size = Size;
488 } // end anonymous namespace.
490 bool X86AsmParser::isSrcOp(X86Operand &Op) {
491 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
493 return (Op.isMem() &&
494 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
495 isa<MCConstantExpr>(Op.Mem.Disp) &&
496 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
497 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
500 bool X86AsmParser::isDstOp(X86Operand &Op) {
501 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
504 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
505 isa<MCConstantExpr>(Op.Mem.Disp) &&
506 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
507 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
510 bool X86AsmParser::ParseRegister(unsigned &RegNo,
511 SMLoc &StartLoc, SMLoc &EndLoc) {
513 const AsmToken &PercentTok = Parser.getTok();
514 StartLoc = PercentTok.getLoc();
516 // If we encounter a %, ignore it. This code handles registers with and
517 // without the prefix, unprefixed registers can occur in cfi directives.
518 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
519 Parser.Lex(); // Eat percent token.
521 const AsmToken &Tok = Parser.getTok();
522 if (Tok.isNot(AsmToken::Identifier)) {
523 if (isParsingIntelSyntax()) return true;
524 return Error(StartLoc, "invalid register name",
525 SMRange(StartLoc, Tok.getEndLoc()));
528 RegNo = MatchRegisterName(Tok.getString());
530 // If the match failed, try the register name as lowercase.
532 RegNo = MatchRegisterName(Tok.getString().lower());
534 if (!is64BitMode()) {
535 // FIXME: This should be done using Requires<In32BitMode> and
536 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
538 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
540 if (RegNo == X86::RIZ ||
541 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
542 X86II::isX86_64NonExtLowByteReg(RegNo) ||
543 X86II::isX86_64ExtendedReg(RegNo))
544 return Error(StartLoc, "register %"
545 + Tok.getString() + " is only available in 64-bit mode",
546 SMRange(StartLoc, Tok.getEndLoc()));
549 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
550 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
552 EndLoc = Tok.getLoc();
553 Parser.Lex(); // Eat 'st'
555 // Check to see if we have '(4)' after %st.
556 if (getLexer().isNot(AsmToken::LParen))
561 const AsmToken &IntTok = Parser.getTok();
562 if (IntTok.isNot(AsmToken::Integer))
563 return Error(IntTok.getLoc(), "expected stack index");
564 switch (IntTok.getIntVal()) {
565 case 0: RegNo = X86::ST0; break;
566 case 1: RegNo = X86::ST1; break;
567 case 2: RegNo = X86::ST2; break;
568 case 3: RegNo = X86::ST3; break;
569 case 4: RegNo = X86::ST4; break;
570 case 5: RegNo = X86::ST5; break;
571 case 6: RegNo = X86::ST6; break;
572 case 7: RegNo = X86::ST7; break;
573 default: return Error(IntTok.getLoc(), "invalid stack index");
576 if (getParser().Lex().isNot(AsmToken::RParen))
577 return Error(Parser.getTok().getLoc(), "expected ')'");
579 EndLoc = Tok.getLoc();
580 Parser.Lex(); // Eat ')'
584 // If this is "db[0-7]", match it as an alias
586 if (RegNo == 0 && Tok.getString().size() == 3 &&
587 Tok.getString().startswith("db")) {
588 switch (Tok.getString()[2]) {
589 case '0': RegNo = X86::DR0; break;
590 case '1': RegNo = X86::DR1; break;
591 case '2': RegNo = X86::DR2; break;
592 case '3': RegNo = X86::DR3; break;
593 case '4': RegNo = X86::DR4; break;
594 case '5': RegNo = X86::DR5; break;
595 case '6': RegNo = X86::DR6; break;
596 case '7': RegNo = X86::DR7; break;
600 EndLoc = Tok.getLoc();
601 Parser.Lex(); // Eat it.
607 if (isParsingIntelSyntax()) return true;
608 return Error(StartLoc, "invalid register name",
609 SMRange(StartLoc, Tok.getEndLoc()));
612 EndLoc = Tok.getEndLoc();
613 Parser.Lex(); // Eat identifier token.
617 X86Operand *X86AsmParser::ParseOperand() {
618 if (isParsingIntelSyntax())
619 return ParseIntelOperand();
620 return ParseATTOperand();
623 /// getIntelMemOperandSize - Return intel memory operand size.
624 static unsigned getIntelMemOperandSize(StringRef OpStr) {
625 unsigned Size = StringSwitch<unsigned>(OpStr)
626 .Cases("BYTE", "byte", 8)
627 .Cases("WORD", "word", 16)
628 .Cases("DWORD", "dword", 32)
629 .Cases("QWORD", "qword", 64)
630 .Cases("XWORD", "xword", 80)
631 .Cases("XMMWORD", "xmmword", 128)
632 .Cases("YMMWORD", "ymmword", 256)
637 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
639 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
640 SMLoc Start = Parser.getTok().getLoc(), End;
642 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
643 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
646 if (getLexer().isNot(AsmToken::LBrac))
647 return ErrorOperand(Start, "Expected '[' token!");
650 if (getLexer().is(AsmToken::Identifier)) {
652 if (ParseRegister(BaseReg, Start, End)) {
653 // Handle '[' 'symbol' ']'
654 if (getParser().ParseExpression(Disp, End)) return 0;
655 if (getLexer().isNot(AsmToken::RBrac))
656 return ErrorOperand(Start, "Expected ']' token!");
658 return X86Operand::CreateMem(Disp, Start, End, Size);
660 } else if (getLexer().is(AsmToken::Integer)) {
661 int64_t Val = Parser.getTok().getIntVal();
663 SMLoc Loc = Parser.getTok().getLoc();
664 if (getLexer().is(AsmToken::RBrac)) {
665 // Handle '[' number ']'
667 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
669 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
671 return X86Operand::CreateMem(Disp, Start, End, Size);
672 } else if (getLexer().is(AsmToken::Star)) {
673 // Handle '[' Scale*IndexReg ']'
675 SMLoc IdxRegLoc = Parser.getTok().getLoc();
676 if (ParseRegister(IndexReg, IdxRegLoc, End))
677 return ErrorOperand(IdxRegLoc, "Expected register");
680 return ErrorOperand(Loc, "Unexpected token");
683 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
684 bool isPlus = getLexer().is(AsmToken::Plus);
686 SMLoc PlusLoc = Parser.getTok().getLoc();
687 if (getLexer().is(AsmToken::Integer)) {
688 int64_t Val = Parser.getTok().getIntVal();
690 if (getLexer().is(AsmToken::Star)) {
692 SMLoc IdxRegLoc = Parser.getTok().getLoc();
693 if (ParseRegister(IndexReg, IdxRegLoc, End))
694 return ErrorOperand(IdxRegLoc, "Expected register");
696 } else if (getLexer().is(AsmToken::RBrac)) {
697 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
698 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
700 return ErrorOperand(PlusLoc, "unexpected token after +");
701 } else if (getLexer().is(AsmToken::Identifier)) {
702 // This could be an index register or a displacement expression.
703 End = Parser.getTok().getLoc();
705 ParseRegister(IndexReg, Start, End);
706 else if (getParser().ParseExpression(Disp, End)) return 0;
710 if (getLexer().isNot(AsmToken::RBrac))
711 if (getParser().ParseExpression(Disp, End)) return 0;
713 End = Parser.getTok().getLoc();
714 if (getLexer().isNot(AsmToken::RBrac))
715 return ErrorOperand(End, "expected ']' token!");
717 End = Parser.getTok().getLoc();
720 if (!BaseReg && !IndexReg)
721 return X86Operand::CreateMem(Disp, Start, End, Size);
723 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
727 /// ParseIntelMemOperand - Parse intel style memory operand.
728 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
729 const AsmToken &Tok = Parser.getTok();
732 unsigned Size = getIntelMemOperandSize(Tok.getString());
735 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
736 "Unexpected token!");
740 if (getLexer().is(AsmToken::LBrac))
741 return ParseIntelBracExpression(SegReg, Size);
743 if (!ParseRegister(SegReg, Start, End)) {
744 // Handel SegReg : [ ... ]
745 if (getLexer().isNot(AsmToken::Colon))
746 return ErrorOperand(Start, "Expected ':' token!");
747 Parser.Lex(); // Eat :
748 if (getLexer().isNot(AsmToken::LBrac))
749 return ErrorOperand(Start, "Expected '[' token!");
750 return ParseIntelBracExpression(SegReg, Size);
753 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
754 if (getParser().ParseExpression(Disp, End)) return 0;
755 return X86Operand::CreateMem(Disp, Start, End, Size);
758 X86Operand *X86AsmParser::ParseIntelOperand() {
759 SMLoc Start = Parser.getTok().getLoc(), End;
762 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
763 getLexer().is(AsmToken::Minus)) {
765 if (!getParser().ParseExpression(Val, End)) {
766 End = Parser.getTok().getLoc();
767 return X86Operand::CreateImm(Val, Start, End);
773 if (!ParseRegister(RegNo, Start, End)) {
774 // If this is a segment register followed by a ':', then this is the start
775 // of a memory reference, otherwise this is a normal register reference.
776 if (getLexer().isNot(AsmToken::Colon))
777 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
779 getParser().Lex(); // Eat the colon.
780 return ParseIntelMemOperand(RegNo, Start);
784 return ParseIntelMemOperand(0, Start);
787 X86Operand *X86AsmParser::ParseATTOperand() {
788 switch (getLexer().getKind()) {
790 // Parse a memory operand with no segment register.
791 return ParseMemOperand(0, Parser.getTok().getLoc());
792 case AsmToken::Percent: {
793 // Read the register.
796 if (ParseRegister(RegNo, Start, End)) return 0;
797 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
798 Error(Start, "%eiz and %riz can only be used as index registers",
799 SMRange(Start, End));
803 // If this is a segment register followed by a ':', then this is the start
804 // of a memory reference, otherwise this is a normal register reference.
805 if (getLexer().isNot(AsmToken::Colon))
806 return X86Operand::CreateReg(RegNo, Start, End);
809 getParser().Lex(); // Eat the colon.
810 return ParseMemOperand(RegNo, Start);
812 case AsmToken::Dollar: {
814 SMLoc Start = Parser.getTok().getLoc(), End;
817 if (getParser().ParseExpression(Val, End))
819 return X86Operand::CreateImm(Val, Start, End);
824 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
825 /// has already been parsed if present.
826 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
828 // We have to disambiguate a parenthesized expression "(4+5)" from the start
829 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
830 // only way to do this without lookahead is to eat the '(' and see what is
832 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
833 if (getLexer().isNot(AsmToken::LParen)) {
835 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
837 // After parsing the base expression we could either have a parenthesized
838 // memory address or not. If not, return now. If so, eat the (.
839 if (getLexer().isNot(AsmToken::LParen)) {
840 // Unless we have a segment register, treat this as an immediate.
842 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
843 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
849 // Okay, we have a '('. We don't know if this is an expression or not, but
850 // so we have to eat the ( to see beyond it.
851 SMLoc LParenLoc = Parser.getTok().getLoc();
852 Parser.Lex(); // Eat the '('.
854 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
855 // Nothing to do here, fall into the code below with the '(' part of the
856 // memory operand consumed.
860 // It must be an parenthesized expression, parse it now.
861 if (getParser().ParseParenExpression(Disp, ExprEnd))
864 // After parsing the base expression we could either have a parenthesized
865 // memory address or not. If not, return now. If so, eat the (.
866 if (getLexer().isNot(AsmToken::LParen)) {
867 // Unless we have a segment register, treat this as an immediate.
869 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
870 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
878 // If we reached here, then we just ate the ( of the memory operand. Process
879 // the rest of the memory operand.
880 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
883 if (getLexer().is(AsmToken::Percent)) {
884 SMLoc StartLoc, EndLoc;
885 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
886 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
887 Error(StartLoc, "eiz and riz can only be used as index registers",
888 SMRange(StartLoc, EndLoc));
893 if (getLexer().is(AsmToken::Comma)) {
894 Parser.Lex(); // Eat the comma.
895 IndexLoc = Parser.getTok().getLoc();
897 // Following the comma we should have either an index register, or a scale
898 // value. We don't support the later form, but we want to parse it
901 // Not that even though it would be completely consistent to support syntax
902 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
903 if (getLexer().is(AsmToken::Percent)) {
905 if (ParseRegister(IndexReg, L, L)) return 0;
907 if (getLexer().isNot(AsmToken::RParen)) {
908 // Parse the scale amount:
909 // ::= ',' [scale-expression]
910 if (getLexer().isNot(AsmToken::Comma)) {
911 Error(Parser.getTok().getLoc(),
912 "expected comma in scale expression");
915 Parser.Lex(); // Eat the comma.
917 if (getLexer().isNot(AsmToken::RParen)) {
918 SMLoc Loc = Parser.getTok().getLoc();
921 if (getParser().ParseAbsoluteExpression(ScaleVal)){
922 Error(Loc, "expected scale expression");
926 // Validate the scale amount.
927 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
928 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
931 Scale = (unsigned)ScaleVal;
934 } else if (getLexer().isNot(AsmToken::RParen)) {
935 // A scale amount without an index is ignored.
937 SMLoc Loc = Parser.getTok().getLoc();
940 if (getParser().ParseAbsoluteExpression(Value))
944 Warning(Loc, "scale factor without index register is ignored");
949 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
950 if (getLexer().isNot(AsmToken::RParen)) {
951 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
954 SMLoc MemEnd = Parser.getTok().getLoc();
955 Parser.Lex(); // Eat the ')'.
957 // If we have both a base register and an index register make sure they are
958 // both 64-bit or 32-bit registers.
959 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
960 if (BaseReg != 0 && IndexReg != 0) {
961 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
962 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
963 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
964 IndexReg != X86::RIZ) {
965 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
968 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
969 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
970 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
971 IndexReg != X86::EIZ){
972 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
977 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
982 ParseInstruction(StringRef Name, SMLoc NameLoc,
983 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
984 StringRef PatchedName = Name;
986 // FIXME: Hack to recognize setneb as setne.
987 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
988 PatchedName != "setb" && PatchedName != "setnb")
989 PatchedName = PatchedName.substr(0, Name.size()-1);
991 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
992 const MCExpr *ExtraImmOp = 0;
993 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
994 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
995 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
996 bool IsVCMP = PatchedName[0] == 'v';
997 unsigned SSECCIdx = IsVCMP ? 4 : 3;
998 unsigned SSEComparisonCode = StringSwitch<unsigned>(
999 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1003 .Case("unord", 0x03)
1008 /* AVX only from here */
1009 .Case("eq_uq", 0x08)
1012 .Case("false", 0x0B)
1013 .Case("neq_oq", 0x0C)
1017 .Case("eq_os", 0x10)
1018 .Case("lt_oq", 0x11)
1019 .Case("le_oq", 0x12)
1020 .Case("unord_s", 0x13)
1021 .Case("neq_us", 0x14)
1022 .Case("nlt_uq", 0x15)
1023 .Case("nle_uq", 0x16)
1024 .Case("ord_s", 0x17)
1025 .Case("eq_us", 0x18)
1026 .Case("nge_uq", 0x19)
1027 .Case("ngt_uq", 0x1A)
1028 .Case("false_os", 0x1B)
1029 .Case("neq_os", 0x1C)
1030 .Case("ge_oq", 0x1D)
1031 .Case("gt_oq", 0x1E)
1032 .Case("true_us", 0x1F)
1034 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1035 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1036 getParser().getContext());
1037 if (PatchedName.endswith("ss")) {
1038 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1039 } else if (PatchedName.endswith("sd")) {
1040 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1041 } else if (PatchedName.endswith("ps")) {
1042 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1044 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1045 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1050 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1052 if (ExtraImmOp && !isParsingIntelSyntax())
1053 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1055 // Determine whether this is an instruction prefix.
1057 Name == "lock" || Name == "rep" ||
1058 Name == "repe" || Name == "repz" ||
1059 Name == "repne" || Name == "repnz" ||
1060 Name == "rex64" || Name == "data16";
1063 // This does the actual operand parsing. Don't parse any more if we have a
1064 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1065 // just want to parse the "lock" as the first instruction and the "incl" as
1067 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1069 // Parse '*' modifier.
1070 if (getLexer().is(AsmToken::Star)) {
1071 SMLoc Loc = Parser.getTok().getLoc();
1072 Operands.push_back(X86Operand::CreateToken("*", Loc));
1073 Parser.Lex(); // Eat the star.
1076 // Read the first operand.
1077 if (X86Operand *Op = ParseOperand())
1078 Operands.push_back(Op);
1080 Parser.EatToEndOfStatement();
1084 while (getLexer().is(AsmToken::Comma)) {
1085 Parser.Lex(); // Eat the comma.
1087 // Parse and remember the operand.
1088 if (X86Operand *Op = ParseOperand())
1089 Operands.push_back(Op);
1091 Parser.EatToEndOfStatement();
1096 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1097 SMLoc Loc = getLexer().getLoc();
1098 Parser.EatToEndOfStatement();
1099 return Error(Loc, "unexpected token in argument list");
1103 if (getLexer().is(AsmToken::EndOfStatement))
1104 Parser.Lex(); // Consume the EndOfStatement
1105 else if (isPrefix && getLexer().is(AsmToken::Slash))
1106 Parser.Lex(); // Consume the prefix separator Slash
1108 if (ExtraImmOp && isParsingIntelSyntax())
1109 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1111 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1112 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1113 // documented form in various unofficial manuals, so a lot of code uses it.
1114 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1115 Operands.size() == 3) {
1116 X86Operand &Op = *(X86Operand*)Operands.back();
1117 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1118 isa<MCConstantExpr>(Op.Mem.Disp) &&
1119 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1120 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1121 SMLoc Loc = Op.getEndLoc();
1122 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1126 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1127 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1128 Operands.size() == 3) {
1129 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1130 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1131 isa<MCConstantExpr>(Op.Mem.Disp) &&
1132 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1133 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1134 SMLoc Loc = Op.getEndLoc();
1135 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1139 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1140 if (Name.startswith("ins") && Operands.size() == 3 &&
1141 (Name == "insb" || Name == "insw" || Name == "insl")) {
1142 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1143 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1144 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1145 Operands.pop_back();
1146 Operands.pop_back();
1152 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1153 if (Name.startswith("outs") && Operands.size() == 3 &&
1154 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1155 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1156 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1157 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1158 Operands.pop_back();
1159 Operands.pop_back();
1165 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1166 if (Name.startswith("movs") && Operands.size() == 3 &&
1167 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1168 (is64BitMode() && Name == "movsq"))) {
1169 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1170 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1171 if (isSrcOp(Op) && isDstOp(Op2)) {
1172 Operands.pop_back();
1173 Operands.pop_back();
1178 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1179 if (Name.startswith("lods") && Operands.size() == 3 &&
1180 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1181 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1182 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1183 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1184 if (isSrcOp(*Op1) && Op2->isReg()) {
1186 unsigned reg = Op2->getReg();
1187 bool isLods = Name == "lods";
1188 if (reg == X86::AL && (isLods || Name == "lodsb"))
1190 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1192 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1194 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1199 Operands.pop_back();
1200 Operands.pop_back();
1204 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1208 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1209 if (Name.startswith("stos") && Operands.size() == 3 &&
1210 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1211 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1212 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1213 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1214 if (isDstOp(*Op2) && Op1->isReg()) {
1216 unsigned reg = Op1->getReg();
1217 bool isStos = Name == "stos";
1218 if (reg == X86::AL && (isStos || Name == "stosb"))
1220 else if (reg == X86::AX && (isStos || Name == "stosw"))
1222 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1224 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1229 Operands.pop_back();
1230 Operands.pop_back();
1234 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1239 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1241 if ((Name.startswith("shr") || Name.startswith("sar") ||
1242 Name.startswith("shl") || Name.startswith("sal") ||
1243 Name.startswith("rcl") || Name.startswith("rcr") ||
1244 Name.startswith("rol") || Name.startswith("ror")) &&
1245 Operands.size() == 3) {
1246 if (isParsingIntelSyntax()) {
1248 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1249 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1250 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1252 Operands.pop_back();
1255 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1256 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1257 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1259 Operands.erase(Operands.begin() + 1);
1264 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1265 // instalias with an immediate operand yet.
1266 if (Name == "int" && Operands.size() == 2) {
1267 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1268 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1269 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1271 Operands.erase(Operands.begin() + 1);
1272 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1280 processInstruction(MCInst &Inst,
1281 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1282 switch (Inst.getOpcode()) {
1283 default: return false;
1284 case X86::AND16i16: {
1285 if (!Inst.getOperand(0).isImm() ||
1286 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1290 TmpInst.setOpcode(X86::AND16ri8);
1291 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1292 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1293 TmpInst.addOperand(Inst.getOperand(0));
1297 case X86::AND32i32: {
1298 if (!Inst.getOperand(0).isImm() ||
1299 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1303 TmpInst.setOpcode(X86::AND32ri8);
1304 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1305 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1306 TmpInst.addOperand(Inst.getOperand(0));
1310 case X86::AND64i32: {
1311 if (!Inst.getOperand(0).isImm() ||
1312 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1316 TmpInst.setOpcode(X86::AND64ri8);
1317 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1318 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1319 TmpInst.addOperand(Inst.getOperand(0));
1323 case X86::XOR16i16: {
1324 if (!Inst.getOperand(0).isImm() ||
1325 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1329 TmpInst.setOpcode(X86::XOR16ri8);
1330 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1331 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1332 TmpInst.addOperand(Inst.getOperand(0));
1336 case X86::XOR32i32: {
1337 if (!Inst.getOperand(0).isImm() ||
1338 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1342 TmpInst.setOpcode(X86::XOR32ri8);
1343 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1344 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1345 TmpInst.addOperand(Inst.getOperand(0));
1349 case X86::XOR64i32: {
1350 if (!Inst.getOperand(0).isImm() ||
1351 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1355 TmpInst.setOpcode(X86::XOR64ri8);
1356 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1357 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1358 TmpInst.addOperand(Inst.getOperand(0));
1362 case X86::OR16i16: {
1363 if (!Inst.getOperand(0).isImm() ||
1364 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1368 TmpInst.setOpcode(X86::OR16ri8);
1369 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1370 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1371 TmpInst.addOperand(Inst.getOperand(0));
1375 case X86::OR32i32: {
1376 if (!Inst.getOperand(0).isImm() ||
1377 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1381 TmpInst.setOpcode(X86::OR32ri8);
1382 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1383 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1384 TmpInst.addOperand(Inst.getOperand(0));
1388 case X86::OR64i32: {
1389 if (!Inst.getOperand(0).isImm() ||
1390 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1394 TmpInst.setOpcode(X86::OR64ri8);
1395 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1396 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1397 TmpInst.addOperand(Inst.getOperand(0));
1401 case X86::CMP16i16: {
1402 if (!Inst.getOperand(0).isImm() ||
1403 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1407 TmpInst.setOpcode(X86::CMP16ri8);
1408 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1409 TmpInst.addOperand(Inst.getOperand(0));
1413 case X86::CMP32i32: {
1414 if (!Inst.getOperand(0).isImm() ||
1415 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1419 TmpInst.setOpcode(X86::CMP32ri8);
1420 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1421 TmpInst.addOperand(Inst.getOperand(0));
1425 case X86::CMP64i32: {
1426 if (!Inst.getOperand(0).isImm() ||
1427 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1431 TmpInst.setOpcode(X86::CMP64ri8);
1432 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1433 TmpInst.addOperand(Inst.getOperand(0));
1437 case X86::ADD16i16: {
1438 if (!Inst.getOperand(0).isImm() ||
1439 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1443 TmpInst.setOpcode(X86::ADD16ri8);
1444 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1445 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1446 TmpInst.addOperand(Inst.getOperand(0));
1450 case X86::ADD32i32: {
1451 if (!Inst.getOperand(0).isImm() ||
1452 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1456 TmpInst.setOpcode(X86::ADD32ri8);
1457 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1458 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1459 TmpInst.addOperand(Inst.getOperand(0));
1463 case X86::ADD64i32: {
1464 if (!Inst.getOperand(0).isImm() ||
1465 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1469 TmpInst.setOpcode(X86::ADD64ri8);
1470 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1471 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1472 TmpInst.addOperand(Inst.getOperand(0));
1476 case X86::SUB16i16: {
1477 if (!Inst.getOperand(0).isImm() ||
1478 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1482 TmpInst.setOpcode(X86::SUB16ri8);
1483 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1484 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1485 TmpInst.addOperand(Inst.getOperand(0));
1489 case X86::SUB32i32: {
1490 if (!Inst.getOperand(0).isImm() ||
1491 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1495 TmpInst.setOpcode(X86::SUB32ri8);
1496 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1497 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1498 TmpInst.addOperand(Inst.getOperand(0));
1502 case X86::SUB64i32: {
1503 if (!Inst.getOperand(0).isImm() ||
1504 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1508 TmpInst.setOpcode(X86::SUB64ri8);
1509 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1510 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1511 TmpInst.addOperand(Inst.getOperand(0));
1519 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1520 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1521 MCStreamer &Out, unsigned &ErrorInfo,
1522 bool MatchingInlineAsm) {
1523 assert(!Operands.empty() && "Unexpect empty operand list!");
1524 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1525 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1526 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1528 // First, handle aliases that expand to multiple instructions.
1529 // FIXME: This should be replaced with a real .td file alias mechanism.
1530 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1532 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1533 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1534 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1535 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1537 Inst.setOpcode(X86::WAIT);
1539 if (!MatchingInlineAsm)
1540 Out.EmitInstruction(Inst);
1543 StringSwitch<const char*>(Op->getToken())
1544 .Case("finit", "fninit")
1545 .Case("fsave", "fnsave")
1546 .Case("fstcw", "fnstcw")
1547 .Case("fstcww", "fnstcw")
1548 .Case("fstenv", "fnstenv")
1549 .Case("fstsw", "fnstsw")
1550 .Case("fstsww", "fnstsw")
1551 .Case("fclex", "fnclex")
1553 assert(Repl && "Unknown wait-prefixed instruction");
1555 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1558 bool WasOriginallyInvalidOperand = false;
1561 // First, try a direct match.
1562 switch (MatchInstructionImpl(Operands, Inst,
1563 ErrorInfo, MatchingInlineAsm,
1564 isParsingIntelSyntax())) {
1567 // Some instructions need post-processing to, for example, tweak which
1568 // encoding is selected. Loop on it while changes happen so the
1569 // individual transformations can chain off each other.
1570 if (!MatchingInlineAsm)
1571 while (processInstruction(Inst, Operands))
1575 if (!MatchingInlineAsm)
1576 Out.EmitInstruction(Inst);
1577 Opcode = Inst.getOpcode();
1579 case Match_MissingFeature:
1580 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1581 EmptyRanges, MatchingInlineAsm);
1583 case Match_InvalidOperand:
1584 WasOriginallyInvalidOperand = true;
1586 case Match_MnemonicFail:
1590 // FIXME: Ideally, we would only attempt suffix matches for things which are
1591 // valid prefixes, and we could just infer the right unambiguous
1592 // type. However, that requires substantially more matcher support than the
1595 // Change the operand to point to a temporary token.
1596 StringRef Base = Op->getToken();
1597 SmallString<16> Tmp;
1600 Op->setTokenValue(Tmp.str());
1602 // If this instruction starts with an 'f', then it is a floating point stack
1603 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1604 // 80-bit floating point, which use the suffixes s,l,t respectively.
1606 // Otherwise, we assume that this may be an integer instruction, which comes
1607 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1608 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1610 // Check for the various suffix matches.
1611 Tmp[Base.size()] = Suffixes[0];
1612 unsigned ErrorInfoIgnore;
1613 unsigned Match1, Match2, Match3, Match4;
1615 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1616 isParsingIntelSyntax());
1617 Tmp[Base.size()] = Suffixes[1];
1618 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1619 isParsingIntelSyntax());
1620 Tmp[Base.size()] = Suffixes[2];
1621 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1622 isParsingIntelSyntax());
1623 Tmp[Base.size()] = Suffixes[3];
1624 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1625 isParsingIntelSyntax());
1627 // Restore the old token.
1628 Op->setTokenValue(Base);
1630 // If exactly one matched, then we treat that as a successful match (and the
1631 // instruction will already have been filled in correctly, since the failing
1632 // matches won't have modified it).
1633 unsigned NumSuccessfulMatches =
1634 (Match1 == Match_Success) + (Match2 == Match_Success) +
1635 (Match3 == Match_Success) + (Match4 == Match_Success);
1636 if (NumSuccessfulMatches == 1) {
1638 if (!MatchingInlineAsm)
1639 Out.EmitInstruction(Inst);
1640 Opcode = Inst.getOpcode();
1644 // Otherwise, the match failed, try to produce a decent error message.
1646 // If we had multiple suffix matches, then identify this as an ambiguous
1648 if (NumSuccessfulMatches > 1) {
1650 unsigned NumMatches = 0;
1651 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1652 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1653 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1654 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1656 SmallString<126> Msg;
1657 raw_svector_ostream OS(Msg);
1658 OS << "ambiguous instructions require an explicit suffix (could be ";
1659 for (unsigned i = 0; i != NumMatches; ++i) {
1662 if (i + 1 == NumMatches)
1664 OS << "'" << Base << MatchChars[i] << "'";
1667 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1671 // Okay, we know that none of the variants matched successfully.
1673 // If all of the instructions reported an invalid mnemonic, then the original
1674 // mnemonic was invalid.
1675 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1676 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1677 if (!WasOriginallyInvalidOperand) {
1678 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1680 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1681 Ranges, MatchingInlineAsm);
1684 // Recover location info for the operand if we know which was the problem.
1685 if (ErrorInfo != ~0U) {
1686 if (ErrorInfo >= Operands.size())
1687 return Error(IDLoc, "too few operands for instruction",
1688 EmptyRanges, MatchingInlineAsm);
1690 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
1691 if (Operand->getStartLoc().isValid()) {
1692 SMRange OperandRange = Operand->getLocRange();
1693 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1694 OperandRange, MatchingInlineAsm);
1698 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1702 // If one instruction matched with a missing feature, report this as a
1704 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1705 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1706 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1707 EmptyRanges, MatchingInlineAsm);
1711 // If one instruction matched with an invalid operand, report this as an
1713 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1714 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1715 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1720 // If all of these were an outright failure, report it in a useless way.
1721 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1722 EmptyRanges, MatchingInlineAsm);
1727 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1728 StringRef IDVal = DirectiveID.getIdentifier();
1729 if (IDVal == ".word")
1730 return ParseDirectiveWord(2, DirectiveID.getLoc());
1731 else if (IDVal.startswith(".code"))
1732 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1733 else if (IDVal.startswith(".att_syntax")) {
1734 getParser().setAssemblerDialect(0);
1736 } else if (IDVal.startswith(".intel_syntax")) {
1737 getParser().setAssemblerDialect(1);
1738 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1739 if(Parser.getTok().getString() == "noprefix") {
1740 // FIXME : Handle noprefix
1750 /// ParseDirectiveWord
1751 /// ::= .word [ expression (, expression)* ]
1752 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1753 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1755 const MCExpr *Value;
1756 if (getParser().ParseExpression(Value))
1759 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1761 if (getLexer().is(AsmToken::EndOfStatement))
1764 // FIXME: Improve diagnostic.
1765 if (getLexer().isNot(AsmToken::Comma))
1766 return Error(L, "unexpected token in directive");
1775 /// ParseDirectiveCode
1776 /// ::= .code32 | .code64
1777 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1778 if (IDVal == ".code32") {
1780 if (is64BitMode()) {
1782 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1784 } else if (IDVal == ".code64") {
1786 if (!is64BitMode()) {
1788 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1791 return Error(L, "unexpected directive " + IDVal);
1798 extern "C" void LLVMInitializeX86AsmLexer();
1800 // Force static initialization.
1801 extern "C" void LLVMInitializeX86AsmParser() {
1802 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1803 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1804 LLVMInitializeX86AsmLexer();
1807 #define GET_REGISTER_MATCHER
1808 #define GET_MATCHER_IMPLEMENTATION
1809 #include "X86GenAsmMatcher.inc"