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/APFloat.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/raw_ostream.h"
35 class X86AsmParser : public MCTargetAsmParser {
38 ParseInstructionInfo *InstInfo;
40 MCAsmParser &getParser() const { return Parser; }
42 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
44 bool Error(SMLoc L, const Twine &Msg,
45 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
46 bool MatchingInlineAsm = false) {
47 if (MatchingInlineAsm) return true;
48 return Parser.Error(L, Msg, Ranges);
51 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
56 X86Operand *ParseOperand();
57 X86Operand *ParseATTOperand();
58 X86Operand *ParseIntelOperand();
59 X86Operand *ParseIntelOffsetOfOperator(SMLoc StartLoc);
60 X86Operand *ParseIntelMemOperand(unsigned SegReg, SMLoc StartLoc);
61 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
62 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
64 bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr **NewDisp,
65 SmallString<64> &Err);
67 bool ParseDirectiveWord(unsigned Size, SMLoc L);
68 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
70 bool processInstruction(MCInst &Inst,
71 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
73 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
74 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
75 MCStreamer &Out, unsigned &ErrorInfo,
76 bool MatchingInlineAsm);
78 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
79 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
80 bool isSrcOp(X86Operand &Op);
82 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
83 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
84 bool isDstOp(X86Operand &Op);
86 bool is64BitMode() const {
87 // FIXME: Can tablegen auto-generate this?
88 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
91 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
92 setAvailableFeatures(FB);
95 /// @name Auto-generated Matcher Functions
98 #define GET_ASSEMBLER_HEADER
99 #include "X86GenAsmMatcher.inc"
104 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
105 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
107 // Initialize the set of available features.
108 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
110 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
112 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
114 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
116 virtual bool ParseDirective(AsmToken DirectiveID);
118 bool isParsingIntelSyntax() {
119 return getParser().getAssemblerDialect();
122 } // end anonymous namespace
124 /// @name Auto-generated Match Functions
127 static unsigned MatchRegisterName(StringRef Name);
131 static bool isImmSExti16i8Value(uint64_t Value) {
132 return (( Value <= 0x000000000000007FULL)||
133 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
134 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
137 static bool isImmSExti32i8Value(uint64_t Value) {
138 return (( Value <= 0x000000000000007FULL)||
139 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
140 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
143 static bool isImmZExtu32u8Value(uint64_t Value) {
144 return (Value <= 0x00000000000000FFULL);
147 static bool isImmSExti64i8Value(uint64_t Value) {
148 return (( Value <= 0x000000000000007FULL)||
149 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
152 static bool isImmSExti64i32Value(uint64_t Value) {
153 return (( Value <= 0x000000007FFFFFFFULL)||
154 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
158 /// X86Operand - Instances of this class represent a parsed X86 machine
160 struct X86Operand : public MCParsedAsmOperand {
168 SMLoc StartLoc, EndLoc;
196 X86Operand(KindTy K, SMLoc Start, SMLoc End)
197 : Kind(K), StartLoc(Start), EndLoc(End) {}
199 /// getStartLoc - Get the location of the first token of this operand.
200 SMLoc getStartLoc() const { return StartLoc; }
201 /// getEndLoc - Get the location of the last token of this operand.
202 SMLoc getEndLoc() const { return EndLoc; }
203 /// getLocRange - Get the range between the first and last token of this
205 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
206 /// getOffsetOfLoc - Get the location of the offset operator.
207 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
209 virtual void print(raw_ostream &OS) const {}
211 StringRef getToken() const {
212 assert(Kind == Token && "Invalid access!");
213 return StringRef(Tok.Data, Tok.Length);
215 void setTokenValue(StringRef Value) {
216 assert(Kind == Token && "Invalid access!");
217 Tok.Data = Value.data();
218 Tok.Length = Value.size();
221 unsigned getReg() const {
222 assert(Kind == Register && "Invalid access!");
226 const MCExpr *getImm() const {
227 assert(Kind == Immediate && "Invalid access!");
231 const MCExpr *getMemDisp() const {
232 assert(Kind == Memory && "Invalid access!");
235 unsigned getMemSegReg() const {
236 assert(Kind == Memory && "Invalid access!");
239 unsigned getMemBaseReg() const {
240 assert(Kind == Memory && "Invalid access!");
243 unsigned getMemIndexReg() const {
244 assert(Kind == Memory && "Invalid access!");
247 unsigned getMemScale() const {
248 assert(Kind == Memory && "Invalid access!");
252 bool isToken() const {return Kind == Token; }
254 bool isImm() const { return Kind == Immediate; }
256 bool isImmSExti16i8() const {
260 // If this isn't a constant expr, just assume it fits and let relaxation
262 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
266 // Otherwise, check the value is in a range that makes sense for this
268 return isImmSExti16i8Value(CE->getValue());
270 bool isImmSExti32i8() const {
274 // If this isn't a constant expr, just assume it fits and let relaxation
276 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
280 // Otherwise, check the value is in a range that makes sense for this
282 return isImmSExti32i8Value(CE->getValue());
284 bool isImmZExtu32u8() const {
288 // If this isn't a constant expr, just assume it fits and let relaxation
290 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
294 // Otherwise, check the value is in a range that makes sense for this
296 return isImmZExtu32u8Value(CE->getValue());
298 bool isImmSExti64i8() const {
302 // If this isn't a constant expr, just assume it fits and let relaxation
304 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
308 // Otherwise, check the value is in a range that makes sense for this
310 return isImmSExti64i8Value(CE->getValue());
312 bool isImmSExti64i32() const {
316 // If this isn't a constant expr, just assume it fits and let relaxation
318 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
322 // Otherwise, check the value is in a range that makes sense for this
324 return isImmSExti64i32Value(CE->getValue());
327 unsigned getMemSize() const {
328 assert(Kind == Memory && "Invalid access!");
332 bool isOffsetOf() const {
333 return OffsetOfLoc.getPointer();
336 bool needSizeDirective() const {
337 assert(Kind == Memory && "Invalid access!");
338 return Mem.NeedSizeDir;
341 bool isMem() const { return Kind == Memory; }
342 bool isMem8() const {
343 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
345 bool isMem16() const {
346 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
348 bool isMem32() const {
349 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
351 bool isMem64() const {
352 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
354 bool isMem80() const {
355 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
357 bool isMem128() const {
358 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
360 bool isMem256() const {
361 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
364 bool isMemVX32() const {
365 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
366 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
368 bool isMemVY32() const {
369 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
370 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
372 bool isMemVX64() const {
373 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
374 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
376 bool isMemVY64() const {
377 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
378 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
381 bool isAbsMem() const {
382 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
383 !getMemIndexReg() && getMemScale() == 1;
386 bool isReg() const { return Kind == Register; }
388 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
389 // Add as immediates when possible.
390 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
391 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
393 Inst.addOperand(MCOperand::CreateExpr(Expr));
396 void addRegOperands(MCInst &Inst, unsigned N) const {
397 assert(N == 1 && "Invalid number of operands!");
398 Inst.addOperand(MCOperand::CreateReg(getReg()));
401 void addImmOperands(MCInst &Inst, unsigned N) const {
402 assert(N == 1 && "Invalid number of operands!");
403 addExpr(Inst, getImm());
406 void addMem8Operands(MCInst &Inst, unsigned N) const {
407 addMemOperands(Inst, N);
409 void addMem16Operands(MCInst &Inst, unsigned N) const {
410 addMemOperands(Inst, N);
412 void addMem32Operands(MCInst &Inst, unsigned N) const {
413 addMemOperands(Inst, N);
415 void addMem64Operands(MCInst &Inst, unsigned N) const {
416 addMemOperands(Inst, N);
418 void addMem80Operands(MCInst &Inst, unsigned N) const {
419 addMemOperands(Inst, N);
421 void addMem128Operands(MCInst &Inst, unsigned N) const {
422 addMemOperands(Inst, N);
424 void addMem256Operands(MCInst &Inst, unsigned N) const {
425 addMemOperands(Inst, N);
427 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
428 addMemOperands(Inst, N);
430 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
431 addMemOperands(Inst, N);
433 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
434 addMemOperands(Inst, N);
436 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
437 addMemOperands(Inst, N);
440 void addMemOperands(MCInst &Inst, unsigned N) const {
441 assert((N == 5) && "Invalid number of operands!");
442 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
443 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
444 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
445 addExpr(Inst, getMemDisp());
446 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
449 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
450 assert((N == 1) && "Invalid number of operands!");
451 // Add as immediates when possible.
452 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
453 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
455 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
458 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
459 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
460 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
461 Res->Tok.Data = Str.data();
462 Res->Tok.Length = Str.size();
466 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
467 SMLoc OffsetOfLoc = SMLoc()) {
468 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
469 Res->Reg.RegNo = RegNo;
470 Res->OffsetOfLoc = OffsetOfLoc;
474 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
475 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
480 /// Create an absolute memory operand.
481 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
482 unsigned Size = 0, bool NeedSizeDir = false){
483 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
485 Res->Mem.Disp = Disp;
486 Res->Mem.BaseReg = 0;
487 Res->Mem.IndexReg = 0;
489 Res->Mem.Size = Size;
490 Res->Mem.NeedSizeDir = NeedSizeDir;
494 /// Create a generalized memory operand.
495 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
496 unsigned BaseReg, unsigned IndexReg,
497 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
498 unsigned Size = 0, bool NeedSizeDir = false) {
499 // We should never just have a displacement, that should be parsed as an
500 // absolute memory operand.
501 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
503 // The scale should always be one of {1,2,4,8}.
504 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
506 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
507 Res->Mem.SegReg = SegReg;
508 Res->Mem.Disp = Disp;
509 Res->Mem.BaseReg = BaseReg;
510 Res->Mem.IndexReg = IndexReg;
511 Res->Mem.Scale = Scale;
512 Res->Mem.Size = Size;
513 Res->Mem.NeedSizeDir = NeedSizeDir;
518 } // end anonymous namespace.
520 bool X86AsmParser::isSrcOp(X86Operand &Op) {
521 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
523 return (Op.isMem() &&
524 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
525 isa<MCConstantExpr>(Op.Mem.Disp) &&
526 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
527 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
530 bool X86AsmParser::isDstOp(X86Operand &Op) {
531 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
534 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
535 isa<MCConstantExpr>(Op.Mem.Disp) &&
536 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
537 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
540 bool X86AsmParser::ParseRegister(unsigned &RegNo,
541 SMLoc &StartLoc, SMLoc &EndLoc) {
543 const AsmToken &PercentTok = Parser.getTok();
544 StartLoc = PercentTok.getLoc();
546 // If we encounter a %, ignore it. This code handles registers with and
547 // without the prefix, unprefixed registers can occur in cfi directives.
548 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
549 Parser.Lex(); // Eat percent token.
551 const AsmToken &Tok = Parser.getTok();
552 if (Tok.isNot(AsmToken::Identifier)) {
553 if (isParsingIntelSyntax()) return true;
554 return Error(StartLoc, "invalid register name",
555 SMRange(StartLoc, Tok.getEndLoc()));
558 RegNo = MatchRegisterName(Tok.getString());
560 // If the match failed, try the register name as lowercase.
562 RegNo = MatchRegisterName(Tok.getString().lower());
564 if (!is64BitMode()) {
565 // FIXME: This should be done using Requires<In32BitMode> and
566 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
568 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
570 if (RegNo == X86::RIZ ||
571 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
572 X86II::isX86_64NonExtLowByteReg(RegNo) ||
573 X86II::isX86_64ExtendedReg(RegNo))
574 return Error(StartLoc, "register %"
575 + Tok.getString() + " is only available in 64-bit mode",
576 SMRange(StartLoc, Tok.getEndLoc()));
579 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
580 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
582 EndLoc = Tok.getLoc();
583 Parser.Lex(); // Eat 'st'
585 // Check to see if we have '(4)' after %st.
586 if (getLexer().isNot(AsmToken::LParen))
591 const AsmToken &IntTok = Parser.getTok();
592 if (IntTok.isNot(AsmToken::Integer))
593 return Error(IntTok.getLoc(), "expected stack index");
594 switch (IntTok.getIntVal()) {
595 case 0: RegNo = X86::ST0; break;
596 case 1: RegNo = X86::ST1; break;
597 case 2: RegNo = X86::ST2; break;
598 case 3: RegNo = X86::ST3; break;
599 case 4: RegNo = X86::ST4; break;
600 case 5: RegNo = X86::ST5; break;
601 case 6: RegNo = X86::ST6; break;
602 case 7: RegNo = X86::ST7; break;
603 default: return Error(IntTok.getLoc(), "invalid stack index");
606 if (getParser().Lex().isNot(AsmToken::RParen))
607 return Error(Parser.getTok().getLoc(), "expected ')'");
609 EndLoc = Tok.getLoc();
610 Parser.Lex(); // Eat ')'
614 // If this is "db[0-7]", match it as an alias
616 if (RegNo == 0 && Tok.getString().size() == 3 &&
617 Tok.getString().startswith("db")) {
618 switch (Tok.getString()[2]) {
619 case '0': RegNo = X86::DR0; break;
620 case '1': RegNo = X86::DR1; break;
621 case '2': RegNo = X86::DR2; break;
622 case '3': RegNo = X86::DR3; break;
623 case '4': RegNo = X86::DR4; break;
624 case '5': RegNo = X86::DR5; break;
625 case '6': RegNo = X86::DR6; break;
626 case '7': RegNo = X86::DR7; break;
630 EndLoc = Tok.getLoc();
631 Parser.Lex(); // Eat it.
637 if (isParsingIntelSyntax()) return true;
638 return Error(StartLoc, "invalid register name",
639 SMRange(StartLoc, Tok.getEndLoc()));
642 EndLoc = Tok.getEndLoc();
643 Parser.Lex(); // Eat identifier token.
647 X86Operand *X86AsmParser::ParseOperand() {
648 if (isParsingIntelSyntax())
649 return ParseIntelOperand();
650 return ParseATTOperand();
653 /// getIntelMemOperandSize - Return intel memory operand size.
654 static unsigned getIntelMemOperandSize(StringRef OpStr) {
655 unsigned Size = StringSwitch<unsigned>(OpStr)
656 .Cases("BYTE", "byte", 8)
657 .Cases("WORD", "word", 16)
658 .Cases("DWORD", "dword", 32)
659 .Cases("QWORD", "qword", 64)
660 .Cases("XWORD", "xword", 80)
661 .Cases("XMMWORD", "xmmword", 128)
662 .Cases("YMMWORD", "ymmword", 256)
667 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
669 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
670 const AsmToken &Tok = Parser.getTok();
671 SMLoc Start = Tok.getLoc(), End;
673 const MCExpr *Disp = MCConstantExpr::Create(0, getContext());
674 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
677 if (getLexer().isNot(AsmToken::LBrac))
678 return ErrorOperand(Start, "Expected '[' token!");
681 if (getLexer().is(AsmToken::Identifier)) {
683 if (ParseRegister(BaseReg, Start, End)) {
684 // Handle '[' 'symbol' ']'
685 if (getParser().ParseExpression(Disp, End)) return 0;
686 if (getLexer().isNot(AsmToken::RBrac))
687 return ErrorOperand(Start, "Expected ']' token!");
689 return X86Operand::CreateMem(Disp, Start, End, Size);
691 } else if (getLexer().is(AsmToken::Integer)) {
692 int64_t Val = Tok.getIntVal();
694 SMLoc Loc = Tok.getLoc();
695 if (getLexer().is(AsmToken::RBrac)) {
696 // Handle '[' number ']'
698 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
700 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
702 return X86Operand::CreateMem(Disp, Start, End, Size);
703 } else if (getLexer().is(AsmToken::Star)) {
704 // Handle '[' Scale*IndexReg ']'
706 SMLoc IdxRegLoc = Tok.getLoc();
707 if (ParseRegister(IndexReg, IdxRegLoc, End))
708 return ErrorOperand(IdxRegLoc, "Expected register");
711 return ErrorOperand(Loc, "Unexpected token");
714 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
715 bool isPlus = getLexer().is(AsmToken::Plus);
717 SMLoc PlusLoc = Tok.getLoc();
718 if (getLexer().is(AsmToken::Integer)) {
719 int64_t Val = Tok.getIntVal();
721 if (getLexer().is(AsmToken::Star)) {
723 SMLoc IdxRegLoc = Tok.getLoc();
724 if (ParseRegister(IndexReg, IdxRegLoc, End))
725 return ErrorOperand(IdxRegLoc, "Expected register");
727 } else if (getLexer().is(AsmToken::RBrac)) {
728 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
729 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
731 return ErrorOperand(PlusLoc, "unexpected token after +");
732 } else if (getLexer().is(AsmToken::Identifier)) {
733 // This could be an index register or a displacement expression.
736 ParseRegister(IndexReg, Start, End);
737 else if (getParser().ParseExpression(Disp, End)) return 0;
741 if (getLexer().isNot(AsmToken::RBrac))
742 if (getParser().ParseExpression(Disp, End)) return 0;
745 if (getLexer().isNot(AsmToken::RBrac))
746 return ErrorOperand(End, "expected ']' token!");
750 if (Tok.getString().startswith(".")) {
752 const MCExpr *NewDisp;
753 if (ParseIntelDotOperator(Disp, &NewDisp, Err))
754 return ErrorOperand(Tok.getLoc(), Err);
756 Parser.Lex(); // Eat the field.
763 if (!BaseReg && !IndexReg)
764 return X86Operand::CreateMem(Disp, Start, End, Size);
766 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
770 /// ParseIntelMemOperand - Parse intel style memory operand.
771 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
772 const AsmToken &Tok = Parser.getTok();
775 unsigned Size = getIntelMemOperandSize(Tok.getString());
778 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
779 "Unexpected token!");
783 if (getLexer().is(AsmToken::LBrac))
784 return ParseIntelBracExpression(SegReg, Size);
786 if (!ParseRegister(SegReg, Start, End)) {
787 // Handel SegReg : [ ... ]
788 if (getLexer().isNot(AsmToken::Colon))
789 return ErrorOperand(Start, "Expected ':' token!");
790 Parser.Lex(); // Eat :
791 if (getLexer().isNot(AsmToken::LBrac))
792 return ErrorOperand(Start, "Expected '[' token!");
793 return ParseIntelBracExpression(SegReg, Size);
796 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
797 if (getParser().ParseExpression(Disp, End)) return 0;
798 End = Parser.getTok().getLoc();
800 bool NeedSizeDir = false;
801 if (!Size && isParsingInlineAsm()) {
802 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
803 const MCSymbol &Sym = SymRef->getSymbol();
804 // FIXME: The SemaLookup will fail if the name is anything other then an
806 // FIXME: Pass a valid SMLoc.
807 SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Size);
808 NeedSizeDir = Size > 0;
811 if (!isParsingInlineAsm())
812 return X86Operand::CreateMem(Disp, Start, End, Size);
814 // When parsing inline assembly we set the base register to a non-zero value
815 // as we don't know the actual value at this time. This is necessary to
816 // get the matching correct in some cases.
817 return X86Operand::CreateMem(/*SegReg*/0, Disp, /*BaseReg*/1, /*IndexReg*/0,
818 /*Scale*/1, Start, End, Size, NeedSizeDir);
821 /// Parse the '.' operator.
822 bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
823 const MCExpr **NewDisp,
824 SmallString<64> &Err) {
825 AsmToken Tok = *&Parser.getTok();
826 uint64_t OrigDispVal, DotDispVal;
828 // FIXME: Handle non-constant expressions.
829 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp)) {
830 OrigDispVal = OrigDisp->getValue();
832 Err = "Non-constant offsets are not supported!";
837 StringRef DotDispStr = Tok.getString().drop_front(1);
839 // .Imm gets lexed as a real.
840 if (Tok.is(AsmToken::Real)) {
842 DotDispStr.getAsInteger(10, DotDisp);
843 DotDispVal = DotDisp.getZExtValue();
845 Err = "Unexpected token type!";
849 // Special case zero dot displacement.
855 *NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
859 /// Parse the 'offset' operator. This operator is used to specify the
860 /// location rather then the content of a variable.
861 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator(SMLoc Start) {
862 SMLoc OffsetOfLoc = Start;
863 Parser.Lex(); // Eat offset.
864 Start = Parser.getTok().getLoc();
865 assert (Parser.getTok().is(AsmToken::Identifier) && "Expected an identifier");
869 if (getParser().ParseExpression(Val, End))
872 End = Parser.getTok().getLoc();
874 // The offset operator will have an 'r' constraint, thus we need to create
875 // register operand to ensure proper matching. Just pick a GPR based on
876 // the size of a pointer.
877 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
878 return X86Operand::CreateReg(RegNo, Start, End, OffsetOfLoc);
881 X86Operand *X86AsmParser::ParseIntelOperand() {
882 SMLoc Start = Parser.getTok().getLoc(), End;
885 const AsmToken &Tok = Parser.getTok();
886 if ((Tok.getString() == "offset" || Tok.getString() == "OFFSET") &&
887 isParsingInlineAsm())
888 return ParseIntelOffsetOfOperator(Start);
891 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
892 getLexer().is(AsmToken::Minus)) {
894 if (!getParser().ParseExpression(Val, End)) {
895 End = Parser.getTok().getLoc();
896 return X86Operand::CreateImm(Val, Start, End);
902 if (!ParseRegister(RegNo, Start, End)) {
903 // If this is a segment register followed by a ':', then this is the start
904 // of a memory reference, otherwise this is a normal register reference.
905 if (getLexer().isNot(AsmToken::Colon))
906 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
908 getParser().Lex(); // Eat the colon.
909 return ParseIntelMemOperand(RegNo, Start);
913 return ParseIntelMemOperand(0, Start);
916 X86Operand *X86AsmParser::ParseATTOperand() {
917 switch (getLexer().getKind()) {
919 // Parse a memory operand with no segment register.
920 return ParseMemOperand(0, Parser.getTok().getLoc());
921 case AsmToken::Percent: {
922 // Read the register.
925 if (ParseRegister(RegNo, Start, End)) return 0;
926 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
927 Error(Start, "%eiz and %riz can only be used as index registers",
928 SMRange(Start, End));
932 // If this is a segment register followed by a ':', then this is the start
933 // of a memory reference, otherwise this is a normal register reference.
934 if (getLexer().isNot(AsmToken::Colon))
935 return X86Operand::CreateReg(RegNo, Start, End);
938 getParser().Lex(); // Eat the colon.
939 return ParseMemOperand(RegNo, Start);
941 case AsmToken::Dollar: {
943 SMLoc Start = Parser.getTok().getLoc(), End;
946 if (getParser().ParseExpression(Val, End))
948 return X86Operand::CreateImm(Val, Start, End);
953 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
954 /// has already been parsed if present.
955 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
957 // We have to disambiguate a parenthesized expression "(4+5)" from the start
958 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
959 // only way to do this without lookahead is to eat the '(' and see what is
961 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
962 if (getLexer().isNot(AsmToken::LParen)) {
964 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
966 // After parsing the base expression we could either have a parenthesized
967 // memory address or not. If not, return now. If so, eat the (.
968 if (getLexer().isNot(AsmToken::LParen)) {
969 // Unless we have a segment register, treat this as an immediate.
971 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
972 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
978 // Okay, we have a '('. We don't know if this is an expression or not, but
979 // so we have to eat the ( to see beyond it.
980 SMLoc LParenLoc = Parser.getTok().getLoc();
981 Parser.Lex(); // Eat the '('.
983 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
984 // Nothing to do here, fall into the code below with the '(' part of the
985 // memory operand consumed.
989 // It must be an parenthesized expression, parse it now.
990 if (getParser().ParseParenExpression(Disp, ExprEnd))
993 // After parsing the base expression we could either have a parenthesized
994 // memory address or not. If not, return now. If so, eat the (.
995 if (getLexer().isNot(AsmToken::LParen)) {
996 // Unless we have a segment register, treat this as an immediate.
998 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
999 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1007 // If we reached here, then we just ate the ( of the memory operand. Process
1008 // the rest of the memory operand.
1009 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1012 if (getLexer().is(AsmToken::Percent)) {
1013 SMLoc StartLoc, EndLoc;
1014 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1015 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1016 Error(StartLoc, "eiz and riz can only be used as index registers",
1017 SMRange(StartLoc, EndLoc));
1022 if (getLexer().is(AsmToken::Comma)) {
1023 Parser.Lex(); // Eat the comma.
1024 IndexLoc = Parser.getTok().getLoc();
1026 // Following the comma we should have either an index register, or a scale
1027 // value. We don't support the later form, but we want to parse it
1030 // Not that even though it would be completely consistent to support syntax
1031 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1032 if (getLexer().is(AsmToken::Percent)) {
1034 if (ParseRegister(IndexReg, L, L)) return 0;
1036 if (getLexer().isNot(AsmToken::RParen)) {
1037 // Parse the scale amount:
1038 // ::= ',' [scale-expression]
1039 if (getLexer().isNot(AsmToken::Comma)) {
1040 Error(Parser.getTok().getLoc(),
1041 "expected comma in scale expression");
1044 Parser.Lex(); // Eat the comma.
1046 if (getLexer().isNot(AsmToken::RParen)) {
1047 SMLoc Loc = Parser.getTok().getLoc();
1050 if (getParser().ParseAbsoluteExpression(ScaleVal)){
1051 Error(Loc, "expected scale expression");
1055 // Validate the scale amount.
1056 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1057 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1060 Scale = (unsigned)ScaleVal;
1063 } else if (getLexer().isNot(AsmToken::RParen)) {
1064 // A scale amount without an index is ignored.
1066 SMLoc Loc = Parser.getTok().getLoc();
1069 if (getParser().ParseAbsoluteExpression(Value))
1073 Warning(Loc, "scale factor without index register is ignored");
1078 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1079 if (getLexer().isNot(AsmToken::RParen)) {
1080 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1083 SMLoc MemEnd = Parser.getTok().getLoc();
1084 Parser.Lex(); // Eat the ')'.
1086 // If we have both a base register and an index register make sure they are
1087 // both 64-bit or 32-bit registers.
1088 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1089 if (BaseReg != 0 && IndexReg != 0) {
1090 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1091 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1092 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1093 IndexReg != X86::RIZ) {
1094 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1097 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1098 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1099 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1100 IndexReg != X86::EIZ){
1101 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1106 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1111 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1112 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1114 StringRef PatchedName = Name;
1116 // FIXME: Hack to recognize setneb as setne.
1117 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1118 PatchedName != "setb" && PatchedName != "setnb")
1119 PatchedName = PatchedName.substr(0, Name.size()-1);
1121 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1122 const MCExpr *ExtraImmOp = 0;
1123 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1124 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1125 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1126 bool IsVCMP = PatchedName[0] == 'v';
1127 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1128 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1129 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1133 .Case("unord", 0x03)
1138 /* AVX only from here */
1139 .Case("eq_uq", 0x08)
1142 .Case("false", 0x0B)
1143 .Case("neq_oq", 0x0C)
1147 .Case("eq_os", 0x10)
1148 .Case("lt_oq", 0x11)
1149 .Case("le_oq", 0x12)
1150 .Case("unord_s", 0x13)
1151 .Case("neq_us", 0x14)
1152 .Case("nlt_uq", 0x15)
1153 .Case("nle_uq", 0x16)
1154 .Case("ord_s", 0x17)
1155 .Case("eq_us", 0x18)
1156 .Case("nge_uq", 0x19)
1157 .Case("ngt_uq", 0x1A)
1158 .Case("false_os", 0x1B)
1159 .Case("neq_os", 0x1C)
1160 .Case("ge_oq", 0x1D)
1161 .Case("gt_oq", 0x1E)
1162 .Case("true_us", 0x1F)
1164 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1165 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1166 getParser().getContext());
1167 if (PatchedName.endswith("ss")) {
1168 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1169 } else if (PatchedName.endswith("sd")) {
1170 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1171 } else if (PatchedName.endswith("ps")) {
1172 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1174 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1175 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1180 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1182 if (ExtraImmOp && !isParsingIntelSyntax())
1183 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1185 // Determine whether this is an instruction prefix.
1187 Name == "lock" || Name == "rep" ||
1188 Name == "repe" || Name == "repz" ||
1189 Name == "repne" || Name == "repnz" ||
1190 Name == "rex64" || Name == "data16";
1193 // This does the actual operand parsing. Don't parse any more if we have a
1194 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1195 // just want to parse the "lock" as the first instruction and the "incl" as
1197 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1199 // Parse '*' modifier.
1200 if (getLexer().is(AsmToken::Star)) {
1201 SMLoc Loc = Parser.getTok().getLoc();
1202 Operands.push_back(X86Operand::CreateToken("*", Loc));
1203 Parser.Lex(); // Eat the star.
1206 // Read the first operand.
1207 if (X86Operand *Op = ParseOperand())
1208 Operands.push_back(Op);
1210 Parser.EatToEndOfStatement();
1214 while (getLexer().is(AsmToken::Comma)) {
1215 Parser.Lex(); // Eat the comma.
1217 // Parse and remember the operand.
1218 if (X86Operand *Op = ParseOperand())
1219 Operands.push_back(Op);
1221 Parser.EatToEndOfStatement();
1226 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1227 SMLoc Loc = getLexer().getLoc();
1228 Parser.EatToEndOfStatement();
1229 return Error(Loc, "unexpected token in argument list");
1233 if (getLexer().is(AsmToken::EndOfStatement))
1234 Parser.Lex(); // Consume the EndOfStatement
1235 else if (isPrefix && getLexer().is(AsmToken::Slash))
1236 Parser.Lex(); // Consume the prefix separator Slash
1238 if (ExtraImmOp && isParsingIntelSyntax())
1239 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1241 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1242 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1243 // documented form in various unofficial manuals, so a lot of code uses it.
1244 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1245 Operands.size() == 3) {
1246 X86Operand &Op = *(X86Operand*)Operands.back();
1247 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1248 isa<MCConstantExpr>(Op.Mem.Disp) &&
1249 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1250 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1251 SMLoc Loc = Op.getEndLoc();
1252 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1256 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1257 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1258 Operands.size() == 3) {
1259 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1260 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1261 isa<MCConstantExpr>(Op.Mem.Disp) &&
1262 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1263 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1264 SMLoc Loc = Op.getEndLoc();
1265 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1269 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1270 if (Name.startswith("ins") && Operands.size() == 3 &&
1271 (Name == "insb" || Name == "insw" || Name == "insl")) {
1272 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1273 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1274 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1275 Operands.pop_back();
1276 Operands.pop_back();
1282 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1283 if (Name.startswith("outs") && Operands.size() == 3 &&
1284 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1285 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1286 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1287 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1288 Operands.pop_back();
1289 Operands.pop_back();
1295 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1296 if (Name.startswith("movs") && Operands.size() == 3 &&
1297 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1298 (is64BitMode() && Name == "movsq"))) {
1299 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1300 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1301 if (isSrcOp(Op) && isDstOp(Op2)) {
1302 Operands.pop_back();
1303 Operands.pop_back();
1308 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1309 if (Name.startswith("lods") && Operands.size() == 3 &&
1310 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1311 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1312 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1313 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1314 if (isSrcOp(*Op1) && Op2->isReg()) {
1316 unsigned reg = Op2->getReg();
1317 bool isLods = Name == "lods";
1318 if (reg == X86::AL && (isLods || Name == "lodsb"))
1320 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1322 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1324 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1329 Operands.pop_back();
1330 Operands.pop_back();
1334 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1338 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1339 if (Name.startswith("stos") && Operands.size() == 3 &&
1340 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1341 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1342 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1343 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1344 if (isDstOp(*Op2) && Op1->isReg()) {
1346 unsigned reg = Op1->getReg();
1347 bool isStos = Name == "stos";
1348 if (reg == X86::AL && (isStos || Name == "stosb"))
1350 else if (reg == X86::AX && (isStos || Name == "stosw"))
1352 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1354 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1359 Operands.pop_back();
1360 Operands.pop_back();
1364 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1369 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1371 if ((Name.startswith("shr") || Name.startswith("sar") ||
1372 Name.startswith("shl") || Name.startswith("sal") ||
1373 Name.startswith("rcl") || Name.startswith("rcr") ||
1374 Name.startswith("rol") || Name.startswith("ror")) &&
1375 Operands.size() == 3) {
1376 if (isParsingIntelSyntax()) {
1378 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1379 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1380 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1382 Operands.pop_back();
1385 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1386 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1387 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1389 Operands.erase(Operands.begin() + 1);
1394 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1395 // instalias with an immediate operand yet.
1396 if (Name == "int" && Operands.size() == 2) {
1397 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1398 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1399 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1401 Operands.erase(Operands.begin() + 1);
1402 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1410 processInstruction(MCInst &Inst,
1411 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1412 switch (Inst.getOpcode()) {
1413 default: return false;
1414 case X86::AND16i16: {
1415 if (!Inst.getOperand(0).isImm() ||
1416 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1420 TmpInst.setOpcode(X86::AND16ri8);
1421 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1422 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1423 TmpInst.addOperand(Inst.getOperand(0));
1427 case X86::AND32i32: {
1428 if (!Inst.getOperand(0).isImm() ||
1429 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1433 TmpInst.setOpcode(X86::AND32ri8);
1434 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1435 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1436 TmpInst.addOperand(Inst.getOperand(0));
1440 case X86::AND64i32: {
1441 if (!Inst.getOperand(0).isImm() ||
1442 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1446 TmpInst.setOpcode(X86::AND64ri8);
1447 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1448 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1449 TmpInst.addOperand(Inst.getOperand(0));
1453 case X86::XOR16i16: {
1454 if (!Inst.getOperand(0).isImm() ||
1455 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1459 TmpInst.setOpcode(X86::XOR16ri8);
1460 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1461 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1462 TmpInst.addOperand(Inst.getOperand(0));
1466 case X86::XOR32i32: {
1467 if (!Inst.getOperand(0).isImm() ||
1468 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1472 TmpInst.setOpcode(X86::XOR32ri8);
1473 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1474 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1475 TmpInst.addOperand(Inst.getOperand(0));
1479 case X86::XOR64i32: {
1480 if (!Inst.getOperand(0).isImm() ||
1481 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1485 TmpInst.setOpcode(X86::XOR64ri8);
1486 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1487 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1488 TmpInst.addOperand(Inst.getOperand(0));
1492 case X86::OR16i16: {
1493 if (!Inst.getOperand(0).isImm() ||
1494 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1498 TmpInst.setOpcode(X86::OR16ri8);
1499 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1500 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1501 TmpInst.addOperand(Inst.getOperand(0));
1505 case X86::OR32i32: {
1506 if (!Inst.getOperand(0).isImm() ||
1507 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1511 TmpInst.setOpcode(X86::OR32ri8);
1512 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1513 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1514 TmpInst.addOperand(Inst.getOperand(0));
1518 case X86::OR64i32: {
1519 if (!Inst.getOperand(0).isImm() ||
1520 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1524 TmpInst.setOpcode(X86::OR64ri8);
1525 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1526 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1527 TmpInst.addOperand(Inst.getOperand(0));
1531 case X86::CMP16i16: {
1532 if (!Inst.getOperand(0).isImm() ||
1533 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1537 TmpInst.setOpcode(X86::CMP16ri8);
1538 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1539 TmpInst.addOperand(Inst.getOperand(0));
1543 case X86::CMP32i32: {
1544 if (!Inst.getOperand(0).isImm() ||
1545 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1549 TmpInst.setOpcode(X86::CMP32ri8);
1550 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1551 TmpInst.addOperand(Inst.getOperand(0));
1555 case X86::CMP64i32: {
1556 if (!Inst.getOperand(0).isImm() ||
1557 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1561 TmpInst.setOpcode(X86::CMP64ri8);
1562 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1563 TmpInst.addOperand(Inst.getOperand(0));
1567 case X86::ADD16i16: {
1568 if (!Inst.getOperand(0).isImm() ||
1569 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1573 TmpInst.setOpcode(X86::ADD16ri8);
1574 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1575 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1576 TmpInst.addOperand(Inst.getOperand(0));
1580 case X86::ADD32i32: {
1581 if (!Inst.getOperand(0).isImm() ||
1582 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1586 TmpInst.setOpcode(X86::ADD32ri8);
1587 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1588 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1589 TmpInst.addOperand(Inst.getOperand(0));
1593 case X86::ADD64i32: {
1594 if (!Inst.getOperand(0).isImm() ||
1595 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1599 TmpInst.setOpcode(X86::ADD64ri8);
1600 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1601 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1602 TmpInst.addOperand(Inst.getOperand(0));
1606 case X86::SUB16i16: {
1607 if (!Inst.getOperand(0).isImm() ||
1608 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1612 TmpInst.setOpcode(X86::SUB16ri8);
1613 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1614 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1615 TmpInst.addOperand(Inst.getOperand(0));
1619 case X86::SUB32i32: {
1620 if (!Inst.getOperand(0).isImm() ||
1621 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1625 TmpInst.setOpcode(X86::SUB32ri8);
1626 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1627 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1628 TmpInst.addOperand(Inst.getOperand(0));
1632 case X86::SUB64i32: {
1633 if (!Inst.getOperand(0).isImm() ||
1634 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1638 TmpInst.setOpcode(X86::SUB64ri8);
1639 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1640 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1641 TmpInst.addOperand(Inst.getOperand(0));
1649 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1650 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1651 MCStreamer &Out, unsigned &ErrorInfo,
1652 bool MatchingInlineAsm) {
1653 assert(!Operands.empty() && "Unexpect empty operand list!");
1654 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1655 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1656 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1658 // First, handle aliases that expand to multiple instructions.
1659 // FIXME: This should be replaced with a real .td file alias mechanism.
1660 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1662 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1663 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1664 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1665 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1667 Inst.setOpcode(X86::WAIT);
1669 if (!MatchingInlineAsm)
1670 Out.EmitInstruction(Inst);
1673 StringSwitch<const char*>(Op->getToken())
1674 .Case("finit", "fninit")
1675 .Case("fsave", "fnsave")
1676 .Case("fstcw", "fnstcw")
1677 .Case("fstcww", "fnstcw")
1678 .Case("fstenv", "fnstenv")
1679 .Case("fstsw", "fnstsw")
1680 .Case("fstsww", "fnstsw")
1681 .Case("fclex", "fnclex")
1683 assert(Repl && "Unknown wait-prefixed instruction");
1685 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1688 bool WasOriginallyInvalidOperand = false;
1691 // First, try a direct match.
1692 switch (MatchInstructionImpl(Operands, Inst,
1693 ErrorInfo, MatchingInlineAsm,
1694 isParsingIntelSyntax())) {
1697 // Some instructions need post-processing to, for example, tweak which
1698 // encoding is selected. Loop on it while changes happen so the
1699 // individual transformations can chain off each other.
1700 if (!MatchingInlineAsm)
1701 while (processInstruction(Inst, Operands))
1705 if (!MatchingInlineAsm)
1706 Out.EmitInstruction(Inst);
1707 Opcode = Inst.getOpcode();
1709 case Match_MissingFeature:
1710 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1711 EmptyRanges, MatchingInlineAsm);
1713 case Match_InvalidOperand:
1714 WasOriginallyInvalidOperand = true;
1716 case Match_MnemonicFail:
1720 // FIXME: Ideally, we would only attempt suffix matches for things which are
1721 // valid prefixes, and we could just infer the right unambiguous
1722 // type. However, that requires substantially more matcher support than the
1725 // Change the operand to point to a temporary token.
1726 StringRef Base = Op->getToken();
1727 SmallString<16> Tmp;
1730 Op->setTokenValue(Tmp.str());
1732 // If this instruction starts with an 'f', then it is a floating point stack
1733 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1734 // 80-bit floating point, which use the suffixes s,l,t respectively.
1736 // Otherwise, we assume that this may be an integer instruction, which comes
1737 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1738 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1740 // Check for the various suffix matches.
1741 Tmp[Base.size()] = Suffixes[0];
1742 unsigned ErrorInfoIgnore;
1743 unsigned Match1, Match2, Match3, Match4;
1745 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1746 isParsingIntelSyntax());
1747 Tmp[Base.size()] = Suffixes[1];
1748 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1749 isParsingIntelSyntax());
1750 Tmp[Base.size()] = Suffixes[2];
1751 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1752 isParsingIntelSyntax());
1753 Tmp[Base.size()] = Suffixes[3];
1754 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1755 isParsingIntelSyntax());
1757 // Restore the old token.
1758 Op->setTokenValue(Base);
1760 // If exactly one matched, then we treat that as a successful match (and the
1761 // instruction will already have been filled in correctly, since the failing
1762 // matches won't have modified it).
1763 unsigned NumSuccessfulMatches =
1764 (Match1 == Match_Success) + (Match2 == Match_Success) +
1765 (Match3 == Match_Success) + (Match4 == Match_Success);
1766 if (NumSuccessfulMatches == 1) {
1768 if (!MatchingInlineAsm)
1769 Out.EmitInstruction(Inst);
1770 Opcode = Inst.getOpcode();
1774 // Otherwise, the match failed, try to produce a decent error message.
1776 // If we had multiple suffix matches, then identify this as an ambiguous
1778 if (NumSuccessfulMatches > 1) {
1780 unsigned NumMatches = 0;
1781 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1782 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1783 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1784 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1786 SmallString<126> Msg;
1787 raw_svector_ostream OS(Msg);
1788 OS << "ambiguous instructions require an explicit suffix (could be ";
1789 for (unsigned i = 0; i != NumMatches; ++i) {
1792 if (i + 1 == NumMatches)
1794 OS << "'" << Base << MatchChars[i] << "'";
1797 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1801 // Okay, we know that none of the variants matched successfully.
1803 // If all of the instructions reported an invalid mnemonic, then the original
1804 // mnemonic was invalid.
1805 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1806 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1807 if (!WasOriginallyInvalidOperand) {
1808 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1810 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1811 Ranges, MatchingInlineAsm);
1814 // Recover location info for the operand if we know which was the problem.
1815 if (ErrorInfo != ~0U) {
1816 if (ErrorInfo >= Operands.size())
1817 return Error(IDLoc, "too few operands for instruction",
1818 EmptyRanges, MatchingInlineAsm);
1820 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
1821 if (Operand->getStartLoc().isValid()) {
1822 SMRange OperandRange = Operand->getLocRange();
1823 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1824 OperandRange, MatchingInlineAsm);
1828 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1832 // If one instruction matched with a missing feature, report this as a
1834 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1835 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1836 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1837 EmptyRanges, MatchingInlineAsm);
1841 // If one instruction matched with an invalid operand, report this as an
1843 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1844 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1845 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1850 // If all of these were an outright failure, report it in a useless way.
1851 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1852 EmptyRanges, MatchingInlineAsm);
1857 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1858 StringRef IDVal = DirectiveID.getIdentifier();
1859 if (IDVal == ".word")
1860 return ParseDirectiveWord(2, DirectiveID.getLoc());
1861 else if (IDVal.startswith(".code"))
1862 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1863 else if (IDVal.startswith(".att_syntax")) {
1864 getParser().setAssemblerDialect(0);
1866 } else if (IDVal.startswith(".intel_syntax")) {
1867 getParser().setAssemblerDialect(1);
1868 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1869 if(Parser.getTok().getString() == "noprefix") {
1870 // FIXME : Handle noprefix
1880 /// ParseDirectiveWord
1881 /// ::= .word [ expression (, expression)* ]
1882 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1883 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1885 const MCExpr *Value;
1886 if (getParser().ParseExpression(Value))
1889 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1891 if (getLexer().is(AsmToken::EndOfStatement))
1894 // FIXME: Improve diagnostic.
1895 if (getLexer().isNot(AsmToken::Comma))
1896 return Error(L, "unexpected token in directive");
1905 /// ParseDirectiveCode
1906 /// ::= .code32 | .code64
1907 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1908 if (IDVal == ".code32") {
1910 if (is64BitMode()) {
1912 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1914 } else if (IDVal == ".code64") {
1916 if (!is64BitMode()) {
1918 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1921 return Error(L, "unexpected directive " + IDVal);
1928 extern "C" void LLVMInitializeX86AsmLexer();
1930 // Force static initialization.
1931 extern "C" void LLVMInitializeX86AsmParser() {
1932 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1933 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1934 LLVMInitializeX86AsmLexer();
1937 #define GET_REGISTER_MATCHER
1938 #define GET_MATCHER_IMPLEMENTATION
1939 #include "X86GenAsmMatcher.inc"