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 {
39 MCAsmParser &getParser() const { return Parser; }
41 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
43 bool Error(SMLoc L, const Twine &Msg,
44 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
45 bool MatchingInlineAsm = false) {
46 if (MatchingInlineAsm) return true;
47 return Parser.Error(L, Msg, Ranges);
50 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
55 X86Operand *ParseOperand();
56 X86Operand *ParseATTOperand();
57 X86Operand *ParseIntelOperand();
58 X86Operand *ParseIntelOffsetOfOperator(SMLoc StartLoc);
59 X86Operand *ParseIntelMemOperand(unsigned SegReg, SMLoc StartLoc);
60 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
61 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
63 const MCExpr *ParseIntelDotOperator(const MCExpr *Disp);
65 bool ParseDirectiveWord(unsigned Size, SMLoc L);
66 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
68 bool processInstruction(MCInst &Inst,
69 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
71 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
72 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
73 MCStreamer &Out, unsigned &ErrorInfo,
74 bool MatchingInlineAsm);
76 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
77 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
78 bool isSrcOp(X86Operand &Op);
80 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
81 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
82 bool isDstOp(X86Operand &Op);
84 bool is64BitMode() const {
85 // FIXME: Can tablegen auto-generate this?
86 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
89 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
90 setAvailableFeatures(FB);
93 /// @name Auto-generated Matcher Functions
96 #define GET_ASSEMBLER_HEADER
97 #include "X86GenAsmMatcher.inc"
102 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
103 : MCTargetAsmParser(), STI(sti), Parser(parser) {
105 // Initialize the set of available features.
106 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
108 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
110 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
111 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
113 virtual bool ParseDirective(AsmToken DirectiveID);
115 bool isParsingIntelSyntax() {
116 return getParser().getAssemblerDialect();
119 } // end anonymous namespace
121 /// @name Auto-generated Match Functions
124 static unsigned MatchRegisterName(StringRef Name);
128 static bool isImmSExti16i8Value(uint64_t Value) {
129 return (( Value <= 0x000000000000007FULL)||
130 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
131 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
134 static bool isImmSExti32i8Value(uint64_t Value) {
135 return (( Value <= 0x000000000000007FULL)||
136 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
137 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
140 static bool isImmZExtu32u8Value(uint64_t Value) {
141 return (Value <= 0x00000000000000FFULL);
144 static bool isImmSExti64i8Value(uint64_t Value) {
145 return (( Value <= 0x000000000000007FULL)||
146 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
149 static bool isImmSExti64i32Value(uint64_t Value) {
150 return (( Value <= 0x000000007FFFFFFFULL)||
151 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
155 /// X86Operand - Instances of this class represent a parsed X86 machine
157 struct X86Operand : public MCParsedAsmOperand {
165 SMLoc StartLoc, EndLoc;
193 X86Operand(KindTy K, SMLoc Start, SMLoc End)
194 : Kind(K), StartLoc(Start), EndLoc(End) {}
196 /// getStartLoc - Get the location of the first token of this operand.
197 SMLoc getStartLoc() const { return StartLoc; }
198 /// getEndLoc - Get the location of the last token of this operand.
199 SMLoc getEndLoc() const { return EndLoc; }
200 /// getLocRange - Get the range between the first and last token of this
202 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
203 /// getOffsetOfLoc - Get the location of the offset operator.
204 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
206 virtual void print(raw_ostream &OS) const {}
208 StringRef getToken() const {
209 assert(Kind == Token && "Invalid access!");
210 return StringRef(Tok.Data, Tok.Length);
212 void setTokenValue(StringRef Value) {
213 assert(Kind == Token && "Invalid access!");
214 Tok.Data = Value.data();
215 Tok.Length = Value.size();
218 unsigned getReg() const {
219 assert(Kind == Register && "Invalid access!");
223 const MCExpr *getImm() const {
224 assert(Kind == Immediate && "Invalid access!");
228 const MCExpr *getMemDisp() const {
229 assert(Kind == Memory && "Invalid access!");
232 unsigned getMemSegReg() const {
233 assert(Kind == Memory && "Invalid access!");
236 unsigned getMemBaseReg() const {
237 assert(Kind == Memory && "Invalid access!");
240 unsigned getMemIndexReg() const {
241 assert(Kind == Memory && "Invalid access!");
244 unsigned getMemScale() const {
245 assert(Kind == Memory && "Invalid access!");
249 bool isToken() const {return Kind == Token; }
251 bool isImm() const { return Kind == Immediate; }
253 bool isImmSExti16i8() const {
257 // If this isn't a constant expr, just assume it fits and let relaxation
259 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
263 // Otherwise, check the value is in a range that makes sense for this
265 return isImmSExti16i8Value(CE->getValue());
267 bool isImmSExti32i8() const {
271 // If this isn't a constant expr, just assume it fits and let relaxation
273 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
277 // Otherwise, check the value is in a range that makes sense for this
279 return isImmSExti32i8Value(CE->getValue());
281 bool isImmZExtu32u8() const {
285 // If this isn't a constant expr, just assume it fits and let relaxation
287 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
291 // Otherwise, check the value is in a range that makes sense for this
293 return isImmZExtu32u8Value(CE->getValue());
295 bool isImmSExti64i8() const {
299 // If this isn't a constant expr, just assume it fits and let relaxation
301 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
305 // Otherwise, check the value is in a range that makes sense for this
307 return isImmSExti64i8Value(CE->getValue());
309 bool isImmSExti64i32() const {
313 // If this isn't a constant expr, just assume it fits and let relaxation
315 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
319 // Otherwise, check the value is in a range that makes sense for this
321 return isImmSExti64i32Value(CE->getValue());
324 unsigned getMemSize() const {
325 assert(Kind == Memory && "Invalid access!");
329 bool isOffsetOf() const {
330 return OffsetOfLoc.getPointer();
333 bool needSizeDirective() const {
334 assert(Kind == Memory && "Invalid access!");
335 return Mem.NeedSizeDir;
338 bool isMem() const { return Kind == Memory; }
339 bool isMem8() const {
340 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
342 bool isMem16() const {
343 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
345 bool isMem32() const {
346 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
348 bool isMem64() const {
349 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
351 bool isMem80() const {
352 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
354 bool isMem128() const {
355 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
357 bool isMem256() const {
358 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
361 bool isMemVX32() const {
362 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
363 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
365 bool isMemVY32() const {
366 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
367 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
369 bool isMemVX64() const {
370 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
371 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
373 bool isMemVY64() const {
374 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
375 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
378 bool isAbsMem() const {
379 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
380 !getMemIndexReg() && getMemScale() == 1;
383 bool isReg() const { return Kind == Register; }
385 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
386 // Add as immediates when possible.
387 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
388 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
390 Inst.addOperand(MCOperand::CreateExpr(Expr));
393 void addRegOperands(MCInst &Inst, unsigned N) const {
394 assert(N == 1 && "Invalid number of operands!");
395 Inst.addOperand(MCOperand::CreateReg(getReg()));
398 void addImmOperands(MCInst &Inst, unsigned N) const {
399 assert(N == 1 && "Invalid number of operands!");
400 addExpr(Inst, getImm());
403 void addMem8Operands(MCInst &Inst, unsigned N) const {
404 addMemOperands(Inst, N);
406 void addMem16Operands(MCInst &Inst, unsigned N) const {
407 addMemOperands(Inst, N);
409 void addMem32Operands(MCInst &Inst, unsigned N) const {
410 addMemOperands(Inst, N);
412 void addMem64Operands(MCInst &Inst, unsigned N) const {
413 addMemOperands(Inst, N);
415 void addMem80Operands(MCInst &Inst, unsigned N) const {
416 addMemOperands(Inst, N);
418 void addMem128Operands(MCInst &Inst, unsigned N) const {
419 addMemOperands(Inst, N);
421 void addMem256Operands(MCInst &Inst, unsigned N) const {
422 addMemOperands(Inst, N);
424 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
425 addMemOperands(Inst, N);
427 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
428 addMemOperands(Inst, N);
430 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
431 addMemOperands(Inst, N);
433 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
434 addMemOperands(Inst, N);
437 void addMemOperands(MCInst &Inst, unsigned N) const {
438 assert((N == 5) && "Invalid number of operands!");
439 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
440 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
441 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
442 addExpr(Inst, getMemDisp());
443 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
446 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
447 assert((N == 1) && "Invalid number of operands!");
448 // Add as immediates when possible.
449 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
450 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
452 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
455 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
456 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
457 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
458 Res->Tok.Data = Str.data();
459 Res->Tok.Length = Str.size();
463 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
464 SMLoc OffsetOfLoc = SMLoc()) {
465 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
466 Res->Reg.RegNo = RegNo;
467 Res->OffsetOfLoc = OffsetOfLoc;
471 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
472 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
477 /// Create an absolute memory operand.
478 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
479 unsigned Size = 0, bool NeedSizeDir = false){
480 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
482 Res->Mem.Disp = Disp;
483 Res->Mem.BaseReg = 0;
484 Res->Mem.IndexReg = 0;
486 Res->Mem.Size = Size;
487 Res->Mem.NeedSizeDir = NeedSizeDir;
491 /// Create a generalized memory operand.
492 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
493 unsigned BaseReg, unsigned IndexReg,
494 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
495 unsigned Size = 0, bool NeedSizeDir = false) {
496 // We should never just have a displacement, that should be parsed as an
497 // absolute memory operand.
498 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
500 // The scale should always be one of {1,2,4,8}.
501 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
503 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
504 Res->Mem.SegReg = SegReg;
505 Res->Mem.Disp = Disp;
506 Res->Mem.BaseReg = BaseReg;
507 Res->Mem.IndexReg = IndexReg;
508 Res->Mem.Scale = Scale;
509 Res->Mem.Size = Size;
510 Res->Mem.NeedSizeDir = NeedSizeDir;
515 } // end anonymous namespace.
517 bool X86AsmParser::isSrcOp(X86Operand &Op) {
518 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
520 return (Op.isMem() &&
521 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
522 isa<MCConstantExpr>(Op.Mem.Disp) &&
523 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
524 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
527 bool X86AsmParser::isDstOp(X86Operand &Op) {
528 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
531 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
532 isa<MCConstantExpr>(Op.Mem.Disp) &&
533 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
534 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
537 bool X86AsmParser::ParseRegister(unsigned &RegNo,
538 SMLoc &StartLoc, SMLoc &EndLoc) {
540 const AsmToken &PercentTok = Parser.getTok();
541 StartLoc = PercentTok.getLoc();
543 // If we encounter a %, ignore it. This code handles registers with and
544 // without the prefix, unprefixed registers can occur in cfi directives.
545 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
546 Parser.Lex(); // Eat percent token.
548 const AsmToken &Tok = Parser.getTok();
549 if (Tok.isNot(AsmToken::Identifier)) {
550 if (isParsingIntelSyntax()) return true;
551 return Error(StartLoc, "invalid register name",
552 SMRange(StartLoc, Tok.getEndLoc()));
555 RegNo = MatchRegisterName(Tok.getString());
557 // If the match failed, try the register name as lowercase.
559 RegNo = MatchRegisterName(Tok.getString().lower());
561 if (!is64BitMode()) {
562 // FIXME: This should be done using Requires<In32BitMode> and
563 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
565 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
567 if (RegNo == X86::RIZ ||
568 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
569 X86II::isX86_64NonExtLowByteReg(RegNo) ||
570 X86II::isX86_64ExtendedReg(RegNo))
571 return Error(StartLoc, "register %"
572 + Tok.getString() + " is only available in 64-bit mode",
573 SMRange(StartLoc, Tok.getEndLoc()));
576 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
577 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
579 EndLoc = Tok.getLoc();
580 Parser.Lex(); // Eat 'st'
582 // Check to see if we have '(4)' after %st.
583 if (getLexer().isNot(AsmToken::LParen))
588 const AsmToken &IntTok = Parser.getTok();
589 if (IntTok.isNot(AsmToken::Integer))
590 return Error(IntTok.getLoc(), "expected stack index");
591 switch (IntTok.getIntVal()) {
592 case 0: RegNo = X86::ST0; break;
593 case 1: RegNo = X86::ST1; break;
594 case 2: RegNo = X86::ST2; break;
595 case 3: RegNo = X86::ST3; break;
596 case 4: RegNo = X86::ST4; break;
597 case 5: RegNo = X86::ST5; break;
598 case 6: RegNo = X86::ST6; break;
599 case 7: RegNo = X86::ST7; break;
600 default: return Error(IntTok.getLoc(), "invalid stack index");
603 if (getParser().Lex().isNot(AsmToken::RParen))
604 return Error(Parser.getTok().getLoc(), "expected ')'");
606 EndLoc = Tok.getLoc();
607 Parser.Lex(); // Eat ')'
611 // If this is "db[0-7]", match it as an alias
613 if (RegNo == 0 && Tok.getString().size() == 3 &&
614 Tok.getString().startswith("db")) {
615 switch (Tok.getString()[2]) {
616 case '0': RegNo = X86::DR0; break;
617 case '1': RegNo = X86::DR1; break;
618 case '2': RegNo = X86::DR2; break;
619 case '3': RegNo = X86::DR3; break;
620 case '4': RegNo = X86::DR4; break;
621 case '5': RegNo = X86::DR5; break;
622 case '6': RegNo = X86::DR6; break;
623 case '7': RegNo = X86::DR7; break;
627 EndLoc = Tok.getLoc();
628 Parser.Lex(); // Eat it.
634 if (isParsingIntelSyntax()) return true;
635 return Error(StartLoc, "invalid register name",
636 SMRange(StartLoc, Tok.getEndLoc()));
639 EndLoc = Tok.getEndLoc();
640 Parser.Lex(); // Eat identifier token.
644 X86Operand *X86AsmParser::ParseOperand() {
645 if (isParsingIntelSyntax())
646 return ParseIntelOperand();
647 return ParseATTOperand();
650 /// getIntelMemOperandSize - Return intel memory operand size.
651 static unsigned getIntelMemOperandSize(StringRef OpStr) {
652 unsigned Size = StringSwitch<unsigned>(OpStr)
653 .Cases("BYTE", "byte", 8)
654 .Cases("WORD", "word", 16)
655 .Cases("DWORD", "dword", 32)
656 .Cases("QWORD", "qword", 64)
657 .Cases("XWORD", "xword", 80)
658 .Cases("XMMWORD", "xmmword", 128)
659 .Cases("YMMWORD", "ymmword", 256)
664 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
666 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
667 const AsmToken &Tok = Parser.getTok();
668 SMLoc Start = Tok.getLoc(), End;
670 const MCExpr *Disp = MCConstantExpr::Create(0, getContext());
671 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
674 if (getLexer().isNot(AsmToken::LBrac))
675 return ErrorOperand(Start, "Expected '[' token!");
678 if (getLexer().is(AsmToken::Identifier)) {
680 if (ParseRegister(BaseReg, Start, End)) {
681 // Handle '[' 'symbol' ']'
682 if (getParser().ParseExpression(Disp, End)) return 0;
683 if (getLexer().isNot(AsmToken::RBrac))
684 return ErrorOperand(Start, "Expected ']' token!");
686 return X86Operand::CreateMem(Disp, Start, End, Size);
688 } else if (getLexer().is(AsmToken::Integer)) {
689 int64_t Val = Tok.getIntVal();
691 SMLoc Loc = Tok.getLoc();
692 if (getLexer().is(AsmToken::RBrac)) {
693 // Handle '[' number ']'
695 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
697 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
699 return X86Operand::CreateMem(Disp, Start, End, Size);
700 } else if (getLexer().is(AsmToken::Star)) {
701 // Handle '[' Scale*IndexReg ']'
703 SMLoc IdxRegLoc = Tok.getLoc();
704 if (ParseRegister(IndexReg, IdxRegLoc, End))
705 return ErrorOperand(IdxRegLoc, "Expected register");
708 return ErrorOperand(Loc, "Unexpected token");
711 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
712 bool isPlus = getLexer().is(AsmToken::Plus);
714 SMLoc PlusLoc = Tok.getLoc();
715 if (getLexer().is(AsmToken::Integer)) {
716 int64_t Val = Tok.getIntVal();
718 if (getLexer().is(AsmToken::Star)) {
720 SMLoc IdxRegLoc = Tok.getLoc();
721 if (ParseRegister(IndexReg, IdxRegLoc, End))
722 return ErrorOperand(IdxRegLoc, "Expected register");
724 } else if (getLexer().is(AsmToken::RBrac)) {
725 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
726 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
728 return ErrorOperand(PlusLoc, "unexpected token after +");
729 } else if (getLexer().is(AsmToken::Identifier)) {
730 // This could be an index register or a displacement expression.
733 ParseRegister(IndexReg, Start, End);
734 else if (getParser().ParseExpression(Disp, End)) return 0;
738 if (getLexer().isNot(AsmToken::RBrac))
739 if (getParser().ParseExpression(Disp, End)) return 0;
742 if (getLexer().isNot(AsmToken::RBrac))
743 return ErrorOperand(End, "expected ']' token!");
747 if (Tok.getString().startswith("."))
748 Disp = ParseIntelDotOperator(Disp);
753 if (!BaseReg && !IndexReg)
754 return X86Operand::CreateMem(Disp, Start, End, Size);
756 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
760 /// ParseIntelMemOperand - Parse intel style memory operand.
761 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
762 const AsmToken &Tok = Parser.getTok();
765 unsigned Size = getIntelMemOperandSize(Tok.getString());
768 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
769 "Unexpected token!");
773 if (getLexer().is(AsmToken::LBrac))
774 return ParseIntelBracExpression(SegReg, Size);
776 if (!ParseRegister(SegReg, Start, End)) {
777 // Handel SegReg : [ ... ]
778 if (getLexer().isNot(AsmToken::Colon))
779 return ErrorOperand(Start, "Expected ':' token!");
780 Parser.Lex(); // Eat :
781 if (getLexer().isNot(AsmToken::LBrac))
782 return ErrorOperand(Start, "Expected '[' token!");
783 return ParseIntelBracExpression(SegReg, Size);
786 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
787 if (getParser().ParseExpression(Disp, End)) return 0;
788 End = Parser.getTok().getLoc();
790 bool NeedSizeDir = false;
791 if (!Size && isParsingInlineAsm()) {
792 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
793 const MCSymbol &Sym = SymRef->getSymbol();
794 // FIXME: The SemaLookup will fail if the name is anything other then an
796 // FIXME: Pass a valid SMLoc.
797 SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Size);
798 NeedSizeDir = Size > 0;
801 if (!isParsingInlineAsm())
802 return X86Operand::CreateMem(Disp, Start, End, Size);
804 // When parsing inline assembly we set the base register to a non-zero value
805 // as we don't know the actual value at this time. This is necessary to
806 // get the matching correct in some cases.
807 return X86Operand::CreateMem(/*SegReg*/0, Disp, /*BaseReg*/1, /*IndexReg*/0,
808 /*Scale*/1, Start, End, Size, NeedSizeDir);
811 /// Parse the '.' operator.
812 const MCExpr *X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp) {
813 AsmToken Tok = *&Parser.getTok();
816 StringRef DotDispStr = Tok.getString().drop_front(1);
818 Lex(); // Eat .field.
820 // .Imm gets lexed as a real.
821 if (Tok.is(AsmToken::Real)) {
823 DotDispStr.getAsInteger(10, DotDisp);
824 uint64_t DotDispVal = DotDisp.getZExtValue();
826 // Special case zero dot displacement.
827 if (!DotDispVal) return Disp;
829 // FIXME: Handle non-constant expressions.
830 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp)) {
831 uint64_t OrigDispVal = OrigDisp->getValue();
832 return MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
838 /// Parse the 'offset' operator. This operator is used to specify the
839 /// location rather then the content of a variable.
840 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator(SMLoc Start) {
841 SMLoc OffsetOfLoc = Start;
842 Parser.Lex(); // Eat offset.
843 Start = Parser.getTok().getLoc();
844 assert (Parser.getTok().is(AsmToken::Identifier) && "Expected an identifier");
848 if (getParser().ParseExpression(Val, End))
851 End = Parser.getTok().getLoc();
853 // The offset operator will have an 'r' constraint, thus we need to create
854 // register operand to ensure proper matching. Just pick a GPR based on
855 // the size of a pointer.
856 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
857 return X86Operand::CreateReg(RegNo, Start, End, OffsetOfLoc);
860 X86Operand *X86AsmParser::ParseIntelOperand() {
861 SMLoc Start = Parser.getTok().getLoc(), End;
864 const AsmToken &Tok = Parser.getTok();
865 if ((Tok.getString() == "offset" || Tok.getString() == "OFFSET") &&
866 isParsingInlineAsm())
867 return ParseIntelOffsetOfOperator(Start);
870 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
871 getLexer().is(AsmToken::Minus)) {
873 if (!getParser().ParseExpression(Val, End)) {
874 End = Parser.getTok().getLoc();
875 return X86Operand::CreateImm(Val, Start, End);
881 if (!ParseRegister(RegNo, Start, End)) {
882 // If this is a segment register followed by a ':', then this is the start
883 // of a memory reference, otherwise this is a normal register reference.
884 if (getLexer().isNot(AsmToken::Colon))
885 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
887 getParser().Lex(); // Eat the colon.
888 return ParseIntelMemOperand(RegNo, Start);
892 return ParseIntelMemOperand(0, Start);
895 X86Operand *X86AsmParser::ParseATTOperand() {
896 switch (getLexer().getKind()) {
898 // Parse a memory operand with no segment register.
899 return ParseMemOperand(0, Parser.getTok().getLoc());
900 case AsmToken::Percent: {
901 // Read the register.
904 if (ParseRegister(RegNo, Start, End)) return 0;
905 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
906 Error(Start, "%eiz and %riz can only be used as index registers",
907 SMRange(Start, End));
911 // If this is a segment register followed by a ':', then this is the start
912 // of a memory reference, otherwise this is a normal register reference.
913 if (getLexer().isNot(AsmToken::Colon))
914 return X86Operand::CreateReg(RegNo, Start, End);
917 getParser().Lex(); // Eat the colon.
918 return ParseMemOperand(RegNo, Start);
920 case AsmToken::Dollar: {
922 SMLoc Start = Parser.getTok().getLoc(), End;
925 if (getParser().ParseExpression(Val, End))
927 return X86Operand::CreateImm(Val, Start, End);
932 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
933 /// has already been parsed if present.
934 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
936 // We have to disambiguate a parenthesized expression "(4+5)" from the start
937 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
938 // only way to do this without lookahead is to eat the '(' and see what is
940 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
941 if (getLexer().isNot(AsmToken::LParen)) {
943 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
945 // After parsing the base expression we could either have a parenthesized
946 // memory address or not. If not, return now. If so, eat the (.
947 if (getLexer().isNot(AsmToken::LParen)) {
948 // Unless we have a segment register, treat this as an immediate.
950 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
951 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
957 // Okay, we have a '('. We don't know if this is an expression or not, but
958 // so we have to eat the ( to see beyond it.
959 SMLoc LParenLoc = Parser.getTok().getLoc();
960 Parser.Lex(); // Eat the '('.
962 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
963 // Nothing to do here, fall into the code below with the '(' part of the
964 // memory operand consumed.
968 // It must be an parenthesized expression, parse it now.
969 if (getParser().ParseParenExpression(Disp, ExprEnd))
972 // After parsing the base expression we could either have a parenthesized
973 // memory address or not. If not, return now. If so, eat the (.
974 if (getLexer().isNot(AsmToken::LParen)) {
975 // Unless we have a segment register, treat this as an immediate.
977 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
978 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
986 // If we reached here, then we just ate the ( of the memory operand. Process
987 // the rest of the memory operand.
988 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
991 if (getLexer().is(AsmToken::Percent)) {
992 SMLoc StartLoc, EndLoc;
993 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
994 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
995 Error(StartLoc, "eiz and riz can only be used as index registers",
996 SMRange(StartLoc, EndLoc));
1001 if (getLexer().is(AsmToken::Comma)) {
1002 Parser.Lex(); // Eat the comma.
1003 IndexLoc = Parser.getTok().getLoc();
1005 // Following the comma we should have either an index register, or a scale
1006 // value. We don't support the later form, but we want to parse it
1009 // Not that even though it would be completely consistent to support syntax
1010 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1011 if (getLexer().is(AsmToken::Percent)) {
1013 if (ParseRegister(IndexReg, L, L)) return 0;
1015 if (getLexer().isNot(AsmToken::RParen)) {
1016 // Parse the scale amount:
1017 // ::= ',' [scale-expression]
1018 if (getLexer().isNot(AsmToken::Comma)) {
1019 Error(Parser.getTok().getLoc(),
1020 "expected comma in scale expression");
1023 Parser.Lex(); // Eat the comma.
1025 if (getLexer().isNot(AsmToken::RParen)) {
1026 SMLoc Loc = Parser.getTok().getLoc();
1029 if (getParser().ParseAbsoluteExpression(ScaleVal)){
1030 Error(Loc, "expected scale expression");
1034 // Validate the scale amount.
1035 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1036 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1039 Scale = (unsigned)ScaleVal;
1042 } else if (getLexer().isNot(AsmToken::RParen)) {
1043 // A scale amount without an index is ignored.
1045 SMLoc Loc = Parser.getTok().getLoc();
1048 if (getParser().ParseAbsoluteExpression(Value))
1052 Warning(Loc, "scale factor without index register is ignored");
1057 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1058 if (getLexer().isNot(AsmToken::RParen)) {
1059 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1062 SMLoc MemEnd = Parser.getTok().getLoc();
1063 Parser.Lex(); // Eat the ')'.
1065 // If we have both a base register and an index register make sure they are
1066 // both 64-bit or 32-bit registers.
1067 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1068 if (BaseReg != 0 && IndexReg != 0) {
1069 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1070 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1071 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1072 IndexReg != X86::RIZ) {
1073 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1076 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1077 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1078 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1079 IndexReg != X86::EIZ){
1080 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1085 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1090 ParseInstruction(StringRef Name, SMLoc NameLoc,
1091 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1092 StringRef PatchedName = Name;
1094 // FIXME: Hack to recognize setneb as setne.
1095 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1096 PatchedName != "setb" && PatchedName != "setnb")
1097 PatchedName = PatchedName.substr(0, Name.size()-1);
1099 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1100 const MCExpr *ExtraImmOp = 0;
1101 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1102 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1103 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1104 bool IsVCMP = PatchedName[0] == 'v';
1105 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1106 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1107 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1111 .Case("unord", 0x03)
1116 /* AVX only from here */
1117 .Case("eq_uq", 0x08)
1120 .Case("false", 0x0B)
1121 .Case("neq_oq", 0x0C)
1125 .Case("eq_os", 0x10)
1126 .Case("lt_oq", 0x11)
1127 .Case("le_oq", 0x12)
1128 .Case("unord_s", 0x13)
1129 .Case("neq_us", 0x14)
1130 .Case("nlt_uq", 0x15)
1131 .Case("nle_uq", 0x16)
1132 .Case("ord_s", 0x17)
1133 .Case("eq_us", 0x18)
1134 .Case("nge_uq", 0x19)
1135 .Case("ngt_uq", 0x1A)
1136 .Case("false_os", 0x1B)
1137 .Case("neq_os", 0x1C)
1138 .Case("ge_oq", 0x1D)
1139 .Case("gt_oq", 0x1E)
1140 .Case("true_us", 0x1F)
1142 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1143 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1144 getParser().getContext());
1145 if (PatchedName.endswith("ss")) {
1146 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1147 } else if (PatchedName.endswith("sd")) {
1148 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1149 } else if (PatchedName.endswith("ps")) {
1150 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1152 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1153 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1158 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1160 if (ExtraImmOp && !isParsingIntelSyntax())
1161 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1163 // Determine whether this is an instruction prefix.
1165 Name == "lock" || Name == "rep" ||
1166 Name == "repe" || Name == "repz" ||
1167 Name == "repne" || Name == "repnz" ||
1168 Name == "rex64" || Name == "data16";
1171 // This does the actual operand parsing. Don't parse any more if we have a
1172 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1173 // just want to parse the "lock" as the first instruction and the "incl" as
1175 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1177 // Parse '*' modifier.
1178 if (getLexer().is(AsmToken::Star)) {
1179 SMLoc Loc = Parser.getTok().getLoc();
1180 Operands.push_back(X86Operand::CreateToken("*", Loc));
1181 Parser.Lex(); // Eat the star.
1184 // Read the first operand.
1185 if (X86Operand *Op = ParseOperand())
1186 Operands.push_back(Op);
1188 Parser.EatToEndOfStatement();
1192 while (getLexer().is(AsmToken::Comma)) {
1193 Parser.Lex(); // Eat the comma.
1195 // Parse and remember the operand.
1196 if (X86Operand *Op = ParseOperand())
1197 Operands.push_back(Op);
1199 Parser.EatToEndOfStatement();
1204 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1205 SMLoc Loc = getLexer().getLoc();
1206 Parser.EatToEndOfStatement();
1207 return Error(Loc, "unexpected token in argument list");
1211 if (getLexer().is(AsmToken::EndOfStatement))
1212 Parser.Lex(); // Consume the EndOfStatement
1213 else if (isPrefix && getLexer().is(AsmToken::Slash))
1214 Parser.Lex(); // Consume the prefix separator Slash
1216 if (ExtraImmOp && isParsingIntelSyntax())
1217 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1219 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1220 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1221 // documented form in various unofficial manuals, so a lot of code uses it.
1222 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1223 Operands.size() == 3) {
1224 X86Operand &Op = *(X86Operand*)Operands.back();
1225 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1226 isa<MCConstantExpr>(Op.Mem.Disp) &&
1227 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1228 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1229 SMLoc Loc = Op.getEndLoc();
1230 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1234 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1235 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1236 Operands.size() == 3) {
1237 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1238 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1239 isa<MCConstantExpr>(Op.Mem.Disp) &&
1240 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1241 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1242 SMLoc Loc = Op.getEndLoc();
1243 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1247 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1248 if (Name.startswith("ins") && Operands.size() == 3 &&
1249 (Name == "insb" || Name == "insw" || Name == "insl")) {
1250 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1251 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1252 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1253 Operands.pop_back();
1254 Operands.pop_back();
1260 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1261 if (Name.startswith("outs") && Operands.size() == 3 &&
1262 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1263 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1264 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1265 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1266 Operands.pop_back();
1267 Operands.pop_back();
1273 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1274 if (Name.startswith("movs") && Operands.size() == 3 &&
1275 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1276 (is64BitMode() && Name == "movsq"))) {
1277 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1278 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1279 if (isSrcOp(Op) && isDstOp(Op2)) {
1280 Operands.pop_back();
1281 Operands.pop_back();
1286 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1287 if (Name.startswith("lods") && Operands.size() == 3 &&
1288 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1289 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1290 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1291 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1292 if (isSrcOp(*Op1) && Op2->isReg()) {
1294 unsigned reg = Op2->getReg();
1295 bool isLods = Name == "lods";
1296 if (reg == X86::AL && (isLods || Name == "lodsb"))
1298 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1300 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1302 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1307 Operands.pop_back();
1308 Operands.pop_back();
1312 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1316 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1317 if (Name.startswith("stos") && Operands.size() == 3 &&
1318 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1319 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1320 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1321 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1322 if (isDstOp(*Op2) && Op1->isReg()) {
1324 unsigned reg = Op1->getReg();
1325 bool isStos = Name == "stos";
1326 if (reg == X86::AL && (isStos || Name == "stosb"))
1328 else if (reg == X86::AX && (isStos || Name == "stosw"))
1330 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1332 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1337 Operands.pop_back();
1338 Operands.pop_back();
1342 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1347 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1349 if ((Name.startswith("shr") || Name.startswith("sar") ||
1350 Name.startswith("shl") || Name.startswith("sal") ||
1351 Name.startswith("rcl") || Name.startswith("rcr") ||
1352 Name.startswith("rol") || Name.startswith("ror")) &&
1353 Operands.size() == 3) {
1354 if (isParsingIntelSyntax()) {
1356 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1357 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1358 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1360 Operands.pop_back();
1363 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1364 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1365 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1367 Operands.erase(Operands.begin() + 1);
1372 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1373 // instalias with an immediate operand yet.
1374 if (Name == "int" && Operands.size() == 2) {
1375 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1376 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1377 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1379 Operands.erase(Operands.begin() + 1);
1380 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1388 processInstruction(MCInst &Inst,
1389 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1390 switch (Inst.getOpcode()) {
1391 default: return false;
1392 case X86::AND16i16: {
1393 if (!Inst.getOperand(0).isImm() ||
1394 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1398 TmpInst.setOpcode(X86::AND16ri8);
1399 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1400 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1401 TmpInst.addOperand(Inst.getOperand(0));
1405 case X86::AND32i32: {
1406 if (!Inst.getOperand(0).isImm() ||
1407 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1411 TmpInst.setOpcode(X86::AND32ri8);
1412 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1413 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1414 TmpInst.addOperand(Inst.getOperand(0));
1418 case X86::AND64i32: {
1419 if (!Inst.getOperand(0).isImm() ||
1420 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1424 TmpInst.setOpcode(X86::AND64ri8);
1425 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1426 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1427 TmpInst.addOperand(Inst.getOperand(0));
1431 case X86::XOR16i16: {
1432 if (!Inst.getOperand(0).isImm() ||
1433 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1437 TmpInst.setOpcode(X86::XOR16ri8);
1438 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1439 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1440 TmpInst.addOperand(Inst.getOperand(0));
1444 case X86::XOR32i32: {
1445 if (!Inst.getOperand(0).isImm() ||
1446 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1450 TmpInst.setOpcode(X86::XOR32ri8);
1451 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1452 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1453 TmpInst.addOperand(Inst.getOperand(0));
1457 case X86::XOR64i32: {
1458 if (!Inst.getOperand(0).isImm() ||
1459 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1463 TmpInst.setOpcode(X86::XOR64ri8);
1464 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1465 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1466 TmpInst.addOperand(Inst.getOperand(0));
1470 case X86::OR16i16: {
1471 if (!Inst.getOperand(0).isImm() ||
1472 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1476 TmpInst.setOpcode(X86::OR16ri8);
1477 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1478 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1479 TmpInst.addOperand(Inst.getOperand(0));
1483 case X86::OR32i32: {
1484 if (!Inst.getOperand(0).isImm() ||
1485 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1489 TmpInst.setOpcode(X86::OR32ri8);
1490 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1491 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1492 TmpInst.addOperand(Inst.getOperand(0));
1496 case X86::OR64i32: {
1497 if (!Inst.getOperand(0).isImm() ||
1498 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1502 TmpInst.setOpcode(X86::OR64ri8);
1503 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1504 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1505 TmpInst.addOperand(Inst.getOperand(0));
1509 case X86::CMP16i16: {
1510 if (!Inst.getOperand(0).isImm() ||
1511 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1515 TmpInst.setOpcode(X86::CMP16ri8);
1516 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1517 TmpInst.addOperand(Inst.getOperand(0));
1521 case X86::CMP32i32: {
1522 if (!Inst.getOperand(0).isImm() ||
1523 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1527 TmpInst.setOpcode(X86::CMP32ri8);
1528 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1529 TmpInst.addOperand(Inst.getOperand(0));
1533 case X86::CMP64i32: {
1534 if (!Inst.getOperand(0).isImm() ||
1535 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1539 TmpInst.setOpcode(X86::CMP64ri8);
1540 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1541 TmpInst.addOperand(Inst.getOperand(0));
1545 case X86::ADD16i16: {
1546 if (!Inst.getOperand(0).isImm() ||
1547 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1551 TmpInst.setOpcode(X86::ADD16ri8);
1552 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1553 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1554 TmpInst.addOperand(Inst.getOperand(0));
1558 case X86::ADD32i32: {
1559 if (!Inst.getOperand(0).isImm() ||
1560 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1564 TmpInst.setOpcode(X86::ADD32ri8);
1565 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1566 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1567 TmpInst.addOperand(Inst.getOperand(0));
1571 case X86::ADD64i32: {
1572 if (!Inst.getOperand(0).isImm() ||
1573 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1577 TmpInst.setOpcode(X86::ADD64ri8);
1578 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1579 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1580 TmpInst.addOperand(Inst.getOperand(0));
1584 case X86::SUB16i16: {
1585 if (!Inst.getOperand(0).isImm() ||
1586 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1590 TmpInst.setOpcode(X86::SUB16ri8);
1591 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1592 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1593 TmpInst.addOperand(Inst.getOperand(0));
1597 case X86::SUB32i32: {
1598 if (!Inst.getOperand(0).isImm() ||
1599 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1603 TmpInst.setOpcode(X86::SUB32ri8);
1604 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1605 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1606 TmpInst.addOperand(Inst.getOperand(0));
1610 case X86::SUB64i32: {
1611 if (!Inst.getOperand(0).isImm() ||
1612 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1616 TmpInst.setOpcode(X86::SUB64ri8);
1617 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1618 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1619 TmpInst.addOperand(Inst.getOperand(0));
1627 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1628 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1629 MCStreamer &Out, unsigned &ErrorInfo,
1630 bool MatchingInlineAsm) {
1631 assert(!Operands.empty() && "Unexpect empty operand list!");
1632 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1633 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1634 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1636 // First, handle aliases that expand to multiple instructions.
1637 // FIXME: This should be replaced with a real .td file alias mechanism.
1638 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1640 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1641 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1642 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1643 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1645 Inst.setOpcode(X86::WAIT);
1647 if (!MatchingInlineAsm)
1648 Out.EmitInstruction(Inst);
1651 StringSwitch<const char*>(Op->getToken())
1652 .Case("finit", "fninit")
1653 .Case("fsave", "fnsave")
1654 .Case("fstcw", "fnstcw")
1655 .Case("fstcww", "fnstcw")
1656 .Case("fstenv", "fnstenv")
1657 .Case("fstsw", "fnstsw")
1658 .Case("fstsww", "fnstsw")
1659 .Case("fclex", "fnclex")
1661 assert(Repl && "Unknown wait-prefixed instruction");
1663 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1666 bool WasOriginallyInvalidOperand = false;
1669 // First, try a direct match.
1670 switch (MatchInstructionImpl(Operands, Inst,
1671 ErrorInfo, MatchingInlineAsm,
1672 isParsingIntelSyntax())) {
1675 // Some instructions need post-processing to, for example, tweak which
1676 // encoding is selected. Loop on it while changes happen so the
1677 // individual transformations can chain off each other.
1678 if (!MatchingInlineAsm)
1679 while (processInstruction(Inst, Operands))
1683 if (!MatchingInlineAsm)
1684 Out.EmitInstruction(Inst);
1685 Opcode = Inst.getOpcode();
1687 case Match_MissingFeature:
1688 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1689 EmptyRanges, MatchingInlineAsm);
1691 case Match_InvalidOperand:
1692 WasOriginallyInvalidOperand = true;
1694 case Match_MnemonicFail:
1698 // FIXME: Ideally, we would only attempt suffix matches for things which are
1699 // valid prefixes, and we could just infer the right unambiguous
1700 // type. However, that requires substantially more matcher support than the
1703 // Change the operand to point to a temporary token.
1704 StringRef Base = Op->getToken();
1705 SmallString<16> Tmp;
1708 Op->setTokenValue(Tmp.str());
1710 // If this instruction starts with an 'f', then it is a floating point stack
1711 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1712 // 80-bit floating point, which use the suffixes s,l,t respectively.
1714 // Otherwise, we assume that this may be an integer instruction, which comes
1715 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1716 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1718 // Check for the various suffix matches.
1719 Tmp[Base.size()] = Suffixes[0];
1720 unsigned ErrorInfoIgnore;
1721 unsigned Match1, Match2, Match3, Match4;
1723 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1724 isParsingIntelSyntax());
1725 Tmp[Base.size()] = Suffixes[1];
1726 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1727 isParsingIntelSyntax());
1728 Tmp[Base.size()] = Suffixes[2];
1729 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1730 isParsingIntelSyntax());
1731 Tmp[Base.size()] = Suffixes[3];
1732 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1733 isParsingIntelSyntax());
1735 // Restore the old token.
1736 Op->setTokenValue(Base);
1738 // If exactly one matched, then we treat that as a successful match (and the
1739 // instruction will already have been filled in correctly, since the failing
1740 // matches won't have modified it).
1741 unsigned NumSuccessfulMatches =
1742 (Match1 == Match_Success) + (Match2 == Match_Success) +
1743 (Match3 == Match_Success) + (Match4 == Match_Success);
1744 if (NumSuccessfulMatches == 1) {
1746 if (!MatchingInlineAsm)
1747 Out.EmitInstruction(Inst);
1748 Opcode = Inst.getOpcode();
1752 // Otherwise, the match failed, try to produce a decent error message.
1754 // If we had multiple suffix matches, then identify this as an ambiguous
1756 if (NumSuccessfulMatches > 1) {
1758 unsigned NumMatches = 0;
1759 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1760 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1761 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1762 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1764 SmallString<126> Msg;
1765 raw_svector_ostream OS(Msg);
1766 OS << "ambiguous instructions require an explicit suffix (could be ";
1767 for (unsigned i = 0; i != NumMatches; ++i) {
1770 if (i + 1 == NumMatches)
1772 OS << "'" << Base << MatchChars[i] << "'";
1775 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1779 // Okay, we know that none of the variants matched successfully.
1781 // If all of the instructions reported an invalid mnemonic, then the original
1782 // mnemonic was invalid.
1783 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1784 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1785 if (!WasOriginallyInvalidOperand) {
1786 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1788 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1789 Ranges, MatchingInlineAsm);
1792 // Recover location info for the operand if we know which was the problem.
1793 if (ErrorInfo != ~0U) {
1794 if (ErrorInfo >= Operands.size())
1795 return Error(IDLoc, "too few operands for instruction",
1796 EmptyRanges, MatchingInlineAsm);
1798 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
1799 if (Operand->getStartLoc().isValid()) {
1800 SMRange OperandRange = Operand->getLocRange();
1801 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1802 OperandRange, MatchingInlineAsm);
1806 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1810 // If one instruction matched with a missing feature, report this as a
1812 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1813 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1814 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1815 EmptyRanges, MatchingInlineAsm);
1819 // If one instruction matched with an invalid operand, report this as an
1821 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1822 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1823 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1828 // If all of these were an outright failure, report it in a useless way.
1829 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1830 EmptyRanges, MatchingInlineAsm);
1835 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1836 StringRef IDVal = DirectiveID.getIdentifier();
1837 if (IDVal == ".word")
1838 return ParseDirectiveWord(2, DirectiveID.getLoc());
1839 else if (IDVal.startswith(".code"))
1840 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1841 else if (IDVal.startswith(".att_syntax")) {
1842 getParser().setAssemblerDialect(0);
1844 } else if (IDVal.startswith(".intel_syntax")) {
1845 getParser().setAssemblerDialect(1);
1846 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1847 if(Parser.getTok().getString() == "noprefix") {
1848 // FIXME : Handle noprefix
1858 /// ParseDirectiveWord
1859 /// ::= .word [ expression (, expression)* ]
1860 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1861 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1863 const MCExpr *Value;
1864 if (getParser().ParseExpression(Value))
1867 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1869 if (getLexer().is(AsmToken::EndOfStatement))
1872 // FIXME: Improve diagnostic.
1873 if (getLexer().isNot(AsmToken::Comma))
1874 return Error(L, "unexpected token in directive");
1883 /// ParseDirectiveCode
1884 /// ::= .code32 | .code64
1885 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1886 if (IDVal == ".code32") {
1888 if (is64BitMode()) {
1890 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1892 } else if (IDVal == ".code64") {
1894 if (!is64BitMode()) {
1896 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1899 return Error(L, "unexpected directive " + IDVal);
1906 extern "C" void LLVMInitializeX86AsmLexer();
1908 // Force static initialization.
1909 extern "C" void LLVMInitializeX86AsmParser() {
1910 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1911 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1912 LLVMInitializeX86AsmLexer();
1915 #define GET_REGISTER_MATCHER
1916 #define GET_MATCHER_IMPLEMENTATION
1917 #include "X86GenAsmMatcher.inc"