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/MCSymbol.h"
15 #include "llvm/MC/MCInst.h"
16 #include "llvm/MC/MCRegisterInfo.h"
17 #include "llvm/MC/MCSubtargetInfo.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCAsmParser.h"
20 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
34 class X86AsmParser : public MCTargetAsmParser {
38 MCAsmParser &getParser() const { return Parser; }
40 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
42 bool Error(SMLoc L, const Twine &Msg,
43 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
44 bool MatchingInlineAsm = false) {
45 if (MatchingInlineAsm) return true;
46 return Parser.Error(L, Msg, Ranges);
49 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
54 X86Operand *ParseOperand();
55 X86Operand *ParseATTOperand();
56 X86Operand *ParseIntelOperand();
57 X86Operand *ParseIntelMemOperand(unsigned SegReg, SMLoc StartLoc);
58 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
59 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
61 bool ParseDirectiveWord(unsigned Size, SMLoc L);
62 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
64 bool processInstruction(MCInst &Inst,
65 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
67 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
68 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
69 MCStreamer &Out, unsigned &ErrorInfo,
70 bool MatchingInlineAsm);
72 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
73 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
74 bool isSrcOp(X86Operand &Op);
76 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
77 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
78 bool isDstOp(X86Operand &Op);
80 bool is64BitMode() const {
81 // FIXME: Can tablegen auto-generate this?
82 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
85 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
86 setAvailableFeatures(FB);
89 /// @name Auto-generated Matcher Functions
92 #define GET_ASSEMBLER_HEADER
93 #include "X86GenAsmMatcher.inc"
98 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
99 : MCTargetAsmParser(), STI(sti), Parser(parser) {
101 // Initialize the set of available features.
102 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
104 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
106 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
107 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
109 virtual bool ParseDirective(AsmToken DirectiveID);
111 bool isParsingIntelSyntax() {
112 return getParser().getAssemblerDialect();
115 } // end anonymous namespace
117 /// @name Auto-generated Match Functions
120 static unsigned MatchRegisterName(StringRef Name);
124 static bool isImmSExti16i8Value(uint64_t Value) {
125 return (( Value <= 0x000000000000007FULL)||
126 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
127 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
130 static bool isImmSExti32i8Value(uint64_t Value) {
131 return (( Value <= 0x000000000000007FULL)||
132 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
133 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
136 static bool isImmZExtu32u8Value(uint64_t Value) {
137 return (Value <= 0x00000000000000FFULL);
140 static bool isImmSExti64i8Value(uint64_t Value) {
141 return (( Value <= 0x000000000000007FULL)||
142 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
145 static bool isImmSExti64i32Value(uint64_t Value) {
146 return (( Value <= 0x000000007FFFFFFFULL)||
147 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
151 /// X86Operand - Instances of this class represent a parsed X86 machine
153 struct X86Operand : public MCParsedAsmOperand {
161 SMLoc StartLoc, EndLoc;
188 X86Operand(KindTy K, SMLoc Start, SMLoc End)
189 : Kind(K), StartLoc(Start), EndLoc(End) {}
191 /// getStartLoc - Get the location of the first token of this operand.
192 SMLoc getStartLoc() const { return StartLoc; }
193 /// getEndLoc - Get the location of the last token of this operand.
194 SMLoc getEndLoc() const { return EndLoc; }
195 /// getLocRange - Get the range between the first and last token of this
197 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
199 virtual void print(raw_ostream &OS) const {}
201 StringRef getToken() const {
202 assert(Kind == Token && "Invalid access!");
203 return StringRef(Tok.Data, Tok.Length);
205 void setTokenValue(StringRef Value) {
206 assert(Kind == Token && "Invalid access!");
207 Tok.Data = Value.data();
208 Tok.Length = Value.size();
211 unsigned getReg() const {
212 assert(Kind == Register && "Invalid access!");
216 const MCExpr *getImm() const {
217 assert(Kind == Immediate && "Invalid access!");
221 const MCExpr *getMemDisp() const {
222 assert(Kind == Memory && "Invalid access!");
225 unsigned getMemSegReg() const {
226 assert(Kind == Memory && "Invalid access!");
229 unsigned getMemBaseReg() const {
230 assert(Kind == Memory && "Invalid access!");
233 unsigned getMemIndexReg() const {
234 assert(Kind == Memory && "Invalid access!");
237 unsigned getMemScale() const {
238 assert(Kind == Memory && "Invalid access!");
242 bool isToken() const {return Kind == Token; }
244 bool isImm() const { return Kind == Immediate; }
246 bool isImmSExti16i8() const {
250 // If this isn't a constant expr, just assume it fits and let relaxation
252 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
256 // Otherwise, check the value is in a range that makes sense for this
258 return isImmSExti16i8Value(CE->getValue());
260 bool isImmSExti32i8() const {
264 // If this isn't a constant expr, just assume it fits and let relaxation
266 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
270 // Otherwise, check the value is in a range that makes sense for this
272 return isImmSExti32i8Value(CE->getValue());
274 bool isImmZExtu32u8() const {
278 // If this isn't a constant expr, just assume it fits and let relaxation
280 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
284 // Otherwise, check the value is in a range that makes sense for this
286 return isImmZExtu32u8Value(CE->getValue());
288 bool isImmSExti64i8() const {
292 // If this isn't a constant expr, just assume it fits and let relaxation
294 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
298 // Otherwise, check the value is in a range that makes sense for this
300 return isImmSExti64i8Value(CE->getValue());
302 bool isImmSExti64i32() const {
306 // If this isn't a constant expr, just assume it fits and let relaxation
308 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
312 // Otherwise, check the value is in a range that makes sense for this
314 return isImmSExti64i32Value(CE->getValue());
317 unsigned getMemSize() const {
318 assert(Kind == Memory && "Invalid access!");
322 bool needSizeDirective() const {
323 assert(Kind == Memory && "Invalid access!");
324 return Mem.NeedSizeDir;
327 bool isMem() const { return Kind == Memory; }
328 bool isMem8() const {
329 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
331 bool isMem16() const {
332 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
334 bool isMem32() const {
335 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
337 bool isMem64() const {
338 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
340 bool isMem80() const {
341 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
343 bool isMem128() const {
344 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
346 bool isMem256() const {
347 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
350 bool isMemVX32() const {
351 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
352 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
354 bool isMemVY32() const {
355 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
356 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
358 bool isMemVX64() const {
359 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
360 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
362 bool isMemVY64() const {
363 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
364 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
367 bool isAbsMem() const {
368 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
369 !getMemIndexReg() && getMemScale() == 1;
372 bool isReg() const { return Kind == Register; }
374 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
375 // Add as immediates when possible.
376 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
377 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
379 Inst.addOperand(MCOperand::CreateExpr(Expr));
382 void addRegOperands(MCInst &Inst, unsigned N) const {
383 assert(N == 1 && "Invalid number of operands!");
384 Inst.addOperand(MCOperand::CreateReg(getReg()));
387 void addImmOperands(MCInst &Inst, unsigned N) const {
388 assert(N == 1 && "Invalid number of operands!");
389 addExpr(Inst, getImm());
392 void addMem8Operands(MCInst &Inst, unsigned N) const {
393 addMemOperands(Inst, N);
395 void addMem16Operands(MCInst &Inst, unsigned N) const {
396 addMemOperands(Inst, N);
398 void addMem32Operands(MCInst &Inst, unsigned N) const {
399 addMemOperands(Inst, N);
401 void addMem64Operands(MCInst &Inst, unsigned N) const {
402 addMemOperands(Inst, N);
404 void addMem80Operands(MCInst &Inst, unsigned N) const {
405 addMemOperands(Inst, N);
407 void addMem128Operands(MCInst &Inst, unsigned N) const {
408 addMemOperands(Inst, N);
410 void addMem256Operands(MCInst &Inst, unsigned N) const {
411 addMemOperands(Inst, N);
413 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
414 addMemOperands(Inst, N);
416 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
417 addMemOperands(Inst, N);
419 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
420 addMemOperands(Inst, N);
422 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
423 addMemOperands(Inst, N);
426 void addMemOperands(MCInst &Inst, unsigned N) const {
427 assert((N == 5) && "Invalid number of operands!");
428 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
429 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
430 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
431 addExpr(Inst, getMemDisp());
432 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
435 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
436 assert((N == 1) && "Invalid number of operands!");
437 // Add as immediates when possible.
438 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
439 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
441 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
444 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
445 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
446 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
447 Res->Tok.Data = Str.data();
448 Res->Tok.Length = Str.size();
452 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
453 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
454 Res->Reg.RegNo = RegNo;
458 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
459 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
464 /// Create an absolute memory operand.
465 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
466 SMLoc EndLoc, unsigned Size = 0,
467 bool NeedSizeDir = false) {
468 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
470 Res->Mem.Disp = Disp;
471 Res->Mem.BaseReg = 0;
472 Res->Mem.IndexReg = 0;
474 Res->Mem.Size = Size;
475 Res->Mem.NeedSizeDir = NeedSizeDir;
479 /// Create a generalized memory operand.
480 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
481 unsigned BaseReg, unsigned IndexReg,
482 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
483 unsigned Size = 0, bool NeedSizeDir = false) {
484 // We should never just have a displacement, that should be parsed as an
485 // absolute memory operand.
486 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
488 // The scale should always be one of {1,2,4,8}.
489 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
491 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
492 Res->Mem.SegReg = SegReg;
493 Res->Mem.Disp = Disp;
494 Res->Mem.BaseReg = BaseReg;
495 Res->Mem.IndexReg = IndexReg;
496 Res->Mem.Scale = Scale;
497 Res->Mem.Size = Size;
498 Res->Mem.NeedSizeDir = NeedSizeDir;
503 } // end anonymous namespace.
505 bool X86AsmParser::isSrcOp(X86Operand &Op) {
506 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
508 return (Op.isMem() &&
509 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
510 isa<MCConstantExpr>(Op.Mem.Disp) &&
511 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
512 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
515 bool X86AsmParser::isDstOp(X86Operand &Op) {
516 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
519 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
520 isa<MCConstantExpr>(Op.Mem.Disp) &&
521 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
522 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
525 bool X86AsmParser::ParseRegister(unsigned &RegNo,
526 SMLoc &StartLoc, SMLoc &EndLoc) {
528 const AsmToken &PercentTok = Parser.getTok();
529 StartLoc = PercentTok.getLoc();
531 // If we encounter a %, ignore it. This code handles registers with and
532 // without the prefix, unprefixed registers can occur in cfi directives.
533 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
534 Parser.Lex(); // Eat percent token.
536 const AsmToken &Tok = Parser.getTok();
537 if (Tok.isNot(AsmToken::Identifier)) {
538 if (isParsingIntelSyntax()) return true;
539 return Error(StartLoc, "invalid register name",
540 SMRange(StartLoc, Tok.getEndLoc()));
543 RegNo = MatchRegisterName(Tok.getString());
545 // If the match failed, try the register name as lowercase.
547 RegNo = MatchRegisterName(Tok.getString().lower());
549 if (!is64BitMode()) {
550 // FIXME: This should be done using Requires<In32BitMode> and
551 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
553 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
555 if (RegNo == X86::RIZ ||
556 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
557 X86II::isX86_64NonExtLowByteReg(RegNo) ||
558 X86II::isX86_64ExtendedReg(RegNo))
559 return Error(StartLoc, "register %"
560 + Tok.getString() + " is only available in 64-bit mode",
561 SMRange(StartLoc, Tok.getEndLoc()));
564 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
565 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
567 EndLoc = Tok.getLoc();
568 Parser.Lex(); // Eat 'st'
570 // Check to see if we have '(4)' after %st.
571 if (getLexer().isNot(AsmToken::LParen))
576 const AsmToken &IntTok = Parser.getTok();
577 if (IntTok.isNot(AsmToken::Integer))
578 return Error(IntTok.getLoc(), "expected stack index");
579 switch (IntTok.getIntVal()) {
580 case 0: RegNo = X86::ST0; break;
581 case 1: RegNo = X86::ST1; break;
582 case 2: RegNo = X86::ST2; break;
583 case 3: RegNo = X86::ST3; break;
584 case 4: RegNo = X86::ST4; break;
585 case 5: RegNo = X86::ST5; break;
586 case 6: RegNo = X86::ST6; break;
587 case 7: RegNo = X86::ST7; break;
588 default: return Error(IntTok.getLoc(), "invalid stack index");
591 if (getParser().Lex().isNot(AsmToken::RParen))
592 return Error(Parser.getTok().getLoc(), "expected ')'");
594 EndLoc = Tok.getLoc();
595 Parser.Lex(); // Eat ')'
599 // If this is "db[0-7]", match it as an alias
601 if (RegNo == 0 && Tok.getString().size() == 3 &&
602 Tok.getString().startswith("db")) {
603 switch (Tok.getString()[2]) {
604 case '0': RegNo = X86::DR0; break;
605 case '1': RegNo = X86::DR1; break;
606 case '2': RegNo = X86::DR2; break;
607 case '3': RegNo = X86::DR3; break;
608 case '4': RegNo = X86::DR4; break;
609 case '5': RegNo = X86::DR5; break;
610 case '6': RegNo = X86::DR6; break;
611 case '7': RegNo = X86::DR7; break;
615 EndLoc = Tok.getLoc();
616 Parser.Lex(); // Eat it.
622 if (isParsingIntelSyntax()) return true;
623 return Error(StartLoc, "invalid register name",
624 SMRange(StartLoc, Tok.getEndLoc()));
627 EndLoc = Tok.getEndLoc();
628 Parser.Lex(); // Eat identifier token.
632 X86Operand *X86AsmParser::ParseOperand() {
633 if (isParsingIntelSyntax())
634 return ParseIntelOperand();
635 return ParseATTOperand();
638 /// getIntelMemOperandSize - Return intel memory operand size.
639 static unsigned getIntelMemOperandSize(StringRef OpStr) {
640 unsigned Size = StringSwitch<unsigned>(OpStr)
641 .Cases("BYTE", "byte", 8)
642 .Cases("WORD", "word", 16)
643 .Cases("DWORD", "dword", 32)
644 .Cases("QWORD", "qword", 64)
645 .Cases("XWORD", "xword", 80)
646 .Cases("XMMWORD", "xmmword", 128)
647 .Cases("YMMWORD", "ymmword", 256)
652 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
654 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
655 SMLoc Start = Parser.getTok().getLoc(), End;
657 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
658 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
661 if (getLexer().isNot(AsmToken::LBrac))
662 return ErrorOperand(Start, "Expected '[' token!");
665 if (getLexer().is(AsmToken::Identifier)) {
667 if (ParseRegister(BaseReg, Start, End)) {
668 // Handle '[' 'symbol' ']'
669 if (getParser().ParseExpression(Disp, End)) return 0;
670 if (getLexer().isNot(AsmToken::RBrac))
671 return ErrorOperand(Start, "Expected ']' token!");
673 return X86Operand::CreateMem(Disp, Start, End, Size);
675 } else if (getLexer().is(AsmToken::Integer)) {
676 int64_t Val = Parser.getTok().getIntVal();
678 SMLoc Loc = Parser.getTok().getLoc();
679 if (getLexer().is(AsmToken::RBrac)) {
680 // Handle '[' number ']'
682 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
684 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
686 return X86Operand::CreateMem(Disp, Start, End, Size);
687 } else if (getLexer().is(AsmToken::Star)) {
688 // Handle '[' Scale*IndexReg ']'
690 SMLoc IdxRegLoc = Parser.getTok().getLoc();
691 if (ParseRegister(IndexReg, IdxRegLoc, End))
692 return ErrorOperand(IdxRegLoc, "Expected register");
695 return ErrorOperand(Loc, "Unexpected token");
698 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
699 bool isPlus = getLexer().is(AsmToken::Plus);
701 SMLoc PlusLoc = Parser.getTok().getLoc();
702 if (getLexer().is(AsmToken::Integer)) {
703 int64_t Val = Parser.getTok().getIntVal();
705 if (getLexer().is(AsmToken::Star)) {
707 SMLoc IdxRegLoc = Parser.getTok().getLoc();
708 if (ParseRegister(IndexReg, IdxRegLoc, End))
709 return ErrorOperand(IdxRegLoc, "Expected register");
711 } else if (getLexer().is(AsmToken::RBrac)) {
712 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
713 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
715 return ErrorOperand(PlusLoc, "unexpected token after +");
716 } else if (getLexer().is(AsmToken::Identifier)) {
717 // This could be an index register or a displacement expression.
718 End = Parser.getTok().getLoc();
720 ParseRegister(IndexReg, Start, End);
721 else if (getParser().ParseExpression(Disp, End)) return 0;
725 if (getLexer().isNot(AsmToken::RBrac))
726 if (getParser().ParseExpression(Disp, End)) return 0;
728 End = Parser.getTok().getLoc();
729 if (getLexer().isNot(AsmToken::RBrac))
730 return ErrorOperand(End, "expected ']' token!");
732 End = Parser.getTok().getLoc();
735 if (!BaseReg && !IndexReg)
736 return X86Operand::CreateMem(Disp, Start, End, Size);
738 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
742 /// ParseIntelMemOperand - Parse intel style memory operand.
743 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
744 const AsmToken &Tok = Parser.getTok();
747 unsigned Size = getIntelMemOperandSize(Tok.getString());
750 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
751 "Unexpected token!");
755 if (getLexer().is(AsmToken::LBrac))
756 return ParseIntelBracExpression(SegReg, Size);
758 if (!ParseRegister(SegReg, Start, End)) {
759 // Handel SegReg : [ ... ]
760 if (getLexer().isNot(AsmToken::Colon))
761 return ErrorOperand(Start, "Expected ':' token!");
762 Parser.Lex(); // Eat :
763 if (getLexer().isNot(AsmToken::LBrac))
764 return ErrorOperand(Start, "Expected '[' token!");
765 return ParseIntelBracExpression(SegReg, Size);
768 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
769 if (getParser().ParseExpression(Disp, End)) return 0;
770 End = Parser.getTok().getLoc();
772 bool NeedSizeDir = false;
773 if (!Size && isParsingInlineAsm()) {
774 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
775 const MCSymbol &Sym = SymRef->getSymbol();
776 // FIXME: The SemaLookup will fail if the name is anything other then an
778 // FIXME: Pass a valid SMLoc.
779 SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Size);
780 NeedSizeDir = Size > 0;
783 return X86Operand::CreateMem(Disp, Start, End, Size, NeedSizeDir);
786 X86Operand *X86AsmParser::ParseIntelOperand() {
787 SMLoc Start = Parser.getTok().getLoc(), End;
790 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
791 getLexer().is(AsmToken::Minus)) {
793 if (!getParser().ParseExpression(Val, End)) {
794 End = Parser.getTok().getLoc();
795 return X86Operand::CreateImm(Val, Start, End);
801 if (!ParseRegister(RegNo, Start, End)) {
802 // If this is a segment register followed by a ':', then this is the start
803 // of a memory reference, otherwise this is a normal register reference.
804 if (getLexer().isNot(AsmToken::Colon))
805 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
807 getParser().Lex(); // Eat the colon.
808 return ParseIntelMemOperand(RegNo, Start);
812 return ParseIntelMemOperand(0, Start);
815 X86Operand *X86AsmParser::ParseATTOperand() {
816 switch (getLexer().getKind()) {
818 // Parse a memory operand with no segment register.
819 return ParseMemOperand(0, Parser.getTok().getLoc());
820 case AsmToken::Percent: {
821 // Read the register.
824 if (ParseRegister(RegNo, Start, End)) return 0;
825 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
826 Error(Start, "%eiz and %riz can only be used as index registers",
827 SMRange(Start, End));
831 // If this is a segment register followed by a ':', then this is the start
832 // of a memory reference, otherwise this is a normal register reference.
833 if (getLexer().isNot(AsmToken::Colon))
834 return X86Operand::CreateReg(RegNo, Start, End);
837 getParser().Lex(); // Eat the colon.
838 return ParseMemOperand(RegNo, Start);
840 case AsmToken::Dollar: {
842 SMLoc Start = Parser.getTok().getLoc(), End;
845 if (getParser().ParseExpression(Val, End))
847 return X86Operand::CreateImm(Val, Start, End);
852 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
853 /// has already been parsed if present.
854 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
856 // We have to disambiguate a parenthesized expression "(4+5)" from the start
857 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
858 // only way to do this without lookahead is to eat the '(' and see what is
860 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
861 if (getLexer().isNot(AsmToken::LParen)) {
863 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
865 // After parsing the base expression we could either have a parenthesized
866 // memory address or not. If not, return now. If so, eat the (.
867 if (getLexer().isNot(AsmToken::LParen)) {
868 // Unless we have a segment register, treat this as an immediate.
870 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
871 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
877 // Okay, we have a '('. We don't know if this is an expression or not, but
878 // so we have to eat the ( to see beyond it.
879 SMLoc LParenLoc = Parser.getTok().getLoc();
880 Parser.Lex(); // Eat the '('.
882 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
883 // Nothing to do here, fall into the code below with the '(' part of the
884 // memory operand consumed.
888 // It must be an parenthesized expression, parse it now.
889 if (getParser().ParseParenExpression(Disp, ExprEnd))
892 // After parsing the base expression we could either have a parenthesized
893 // memory address or not. If not, return now. If so, eat the (.
894 if (getLexer().isNot(AsmToken::LParen)) {
895 // Unless we have a segment register, treat this as an immediate.
897 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
898 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
906 // If we reached here, then we just ate the ( of the memory operand. Process
907 // the rest of the memory operand.
908 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
911 if (getLexer().is(AsmToken::Percent)) {
912 SMLoc StartLoc, EndLoc;
913 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
914 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
915 Error(StartLoc, "eiz and riz can only be used as index registers",
916 SMRange(StartLoc, EndLoc));
921 if (getLexer().is(AsmToken::Comma)) {
922 Parser.Lex(); // Eat the comma.
923 IndexLoc = Parser.getTok().getLoc();
925 // Following the comma we should have either an index register, or a scale
926 // value. We don't support the later form, but we want to parse it
929 // Not that even though it would be completely consistent to support syntax
930 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
931 if (getLexer().is(AsmToken::Percent)) {
933 if (ParseRegister(IndexReg, L, L)) return 0;
935 if (getLexer().isNot(AsmToken::RParen)) {
936 // Parse the scale amount:
937 // ::= ',' [scale-expression]
938 if (getLexer().isNot(AsmToken::Comma)) {
939 Error(Parser.getTok().getLoc(),
940 "expected comma in scale expression");
943 Parser.Lex(); // Eat the comma.
945 if (getLexer().isNot(AsmToken::RParen)) {
946 SMLoc Loc = Parser.getTok().getLoc();
949 if (getParser().ParseAbsoluteExpression(ScaleVal)){
950 Error(Loc, "expected scale expression");
954 // Validate the scale amount.
955 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
956 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
959 Scale = (unsigned)ScaleVal;
962 } else if (getLexer().isNot(AsmToken::RParen)) {
963 // A scale amount without an index is ignored.
965 SMLoc Loc = Parser.getTok().getLoc();
968 if (getParser().ParseAbsoluteExpression(Value))
972 Warning(Loc, "scale factor without index register is ignored");
977 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
978 if (getLexer().isNot(AsmToken::RParen)) {
979 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
982 SMLoc MemEnd = Parser.getTok().getLoc();
983 Parser.Lex(); // Eat the ')'.
985 // If we have both a base register and an index register make sure they are
986 // both 64-bit or 32-bit registers.
987 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
988 if (BaseReg != 0 && IndexReg != 0) {
989 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
990 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
991 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
992 IndexReg != X86::RIZ) {
993 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
996 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
997 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
998 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
999 IndexReg != X86::EIZ){
1000 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1005 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1010 ParseInstruction(StringRef Name, SMLoc NameLoc,
1011 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1012 StringRef PatchedName = Name;
1014 // FIXME: Hack to recognize setneb as setne.
1015 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1016 PatchedName != "setb" && PatchedName != "setnb")
1017 PatchedName = PatchedName.substr(0, Name.size()-1);
1019 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1020 const MCExpr *ExtraImmOp = 0;
1021 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1022 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1023 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1024 bool IsVCMP = PatchedName[0] == 'v';
1025 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1026 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1027 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1031 .Case("unord", 0x03)
1036 /* AVX only from here */
1037 .Case("eq_uq", 0x08)
1040 .Case("false", 0x0B)
1041 .Case("neq_oq", 0x0C)
1045 .Case("eq_os", 0x10)
1046 .Case("lt_oq", 0x11)
1047 .Case("le_oq", 0x12)
1048 .Case("unord_s", 0x13)
1049 .Case("neq_us", 0x14)
1050 .Case("nlt_uq", 0x15)
1051 .Case("nle_uq", 0x16)
1052 .Case("ord_s", 0x17)
1053 .Case("eq_us", 0x18)
1054 .Case("nge_uq", 0x19)
1055 .Case("ngt_uq", 0x1A)
1056 .Case("false_os", 0x1B)
1057 .Case("neq_os", 0x1C)
1058 .Case("ge_oq", 0x1D)
1059 .Case("gt_oq", 0x1E)
1060 .Case("true_us", 0x1F)
1062 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1063 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1064 getParser().getContext());
1065 if (PatchedName.endswith("ss")) {
1066 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1067 } else if (PatchedName.endswith("sd")) {
1068 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1069 } else if (PatchedName.endswith("ps")) {
1070 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1072 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1073 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1078 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1080 if (ExtraImmOp && !isParsingIntelSyntax())
1081 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1083 // Determine whether this is an instruction prefix.
1085 Name == "lock" || Name == "rep" ||
1086 Name == "repe" || Name == "repz" ||
1087 Name == "repne" || Name == "repnz" ||
1088 Name == "rex64" || Name == "data16";
1091 // This does the actual operand parsing. Don't parse any more if we have a
1092 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1093 // just want to parse the "lock" as the first instruction and the "incl" as
1095 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1097 // Parse '*' modifier.
1098 if (getLexer().is(AsmToken::Star)) {
1099 SMLoc Loc = Parser.getTok().getLoc();
1100 Operands.push_back(X86Operand::CreateToken("*", Loc));
1101 Parser.Lex(); // Eat the star.
1104 // Read the first operand.
1105 if (X86Operand *Op = ParseOperand())
1106 Operands.push_back(Op);
1108 Parser.EatToEndOfStatement();
1112 while (getLexer().is(AsmToken::Comma)) {
1113 Parser.Lex(); // Eat the comma.
1115 // Parse and remember the operand.
1116 if (X86Operand *Op = ParseOperand())
1117 Operands.push_back(Op);
1119 Parser.EatToEndOfStatement();
1124 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1125 SMLoc Loc = getLexer().getLoc();
1126 Parser.EatToEndOfStatement();
1127 return Error(Loc, "unexpected token in argument list");
1131 if (getLexer().is(AsmToken::EndOfStatement))
1132 Parser.Lex(); // Consume the EndOfStatement
1133 else if (isPrefix && getLexer().is(AsmToken::Slash))
1134 Parser.Lex(); // Consume the prefix separator Slash
1136 if (ExtraImmOp && isParsingIntelSyntax())
1137 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1139 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1140 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1141 // documented form in various unofficial manuals, so a lot of code uses it.
1142 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1143 Operands.size() == 3) {
1144 X86Operand &Op = *(X86Operand*)Operands.back();
1145 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1146 isa<MCConstantExpr>(Op.Mem.Disp) &&
1147 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1148 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1149 SMLoc Loc = Op.getEndLoc();
1150 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1154 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1155 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1156 Operands.size() == 3) {
1157 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1158 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1159 isa<MCConstantExpr>(Op.Mem.Disp) &&
1160 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1161 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1162 SMLoc Loc = Op.getEndLoc();
1163 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1167 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1168 if (Name.startswith("ins") && Operands.size() == 3 &&
1169 (Name == "insb" || Name == "insw" || Name == "insl")) {
1170 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1171 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1172 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1173 Operands.pop_back();
1174 Operands.pop_back();
1180 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1181 if (Name.startswith("outs") && Operands.size() == 3 &&
1182 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1183 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1184 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1185 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1186 Operands.pop_back();
1187 Operands.pop_back();
1193 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1194 if (Name.startswith("movs") && Operands.size() == 3 &&
1195 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1196 (is64BitMode() && Name == "movsq"))) {
1197 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1198 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1199 if (isSrcOp(Op) && isDstOp(Op2)) {
1200 Operands.pop_back();
1201 Operands.pop_back();
1206 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1207 if (Name.startswith("lods") && Operands.size() == 3 &&
1208 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1209 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1210 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1211 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1212 if (isSrcOp(*Op1) && Op2->isReg()) {
1214 unsigned reg = Op2->getReg();
1215 bool isLods = Name == "lods";
1216 if (reg == X86::AL && (isLods || Name == "lodsb"))
1218 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1220 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1222 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1227 Operands.pop_back();
1228 Operands.pop_back();
1232 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1236 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1237 if (Name.startswith("stos") && Operands.size() == 3 &&
1238 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1239 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1240 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1241 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1242 if (isDstOp(*Op2) && Op1->isReg()) {
1244 unsigned reg = Op1->getReg();
1245 bool isStos = Name == "stos";
1246 if (reg == X86::AL && (isStos || Name == "stosb"))
1248 else if (reg == X86::AX && (isStos || Name == "stosw"))
1250 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1252 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1257 Operands.pop_back();
1258 Operands.pop_back();
1262 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1267 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1269 if ((Name.startswith("shr") || Name.startswith("sar") ||
1270 Name.startswith("shl") || Name.startswith("sal") ||
1271 Name.startswith("rcl") || Name.startswith("rcr") ||
1272 Name.startswith("rol") || Name.startswith("ror")) &&
1273 Operands.size() == 3) {
1274 if (isParsingIntelSyntax()) {
1276 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1277 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1278 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1280 Operands.pop_back();
1283 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1284 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1285 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1287 Operands.erase(Operands.begin() + 1);
1292 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1293 // instalias with an immediate operand yet.
1294 if (Name == "int" && Operands.size() == 2) {
1295 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1296 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1297 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1299 Operands.erase(Operands.begin() + 1);
1300 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1308 processInstruction(MCInst &Inst,
1309 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1310 switch (Inst.getOpcode()) {
1311 default: return false;
1312 case X86::AND16i16: {
1313 if (!Inst.getOperand(0).isImm() ||
1314 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1318 TmpInst.setOpcode(X86::AND16ri8);
1319 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1320 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1321 TmpInst.addOperand(Inst.getOperand(0));
1325 case X86::AND32i32: {
1326 if (!Inst.getOperand(0).isImm() ||
1327 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1331 TmpInst.setOpcode(X86::AND32ri8);
1332 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1333 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1334 TmpInst.addOperand(Inst.getOperand(0));
1338 case X86::AND64i32: {
1339 if (!Inst.getOperand(0).isImm() ||
1340 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1344 TmpInst.setOpcode(X86::AND64ri8);
1345 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1346 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1347 TmpInst.addOperand(Inst.getOperand(0));
1351 case X86::XOR16i16: {
1352 if (!Inst.getOperand(0).isImm() ||
1353 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1357 TmpInst.setOpcode(X86::XOR16ri8);
1358 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1359 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1360 TmpInst.addOperand(Inst.getOperand(0));
1364 case X86::XOR32i32: {
1365 if (!Inst.getOperand(0).isImm() ||
1366 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1370 TmpInst.setOpcode(X86::XOR32ri8);
1371 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1372 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1373 TmpInst.addOperand(Inst.getOperand(0));
1377 case X86::XOR64i32: {
1378 if (!Inst.getOperand(0).isImm() ||
1379 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1383 TmpInst.setOpcode(X86::XOR64ri8);
1384 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1385 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1386 TmpInst.addOperand(Inst.getOperand(0));
1390 case X86::OR16i16: {
1391 if (!Inst.getOperand(0).isImm() ||
1392 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1396 TmpInst.setOpcode(X86::OR16ri8);
1397 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1398 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1399 TmpInst.addOperand(Inst.getOperand(0));
1403 case X86::OR32i32: {
1404 if (!Inst.getOperand(0).isImm() ||
1405 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1409 TmpInst.setOpcode(X86::OR32ri8);
1410 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1411 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1412 TmpInst.addOperand(Inst.getOperand(0));
1416 case X86::OR64i32: {
1417 if (!Inst.getOperand(0).isImm() ||
1418 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1422 TmpInst.setOpcode(X86::OR64ri8);
1423 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1424 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1425 TmpInst.addOperand(Inst.getOperand(0));
1429 case X86::CMP16i16: {
1430 if (!Inst.getOperand(0).isImm() ||
1431 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1435 TmpInst.setOpcode(X86::CMP16ri8);
1436 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1437 TmpInst.addOperand(Inst.getOperand(0));
1441 case X86::CMP32i32: {
1442 if (!Inst.getOperand(0).isImm() ||
1443 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1447 TmpInst.setOpcode(X86::CMP32ri8);
1448 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1449 TmpInst.addOperand(Inst.getOperand(0));
1453 case X86::CMP64i32: {
1454 if (!Inst.getOperand(0).isImm() ||
1455 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1459 TmpInst.setOpcode(X86::CMP64ri8);
1460 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1461 TmpInst.addOperand(Inst.getOperand(0));
1465 case X86::ADD16i16: {
1466 if (!Inst.getOperand(0).isImm() ||
1467 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1471 TmpInst.setOpcode(X86::ADD16ri8);
1472 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1473 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1474 TmpInst.addOperand(Inst.getOperand(0));
1478 case X86::ADD32i32: {
1479 if (!Inst.getOperand(0).isImm() ||
1480 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1484 TmpInst.setOpcode(X86::ADD32ri8);
1485 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1486 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1487 TmpInst.addOperand(Inst.getOperand(0));
1491 case X86::ADD64i32: {
1492 if (!Inst.getOperand(0).isImm() ||
1493 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1497 TmpInst.setOpcode(X86::ADD64ri8);
1498 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1499 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1500 TmpInst.addOperand(Inst.getOperand(0));
1504 case X86::SUB16i16: {
1505 if (!Inst.getOperand(0).isImm() ||
1506 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1510 TmpInst.setOpcode(X86::SUB16ri8);
1511 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1512 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1513 TmpInst.addOperand(Inst.getOperand(0));
1517 case X86::SUB32i32: {
1518 if (!Inst.getOperand(0).isImm() ||
1519 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1523 TmpInst.setOpcode(X86::SUB32ri8);
1524 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1525 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1526 TmpInst.addOperand(Inst.getOperand(0));
1530 case X86::SUB64i32: {
1531 if (!Inst.getOperand(0).isImm() ||
1532 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1536 TmpInst.setOpcode(X86::SUB64ri8);
1537 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1538 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1539 TmpInst.addOperand(Inst.getOperand(0));
1547 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1548 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1549 MCStreamer &Out, unsigned &ErrorInfo,
1550 bool MatchingInlineAsm) {
1551 assert(!Operands.empty() && "Unexpect empty operand list!");
1552 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1553 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1554 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1556 // First, handle aliases that expand to multiple instructions.
1557 // FIXME: This should be replaced with a real .td file alias mechanism.
1558 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1560 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1561 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1562 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1563 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1565 Inst.setOpcode(X86::WAIT);
1567 if (!MatchingInlineAsm)
1568 Out.EmitInstruction(Inst);
1571 StringSwitch<const char*>(Op->getToken())
1572 .Case("finit", "fninit")
1573 .Case("fsave", "fnsave")
1574 .Case("fstcw", "fnstcw")
1575 .Case("fstcww", "fnstcw")
1576 .Case("fstenv", "fnstenv")
1577 .Case("fstsw", "fnstsw")
1578 .Case("fstsww", "fnstsw")
1579 .Case("fclex", "fnclex")
1581 assert(Repl && "Unknown wait-prefixed instruction");
1583 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1586 bool WasOriginallyInvalidOperand = false;
1589 // First, try a direct match.
1590 switch (MatchInstructionImpl(Operands, Inst,
1591 ErrorInfo, MatchingInlineAsm,
1592 isParsingIntelSyntax())) {
1595 // Some instructions need post-processing to, for example, tweak which
1596 // encoding is selected. Loop on it while changes happen so the
1597 // individual transformations can chain off each other.
1598 if (!MatchingInlineAsm)
1599 while (processInstruction(Inst, Operands))
1603 if (!MatchingInlineAsm)
1604 Out.EmitInstruction(Inst);
1605 Opcode = Inst.getOpcode();
1607 case Match_MissingFeature:
1608 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1609 EmptyRanges, MatchingInlineAsm);
1611 case Match_InvalidOperand:
1612 WasOriginallyInvalidOperand = true;
1614 case Match_MnemonicFail:
1618 // FIXME: Ideally, we would only attempt suffix matches for things which are
1619 // valid prefixes, and we could just infer the right unambiguous
1620 // type. However, that requires substantially more matcher support than the
1623 // Change the operand to point to a temporary token.
1624 StringRef Base = Op->getToken();
1625 SmallString<16> Tmp;
1628 Op->setTokenValue(Tmp.str());
1630 // If this instruction starts with an 'f', then it is a floating point stack
1631 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1632 // 80-bit floating point, which use the suffixes s,l,t respectively.
1634 // Otherwise, we assume that this may be an integer instruction, which comes
1635 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1636 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1638 // Check for the various suffix matches.
1639 Tmp[Base.size()] = Suffixes[0];
1640 unsigned ErrorInfoIgnore;
1641 unsigned Match1, Match2, Match3, Match4;
1643 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1644 isParsingIntelSyntax());
1645 Tmp[Base.size()] = Suffixes[1];
1646 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1647 isParsingIntelSyntax());
1648 Tmp[Base.size()] = Suffixes[2];
1649 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1650 isParsingIntelSyntax());
1651 Tmp[Base.size()] = Suffixes[3];
1652 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1653 isParsingIntelSyntax());
1655 // Restore the old token.
1656 Op->setTokenValue(Base);
1658 // If exactly one matched, then we treat that as a successful match (and the
1659 // instruction will already have been filled in correctly, since the failing
1660 // matches won't have modified it).
1661 unsigned NumSuccessfulMatches =
1662 (Match1 == Match_Success) + (Match2 == Match_Success) +
1663 (Match3 == Match_Success) + (Match4 == Match_Success);
1664 if (NumSuccessfulMatches == 1) {
1666 if (!MatchingInlineAsm)
1667 Out.EmitInstruction(Inst);
1668 Opcode = Inst.getOpcode();
1672 // Otherwise, the match failed, try to produce a decent error message.
1674 // If we had multiple suffix matches, then identify this as an ambiguous
1676 if (NumSuccessfulMatches > 1) {
1678 unsigned NumMatches = 0;
1679 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1680 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1681 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1682 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1684 SmallString<126> Msg;
1685 raw_svector_ostream OS(Msg);
1686 OS << "ambiguous instructions require an explicit suffix (could be ";
1687 for (unsigned i = 0; i != NumMatches; ++i) {
1690 if (i + 1 == NumMatches)
1692 OS << "'" << Base << MatchChars[i] << "'";
1695 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1699 // Okay, we know that none of the variants matched successfully.
1701 // If all of the instructions reported an invalid mnemonic, then the original
1702 // mnemonic was invalid.
1703 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1704 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1705 if (!WasOriginallyInvalidOperand) {
1706 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1708 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1709 Ranges, MatchingInlineAsm);
1712 // Recover location info for the operand if we know which was the problem.
1713 if (ErrorInfo != ~0U) {
1714 if (ErrorInfo >= Operands.size())
1715 return Error(IDLoc, "too few operands for instruction",
1716 EmptyRanges, MatchingInlineAsm);
1718 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
1719 if (Operand->getStartLoc().isValid()) {
1720 SMRange OperandRange = Operand->getLocRange();
1721 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1722 OperandRange, MatchingInlineAsm);
1726 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1730 // If one instruction matched with a missing feature, report this as a
1732 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1733 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1734 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1735 EmptyRanges, MatchingInlineAsm);
1739 // If one instruction matched with an invalid operand, report this as an
1741 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1742 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1743 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1748 // If all of these were an outright failure, report it in a useless way.
1749 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1750 EmptyRanges, MatchingInlineAsm);
1755 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1756 StringRef IDVal = DirectiveID.getIdentifier();
1757 if (IDVal == ".word")
1758 return ParseDirectiveWord(2, DirectiveID.getLoc());
1759 else if (IDVal.startswith(".code"))
1760 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1761 else if (IDVal.startswith(".att_syntax")) {
1762 getParser().setAssemblerDialect(0);
1764 } else if (IDVal.startswith(".intel_syntax")) {
1765 getParser().setAssemblerDialect(1);
1766 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1767 if(Parser.getTok().getString() == "noprefix") {
1768 // FIXME : Handle noprefix
1778 /// ParseDirectiveWord
1779 /// ::= .word [ expression (, expression)* ]
1780 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1781 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1783 const MCExpr *Value;
1784 if (getParser().ParseExpression(Value))
1787 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1789 if (getLexer().is(AsmToken::EndOfStatement))
1792 // FIXME: Improve diagnostic.
1793 if (getLexer().isNot(AsmToken::Comma))
1794 return Error(L, "unexpected token in directive");
1803 /// ParseDirectiveCode
1804 /// ::= .code32 | .code64
1805 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1806 if (IDVal == ".code32") {
1808 if (is64BitMode()) {
1810 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1812 } else if (IDVal == ".code64") {
1814 if (!is64BitMode()) {
1816 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1819 return Error(L, "unexpected directive " + IDVal);
1826 extern "C" void LLVMInitializeX86AsmLexer();
1828 // Force static initialization.
1829 extern "C" void LLVMInitializeX86AsmParser() {
1830 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1831 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1832 LLVMInitializeX86AsmLexer();
1835 #define GET_REGISTER_MATCHER
1836 #define GET_MATCHER_IMPLEMENTATION
1837 #include "X86GenAsmMatcher.inc"