1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/MC/MCTargetAsmParser.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCSymbol.h"
15 #include "llvm/MC/MCInst.h"
16 #include "llvm/MC/MCRegisterInfo.h"
17 #include "llvm/MC/MCSubtargetInfo.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCAsmParser.h"
20 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/raw_ostream.h"
34 class X86AsmParser : public MCTargetAsmParser {
38 MCAsmParser &getParser() const { return Parser; }
40 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
42 bool Error(SMLoc L, const Twine &Msg,
43 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
44 bool MatchingInlineAsm = false) {
45 if (MatchingInlineAsm) return true;
46 return Parser.Error(L, Msg, Ranges);
49 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
54 X86Operand *ParseOperand();
55 X86Operand *ParseATTOperand();
56 X86Operand *ParseIntelOperand();
57 X86Operand *ParseIntelMemOperand(unsigned SegReg, SMLoc StartLoc);
58 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
59 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
61 bool ParseDirectiveWord(unsigned Size, SMLoc L);
62 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
64 bool processInstruction(MCInst &Inst,
65 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
67 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
68 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
69 MCStreamer &Out, unsigned &ErrorInfo,
70 bool MatchingInlineAsm);
72 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
73 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
74 bool isSrcOp(X86Operand &Op);
76 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
77 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
78 bool isDstOp(X86Operand &Op);
80 bool is64BitMode() const {
81 // FIXME: Can tablegen auto-generate this?
82 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
85 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
86 setAvailableFeatures(FB);
89 /// @name Auto-generated Matcher Functions
92 #define GET_ASSEMBLER_HEADER
93 #include "X86GenAsmMatcher.inc"
98 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
99 : MCTargetAsmParser(), STI(sti), Parser(parser) {
101 // Initialize the set of available features.
102 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
104 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
106 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
107 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
109 virtual bool ParseDirective(AsmToken DirectiveID);
111 bool isParsingIntelSyntax() {
112 return getParser().getAssemblerDialect();
115 } // end anonymous namespace
117 /// @name Auto-generated Match Functions
120 static unsigned MatchRegisterName(StringRef Name);
124 static bool isImmSExti16i8Value(uint64_t Value) {
125 return (( Value <= 0x000000000000007FULL)||
126 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
127 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
130 static bool isImmSExti32i8Value(uint64_t Value) {
131 return (( Value <= 0x000000000000007FULL)||
132 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
133 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
136 static bool isImmZExtu32u8Value(uint64_t Value) {
137 return (Value <= 0x00000000000000FFULL);
140 static bool isImmSExti64i8Value(uint64_t Value) {
141 return (( Value <= 0x000000000000007FULL)||
142 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
145 static bool isImmSExti64i32Value(uint64_t Value) {
146 return (( Value <= 0x000000007FFFFFFFULL)||
147 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
151 /// X86Operand - Instances of this class represent a parsed X86 machine
153 struct X86Operand : public MCParsedAsmOperand {
161 SMLoc StartLoc, EndLoc;
189 X86Operand(KindTy K, SMLoc Start, SMLoc End)
190 : Kind(K), StartLoc(Start), EndLoc(End) {}
192 /// getStartLoc - Get the location of the first token of this operand.
193 SMLoc getStartLoc() const { return StartLoc; }
194 /// getEndLoc - Get the location of the last token of this operand.
195 SMLoc getEndLoc() const { return EndLoc; }
196 /// getLocRange - Get the range between the first and last token of this
198 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
200 virtual void print(raw_ostream &OS) const {}
202 StringRef getToken() const {
203 assert(Kind == Token && "Invalid access!");
204 return StringRef(Tok.Data, Tok.Length);
206 void setTokenValue(StringRef Value) {
207 assert(Kind == Token && "Invalid access!");
208 Tok.Data = Value.data();
209 Tok.Length = Value.size();
212 unsigned getReg() const {
213 assert(Kind == Register && "Invalid access!");
217 const MCExpr *getImm() const {
218 assert(Kind == Immediate && "Invalid access!");
222 const MCExpr *getMemDisp() const {
223 assert(Kind == Memory && "Invalid access!");
226 unsigned getMemSegReg() const {
227 assert(Kind == Memory && "Invalid access!");
230 unsigned getMemBaseReg() const {
231 assert(Kind == Memory && "Invalid access!");
234 unsigned getMemIndexReg() const {
235 assert(Kind == Memory && "Invalid access!");
238 unsigned getMemScale() const {
239 assert(Kind == Memory && "Invalid access!");
243 bool isToken() const {return Kind == Token; }
245 bool isImm() const { return Kind == Immediate; }
247 bool isImmSExti16i8() const {
251 // If this isn't a constant expr, just assume it fits and let relaxation
253 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
257 // Otherwise, check the value is in a range that makes sense for this
259 return isImmSExti16i8Value(CE->getValue());
261 bool isImmSExti32i8() const {
265 // If this isn't a constant expr, just assume it fits and let relaxation
267 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
271 // Otherwise, check the value is in a range that makes sense for this
273 return isImmSExti32i8Value(CE->getValue());
275 bool isImmZExtu32u8() const {
279 // If this isn't a constant expr, just assume it fits and let relaxation
281 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
285 // Otherwise, check the value is in a range that makes sense for this
287 return isImmZExtu32u8Value(CE->getValue());
289 bool isImmSExti64i8() const {
293 // If this isn't a constant expr, just assume it fits and let relaxation
295 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
299 // Otherwise, check the value is in a range that makes sense for this
301 return isImmSExti64i8Value(CE->getValue());
303 bool isImmSExti64i32() const {
307 // If this isn't a constant expr, just assume it fits and let relaxation
309 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
313 // Otherwise, check the value is in a range that makes sense for this
315 return isImmSExti64i32Value(CE->getValue());
318 unsigned getMemSize() const {
319 assert(Kind == Memory && "Invalid access!");
323 bool isOffsetOf() const {
324 assert(Kind == Memory && "Invalid access!");
328 bool needSizeDirective() const {
329 assert(Kind == Memory && "Invalid access!");
330 return Mem.NeedSizeDir;
333 bool isMem() const { return Kind == Memory; }
334 bool isMem8() const {
335 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
337 bool isMem16() const {
338 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
340 bool isMem32() const {
341 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
343 bool isMem64() const {
344 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
346 bool isMem80() const {
347 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
349 bool isMem128() const {
350 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
352 bool isMem256() const {
353 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
356 bool isMemVX32() const {
357 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
358 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
360 bool isMemVY32() const {
361 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
362 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
364 bool isMemVX64() const {
365 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
366 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
368 bool isMemVY64() const {
369 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
370 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
373 bool isAbsMem() const {
374 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
375 !getMemIndexReg() && getMemScale() == 1;
378 bool isReg() const { return Kind == Register; }
380 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
381 // Add as immediates when possible.
382 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
383 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
385 Inst.addOperand(MCOperand::CreateExpr(Expr));
388 void addRegOperands(MCInst &Inst, unsigned N) const {
389 assert(N == 1 && "Invalid number of operands!");
390 Inst.addOperand(MCOperand::CreateReg(getReg()));
393 void addImmOperands(MCInst &Inst, unsigned N) const {
394 assert(N == 1 && "Invalid number of operands!");
395 addExpr(Inst, getImm());
398 void addMem8Operands(MCInst &Inst, unsigned N) const {
399 addMemOperands(Inst, N);
401 void addMem16Operands(MCInst &Inst, unsigned N) const {
402 addMemOperands(Inst, N);
404 void addMem32Operands(MCInst &Inst, unsigned N) const {
405 addMemOperands(Inst, N);
407 void addMem64Operands(MCInst &Inst, unsigned N) const {
408 addMemOperands(Inst, N);
410 void addMem80Operands(MCInst &Inst, unsigned N) const {
411 addMemOperands(Inst, N);
413 void addMem128Operands(MCInst &Inst, unsigned N) const {
414 addMemOperands(Inst, N);
416 void addMem256Operands(MCInst &Inst, unsigned N) const {
417 addMemOperands(Inst, N);
419 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
420 addMemOperands(Inst, N);
422 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
423 addMemOperands(Inst, N);
425 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
426 addMemOperands(Inst, N);
428 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
429 addMemOperands(Inst, N);
432 void addMemOperands(MCInst &Inst, unsigned N) const {
433 assert((N == 5) && "Invalid number of operands!");
434 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
435 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
436 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
437 addExpr(Inst, getMemDisp());
438 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
441 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
442 assert((N == 1) && "Invalid number of operands!");
443 // Add as immediates when possible.
444 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
445 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
447 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
450 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
451 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
452 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
453 Res->Tok.Data = Str.data();
454 Res->Tok.Length = Str.size();
458 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
459 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
460 Res->Reg.RegNo = RegNo;
464 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
465 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
470 /// Create an absolute memory operand.
471 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
472 SMLoc EndLoc, unsigned Size = 0,
473 bool OffsetOf = false, bool NeedSizeDir = false){
474 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
476 Res->Mem.Disp = Disp;
477 Res->Mem.BaseReg = 0;
478 Res->Mem.IndexReg = 0;
480 Res->Mem.Size = Size;
481 Res->Mem.OffsetOf = OffsetOf;
482 Res->Mem.NeedSizeDir = NeedSizeDir;
486 /// Create a generalized memory operand.
487 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
488 unsigned BaseReg, unsigned IndexReg,
489 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
490 unsigned Size = 0, bool OffsetOf = false,
491 bool NeedSizeDir = false) {
492 // We should never just have a displacement, that should be parsed as an
493 // absolute memory operand.
494 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
496 // The scale should always be one of {1,2,4,8}.
497 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
499 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
500 Res->Mem.SegReg = SegReg;
501 Res->Mem.Disp = Disp;
502 Res->Mem.BaseReg = BaseReg;
503 Res->Mem.IndexReg = IndexReg;
504 Res->Mem.Scale = Scale;
505 Res->Mem.Size = Size;
506 Res->Mem.OffsetOf = OffsetOf;
507 Res->Mem.NeedSizeDir = NeedSizeDir;
512 } // end anonymous namespace.
514 bool X86AsmParser::isSrcOp(X86Operand &Op) {
515 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
517 return (Op.isMem() &&
518 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
519 isa<MCConstantExpr>(Op.Mem.Disp) &&
520 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
521 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
524 bool X86AsmParser::isDstOp(X86Operand &Op) {
525 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
528 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
529 isa<MCConstantExpr>(Op.Mem.Disp) &&
530 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
531 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
534 bool X86AsmParser::ParseRegister(unsigned &RegNo,
535 SMLoc &StartLoc, SMLoc &EndLoc) {
537 const AsmToken &PercentTok = Parser.getTok();
538 StartLoc = PercentTok.getLoc();
540 // If we encounter a %, ignore it. This code handles registers with and
541 // without the prefix, unprefixed registers can occur in cfi directives.
542 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
543 Parser.Lex(); // Eat percent token.
545 const AsmToken &Tok = Parser.getTok();
546 if (Tok.isNot(AsmToken::Identifier)) {
547 if (isParsingIntelSyntax()) return true;
548 return Error(StartLoc, "invalid register name",
549 SMRange(StartLoc, Tok.getEndLoc()));
552 RegNo = MatchRegisterName(Tok.getString());
554 // If the match failed, try the register name as lowercase.
556 RegNo = MatchRegisterName(Tok.getString().lower());
558 if (!is64BitMode()) {
559 // FIXME: This should be done using Requires<In32BitMode> and
560 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
562 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
564 if (RegNo == X86::RIZ ||
565 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
566 X86II::isX86_64NonExtLowByteReg(RegNo) ||
567 X86II::isX86_64ExtendedReg(RegNo))
568 return Error(StartLoc, "register %"
569 + Tok.getString() + " is only available in 64-bit mode",
570 SMRange(StartLoc, Tok.getEndLoc()));
573 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
574 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
576 EndLoc = Tok.getLoc();
577 Parser.Lex(); // Eat 'st'
579 // Check to see if we have '(4)' after %st.
580 if (getLexer().isNot(AsmToken::LParen))
585 const AsmToken &IntTok = Parser.getTok();
586 if (IntTok.isNot(AsmToken::Integer))
587 return Error(IntTok.getLoc(), "expected stack index");
588 switch (IntTok.getIntVal()) {
589 case 0: RegNo = X86::ST0; break;
590 case 1: RegNo = X86::ST1; break;
591 case 2: RegNo = X86::ST2; break;
592 case 3: RegNo = X86::ST3; break;
593 case 4: RegNo = X86::ST4; break;
594 case 5: RegNo = X86::ST5; break;
595 case 6: RegNo = X86::ST6; break;
596 case 7: RegNo = X86::ST7; break;
597 default: return Error(IntTok.getLoc(), "invalid stack index");
600 if (getParser().Lex().isNot(AsmToken::RParen))
601 return Error(Parser.getTok().getLoc(), "expected ')'");
603 EndLoc = Tok.getLoc();
604 Parser.Lex(); // Eat ')'
608 // If this is "db[0-7]", match it as an alias
610 if (RegNo == 0 && Tok.getString().size() == 3 &&
611 Tok.getString().startswith("db")) {
612 switch (Tok.getString()[2]) {
613 case '0': RegNo = X86::DR0; break;
614 case '1': RegNo = X86::DR1; break;
615 case '2': RegNo = X86::DR2; break;
616 case '3': RegNo = X86::DR3; break;
617 case '4': RegNo = X86::DR4; break;
618 case '5': RegNo = X86::DR5; break;
619 case '6': RegNo = X86::DR6; break;
620 case '7': RegNo = X86::DR7; break;
624 EndLoc = Tok.getLoc();
625 Parser.Lex(); // Eat it.
631 if (isParsingIntelSyntax()) return true;
632 return Error(StartLoc, "invalid register name",
633 SMRange(StartLoc, Tok.getEndLoc()));
636 EndLoc = Tok.getEndLoc();
637 Parser.Lex(); // Eat identifier token.
641 X86Operand *X86AsmParser::ParseOperand() {
642 if (isParsingIntelSyntax())
643 return ParseIntelOperand();
644 return ParseATTOperand();
647 /// getIntelMemOperandSize - Return intel memory operand size.
648 static unsigned getIntelMemOperandSize(StringRef OpStr) {
649 unsigned Size = StringSwitch<unsigned>(OpStr)
650 .Cases("BYTE", "byte", 8)
651 .Cases("WORD", "word", 16)
652 .Cases("DWORD", "dword", 32)
653 .Cases("QWORD", "qword", 64)
654 .Cases("XWORD", "xword", 80)
655 .Cases("XMMWORD", "xmmword", 128)
656 .Cases("YMMWORD", "ymmword", 256)
661 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
663 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
664 SMLoc Start = Parser.getTok().getLoc(), End;
666 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
667 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
670 if (getLexer().isNot(AsmToken::LBrac))
671 return ErrorOperand(Start, "Expected '[' token!");
674 if (getLexer().is(AsmToken::Identifier)) {
676 if (ParseRegister(BaseReg, Start, End)) {
677 // Handle '[' 'symbol' ']'
678 if (getParser().ParseExpression(Disp, End)) return 0;
679 if (getLexer().isNot(AsmToken::RBrac))
680 return ErrorOperand(Start, "Expected ']' token!");
682 return X86Operand::CreateMem(Disp, Start, End, Size);
684 } else if (getLexer().is(AsmToken::Integer)) {
685 int64_t Val = Parser.getTok().getIntVal();
687 SMLoc Loc = Parser.getTok().getLoc();
688 if (getLexer().is(AsmToken::RBrac)) {
689 // Handle '[' number ']'
691 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
693 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
695 return X86Operand::CreateMem(Disp, Start, End, Size);
696 } else if (getLexer().is(AsmToken::Star)) {
697 // Handle '[' Scale*IndexReg ']'
699 SMLoc IdxRegLoc = Parser.getTok().getLoc();
700 if (ParseRegister(IndexReg, IdxRegLoc, End))
701 return ErrorOperand(IdxRegLoc, "Expected register");
704 return ErrorOperand(Loc, "Unexpected token");
707 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
708 bool isPlus = getLexer().is(AsmToken::Plus);
710 SMLoc PlusLoc = Parser.getTok().getLoc();
711 if (getLexer().is(AsmToken::Integer)) {
712 int64_t Val = Parser.getTok().getIntVal();
714 if (getLexer().is(AsmToken::Star)) {
716 SMLoc IdxRegLoc = Parser.getTok().getLoc();
717 if (ParseRegister(IndexReg, IdxRegLoc, End))
718 return ErrorOperand(IdxRegLoc, "Expected register");
720 } else if (getLexer().is(AsmToken::RBrac)) {
721 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
722 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
724 return ErrorOperand(PlusLoc, "unexpected token after +");
725 } else if (getLexer().is(AsmToken::Identifier)) {
726 // This could be an index register or a displacement expression.
727 End = Parser.getTok().getLoc();
729 ParseRegister(IndexReg, Start, End);
730 else if (getParser().ParseExpression(Disp, End)) return 0;
734 if (getLexer().isNot(AsmToken::RBrac))
735 if (getParser().ParseExpression(Disp, End)) return 0;
737 End = Parser.getTok().getLoc();
738 if (getLexer().isNot(AsmToken::RBrac))
739 return ErrorOperand(End, "expected ']' token!");
741 End = Parser.getTok().getLoc();
744 if (!BaseReg && !IndexReg)
745 return X86Operand::CreateMem(Disp, Start, End, Size);
747 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
751 /// ParseIntelMemOperand - Parse intel style memory operand.
752 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
753 const AsmToken &Tok = Parser.getTok();
756 unsigned Size = getIntelMemOperandSize(Tok.getString());
759 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
760 "Unexpected token!");
764 // Parse the 'offset' operator. This operator is used to specify the
765 // location rather then the content of a variable.
766 bool OffsetOf = false;
767 if(isParsingInlineAsm() && (Tok.getString() == "offset" ||
768 Tok.getString() == "OFFSET")) {
770 Parser.Lex(); // Eat offset.
773 if (getLexer().is(AsmToken::LBrac)) {
774 assert (!OffsetOf && "Unexpected offset operator!");
775 return ParseIntelBracExpression(SegReg, Size);
778 if (!ParseRegister(SegReg, Start, End)) {
779 assert (!OffsetOf && "Unexpected offset operator!");
780 // Handel SegReg : [ ... ]
781 if (getLexer().isNot(AsmToken::Colon))
782 return ErrorOperand(Start, "Expected ':' token!");
783 Parser.Lex(); // Eat :
784 if (getLexer().isNot(AsmToken::LBrac))
785 return ErrorOperand(Start, "Expected '[' token!");
786 return ParseIntelBracExpression(SegReg, Size);
789 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
790 if (getParser().ParseExpression(Disp, End)) return 0;
791 End = Parser.getTok().getLoc();
793 bool NeedSizeDir = false;
794 if (!Size && isParsingInlineAsm()) {
795 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
796 const MCSymbol &Sym = SymRef->getSymbol();
797 // FIXME: The SemaLookup will fail if the name is anything other then an
799 // FIXME: Pass a valid SMLoc.
800 SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Size);
801 NeedSizeDir = Size > 0;
804 return X86Operand::CreateMem(Disp, Start, End, Size, OffsetOf, NeedSizeDir);
807 X86Operand *X86AsmParser::ParseIntelOperand() {
808 SMLoc Start = Parser.getTok().getLoc(), End;
811 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
812 getLexer().is(AsmToken::Minus)) {
814 if (!getParser().ParseExpression(Val, End)) {
815 End = Parser.getTok().getLoc();
816 return X86Operand::CreateImm(Val, Start, End);
822 if (!ParseRegister(RegNo, Start, End)) {
823 // If this is a segment register followed by a ':', then this is the start
824 // of a memory reference, otherwise this is a normal register reference.
825 if (getLexer().isNot(AsmToken::Colon))
826 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
828 getParser().Lex(); // Eat the colon.
829 return ParseIntelMemOperand(RegNo, Start);
833 return ParseIntelMemOperand(0, Start);
836 X86Operand *X86AsmParser::ParseATTOperand() {
837 switch (getLexer().getKind()) {
839 // Parse a memory operand with no segment register.
840 return ParseMemOperand(0, Parser.getTok().getLoc());
841 case AsmToken::Percent: {
842 // Read the register.
845 if (ParseRegister(RegNo, Start, End)) return 0;
846 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
847 Error(Start, "%eiz and %riz can only be used as index registers",
848 SMRange(Start, End));
852 // If this is a segment register followed by a ':', then this is the start
853 // of a memory reference, otherwise this is a normal register reference.
854 if (getLexer().isNot(AsmToken::Colon))
855 return X86Operand::CreateReg(RegNo, Start, End);
858 getParser().Lex(); // Eat the colon.
859 return ParseMemOperand(RegNo, Start);
861 case AsmToken::Dollar: {
863 SMLoc Start = Parser.getTok().getLoc(), End;
866 if (getParser().ParseExpression(Val, End))
868 return X86Operand::CreateImm(Val, Start, End);
873 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
874 /// has already been parsed if present.
875 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
877 // We have to disambiguate a parenthesized expression "(4+5)" from the start
878 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
879 // only way to do this without lookahead is to eat the '(' and see what is
881 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
882 if (getLexer().isNot(AsmToken::LParen)) {
884 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
886 // After parsing the base expression we could either have a parenthesized
887 // memory address or not. If not, return now. If so, eat the (.
888 if (getLexer().isNot(AsmToken::LParen)) {
889 // Unless we have a segment register, treat this as an immediate.
891 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
892 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
898 // Okay, we have a '('. We don't know if this is an expression or not, but
899 // so we have to eat the ( to see beyond it.
900 SMLoc LParenLoc = Parser.getTok().getLoc();
901 Parser.Lex(); // Eat the '('.
903 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
904 // Nothing to do here, fall into the code below with the '(' part of the
905 // memory operand consumed.
909 // It must be an parenthesized expression, parse it now.
910 if (getParser().ParseParenExpression(Disp, ExprEnd))
913 // After parsing the base expression we could either have a parenthesized
914 // memory address or not. If not, return now. If so, eat the (.
915 if (getLexer().isNot(AsmToken::LParen)) {
916 // Unless we have a segment register, treat this as an immediate.
918 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
919 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
927 // If we reached here, then we just ate the ( of the memory operand. Process
928 // the rest of the memory operand.
929 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
932 if (getLexer().is(AsmToken::Percent)) {
933 SMLoc StartLoc, EndLoc;
934 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
935 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
936 Error(StartLoc, "eiz and riz can only be used as index registers",
937 SMRange(StartLoc, EndLoc));
942 if (getLexer().is(AsmToken::Comma)) {
943 Parser.Lex(); // Eat the comma.
944 IndexLoc = Parser.getTok().getLoc();
946 // Following the comma we should have either an index register, or a scale
947 // value. We don't support the later form, but we want to parse it
950 // Not that even though it would be completely consistent to support syntax
951 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
952 if (getLexer().is(AsmToken::Percent)) {
954 if (ParseRegister(IndexReg, L, L)) return 0;
956 if (getLexer().isNot(AsmToken::RParen)) {
957 // Parse the scale amount:
958 // ::= ',' [scale-expression]
959 if (getLexer().isNot(AsmToken::Comma)) {
960 Error(Parser.getTok().getLoc(),
961 "expected comma in scale expression");
964 Parser.Lex(); // Eat the comma.
966 if (getLexer().isNot(AsmToken::RParen)) {
967 SMLoc Loc = Parser.getTok().getLoc();
970 if (getParser().ParseAbsoluteExpression(ScaleVal)){
971 Error(Loc, "expected scale expression");
975 // Validate the scale amount.
976 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
977 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
980 Scale = (unsigned)ScaleVal;
983 } else if (getLexer().isNot(AsmToken::RParen)) {
984 // A scale amount without an index is ignored.
986 SMLoc Loc = Parser.getTok().getLoc();
989 if (getParser().ParseAbsoluteExpression(Value))
993 Warning(Loc, "scale factor without index register is ignored");
998 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
999 if (getLexer().isNot(AsmToken::RParen)) {
1000 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1003 SMLoc MemEnd = Parser.getTok().getLoc();
1004 Parser.Lex(); // Eat the ')'.
1006 // If we have both a base register and an index register make sure they are
1007 // both 64-bit or 32-bit registers.
1008 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1009 if (BaseReg != 0 && IndexReg != 0) {
1010 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1011 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1012 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1013 IndexReg != X86::RIZ) {
1014 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1017 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1018 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1019 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1020 IndexReg != X86::EIZ){
1021 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1026 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1031 ParseInstruction(StringRef Name, SMLoc NameLoc,
1032 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1033 StringRef PatchedName = Name;
1035 // FIXME: Hack to recognize setneb as setne.
1036 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1037 PatchedName != "setb" && PatchedName != "setnb")
1038 PatchedName = PatchedName.substr(0, Name.size()-1);
1040 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1041 const MCExpr *ExtraImmOp = 0;
1042 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1043 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1044 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1045 bool IsVCMP = PatchedName[0] == 'v';
1046 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1047 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1048 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1052 .Case("unord", 0x03)
1057 /* AVX only from here */
1058 .Case("eq_uq", 0x08)
1061 .Case("false", 0x0B)
1062 .Case("neq_oq", 0x0C)
1066 .Case("eq_os", 0x10)
1067 .Case("lt_oq", 0x11)
1068 .Case("le_oq", 0x12)
1069 .Case("unord_s", 0x13)
1070 .Case("neq_us", 0x14)
1071 .Case("nlt_uq", 0x15)
1072 .Case("nle_uq", 0x16)
1073 .Case("ord_s", 0x17)
1074 .Case("eq_us", 0x18)
1075 .Case("nge_uq", 0x19)
1076 .Case("ngt_uq", 0x1A)
1077 .Case("false_os", 0x1B)
1078 .Case("neq_os", 0x1C)
1079 .Case("ge_oq", 0x1D)
1080 .Case("gt_oq", 0x1E)
1081 .Case("true_us", 0x1F)
1083 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1084 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1085 getParser().getContext());
1086 if (PatchedName.endswith("ss")) {
1087 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1088 } else if (PatchedName.endswith("sd")) {
1089 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1090 } else if (PatchedName.endswith("ps")) {
1091 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1093 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1094 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1099 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1101 if (ExtraImmOp && !isParsingIntelSyntax())
1102 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1104 // Determine whether this is an instruction prefix.
1106 Name == "lock" || Name == "rep" ||
1107 Name == "repe" || Name == "repz" ||
1108 Name == "repne" || Name == "repnz" ||
1109 Name == "rex64" || Name == "data16";
1112 // This does the actual operand parsing. Don't parse any more if we have a
1113 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1114 // just want to parse the "lock" as the first instruction and the "incl" as
1116 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1118 // Parse '*' modifier.
1119 if (getLexer().is(AsmToken::Star)) {
1120 SMLoc Loc = Parser.getTok().getLoc();
1121 Operands.push_back(X86Operand::CreateToken("*", Loc));
1122 Parser.Lex(); // Eat the star.
1125 // Read the first operand.
1126 if (X86Operand *Op = ParseOperand())
1127 Operands.push_back(Op);
1129 Parser.EatToEndOfStatement();
1133 while (getLexer().is(AsmToken::Comma)) {
1134 Parser.Lex(); // Eat the comma.
1136 // Parse and remember the operand.
1137 if (X86Operand *Op = ParseOperand())
1138 Operands.push_back(Op);
1140 Parser.EatToEndOfStatement();
1145 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1146 SMLoc Loc = getLexer().getLoc();
1147 Parser.EatToEndOfStatement();
1148 return Error(Loc, "unexpected token in argument list");
1152 if (getLexer().is(AsmToken::EndOfStatement))
1153 Parser.Lex(); // Consume the EndOfStatement
1154 else if (isPrefix && getLexer().is(AsmToken::Slash))
1155 Parser.Lex(); // Consume the prefix separator Slash
1157 if (ExtraImmOp && isParsingIntelSyntax())
1158 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1160 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1161 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1162 // documented form in various unofficial manuals, so a lot of code uses it.
1163 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1164 Operands.size() == 3) {
1165 X86Operand &Op = *(X86Operand*)Operands.back();
1166 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1167 isa<MCConstantExpr>(Op.Mem.Disp) &&
1168 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1169 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1170 SMLoc Loc = Op.getEndLoc();
1171 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1175 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1176 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1177 Operands.size() == 3) {
1178 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1179 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1180 isa<MCConstantExpr>(Op.Mem.Disp) &&
1181 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1182 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1183 SMLoc Loc = Op.getEndLoc();
1184 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1188 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1189 if (Name.startswith("ins") && Operands.size() == 3 &&
1190 (Name == "insb" || Name == "insw" || Name == "insl")) {
1191 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1192 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1193 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1194 Operands.pop_back();
1195 Operands.pop_back();
1201 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1202 if (Name.startswith("outs") && Operands.size() == 3 &&
1203 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1204 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1205 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1206 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1207 Operands.pop_back();
1208 Operands.pop_back();
1214 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1215 if (Name.startswith("movs") && Operands.size() == 3 &&
1216 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1217 (is64BitMode() && Name == "movsq"))) {
1218 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1219 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1220 if (isSrcOp(Op) && isDstOp(Op2)) {
1221 Operands.pop_back();
1222 Operands.pop_back();
1227 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1228 if (Name.startswith("lods") && Operands.size() == 3 &&
1229 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1230 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1231 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1232 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1233 if (isSrcOp(*Op1) && Op2->isReg()) {
1235 unsigned reg = Op2->getReg();
1236 bool isLods = Name == "lods";
1237 if (reg == X86::AL && (isLods || Name == "lodsb"))
1239 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1241 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1243 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1248 Operands.pop_back();
1249 Operands.pop_back();
1253 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1257 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1258 if (Name.startswith("stos") && Operands.size() == 3 &&
1259 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1260 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1261 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1262 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1263 if (isDstOp(*Op2) && Op1->isReg()) {
1265 unsigned reg = Op1->getReg();
1266 bool isStos = Name == "stos";
1267 if (reg == X86::AL && (isStos || Name == "stosb"))
1269 else if (reg == X86::AX && (isStos || Name == "stosw"))
1271 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1273 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1278 Operands.pop_back();
1279 Operands.pop_back();
1283 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1288 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1290 if ((Name.startswith("shr") || Name.startswith("sar") ||
1291 Name.startswith("shl") || Name.startswith("sal") ||
1292 Name.startswith("rcl") || Name.startswith("rcr") ||
1293 Name.startswith("rol") || Name.startswith("ror")) &&
1294 Operands.size() == 3) {
1295 if (isParsingIntelSyntax()) {
1297 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1298 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1299 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1301 Operands.pop_back();
1304 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1305 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1306 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1308 Operands.erase(Operands.begin() + 1);
1313 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1314 // instalias with an immediate operand yet.
1315 if (Name == "int" && Operands.size() == 2) {
1316 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1317 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1318 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1320 Operands.erase(Operands.begin() + 1);
1321 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1329 processInstruction(MCInst &Inst,
1330 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1331 switch (Inst.getOpcode()) {
1332 default: return false;
1333 case X86::AND16i16: {
1334 if (!Inst.getOperand(0).isImm() ||
1335 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1339 TmpInst.setOpcode(X86::AND16ri8);
1340 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1341 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1342 TmpInst.addOperand(Inst.getOperand(0));
1346 case X86::AND32i32: {
1347 if (!Inst.getOperand(0).isImm() ||
1348 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1352 TmpInst.setOpcode(X86::AND32ri8);
1353 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1354 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1355 TmpInst.addOperand(Inst.getOperand(0));
1359 case X86::AND64i32: {
1360 if (!Inst.getOperand(0).isImm() ||
1361 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1365 TmpInst.setOpcode(X86::AND64ri8);
1366 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1367 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1368 TmpInst.addOperand(Inst.getOperand(0));
1372 case X86::XOR16i16: {
1373 if (!Inst.getOperand(0).isImm() ||
1374 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1378 TmpInst.setOpcode(X86::XOR16ri8);
1379 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1380 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1381 TmpInst.addOperand(Inst.getOperand(0));
1385 case X86::XOR32i32: {
1386 if (!Inst.getOperand(0).isImm() ||
1387 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1391 TmpInst.setOpcode(X86::XOR32ri8);
1392 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1393 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1394 TmpInst.addOperand(Inst.getOperand(0));
1398 case X86::XOR64i32: {
1399 if (!Inst.getOperand(0).isImm() ||
1400 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1404 TmpInst.setOpcode(X86::XOR64ri8);
1405 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1406 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1407 TmpInst.addOperand(Inst.getOperand(0));
1411 case X86::OR16i16: {
1412 if (!Inst.getOperand(0).isImm() ||
1413 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1417 TmpInst.setOpcode(X86::OR16ri8);
1418 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1419 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1420 TmpInst.addOperand(Inst.getOperand(0));
1424 case X86::OR32i32: {
1425 if (!Inst.getOperand(0).isImm() ||
1426 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1430 TmpInst.setOpcode(X86::OR32ri8);
1431 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1432 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1433 TmpInst.addOperand(Inst.getOperand(0));
1437 case X86::OR64i32: {
1438 if (!Inst.getOperand(0).isImm() ||
1439 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1443 TmpInst.setOpcode(X86::OR64ri8);
1444 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1445 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1446 TmpInst.addOperand(Inst.getOperand(0));
1450 case X86::CMP16i16: {
1451 if (!Inst.getOperand(0).isImm() ||
1452 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1456 TmpInst.setOpcode(X86::CMP16ri8);
1457 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1458 TmpInst.addOperand(Inst.getOperand(0));
1462 case X86::CMP32i32: {
1463 if (!Inst.getOperand(0).isImm() ||
1464 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1468 TmpInst.setOpcode(X86::CMP32ri8);
1469 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1470 TmpInst.addOperand(Inst.getOperand(0));
1474 case X86::CMP64i32: {
1475 if (!Inst.getOperand(0).isImm() ||
1476 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1480 TmpInst.setOpcode(X86::CMP64ri8);
1481 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1482 TmpInst.addOperand(Inst.getOperand(0));
1486 case X86::ADD16i16: {
1487 if (!Inst.getOperand(0).isImm() ||
1488 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1492 TmpInst.setOpcode(X86::ADD16ri8);
1493 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1494 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1495 TmpInst.addOperand(Inst.getOperand(0));
1499 case X86::ADD32i32: {
1500 if (!Inst.getOperand(0).isImm() ||
1501 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1505 TmpInst.setOpcode(X86::ADD32ri8);
1506 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1507 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1508 TmpInst.addOperand(Inst.getOperand(0));
1512 case X86::ADD64i32: {
1513 if (!Inst.getOperand(0).isImm() ||
1514 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1518 TmpInst.setOpcode(X86::ADD64ri8);
1519 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1520 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1521 TmpInst.addOperand(Inst.getOperand(0));
1525 case X86::SUB16i16: {
1526 if (!Inst.getOperand(0).isImm() ||
1527 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1531 TmpInst.setOpcode(X86::SUB16ri8);
1532 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1533 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1534 TmpInst.addOperand(Inst.getOperand(0));
1538 case X86::SUB32i32: {
1539 if (!Inst.getOperand(0).isImm() ||
1540 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1544 TmpInst.setOpcode(X86::SUB32ri8);
1545 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1546 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1547 TmpInst.addOperand(Inst.getOperand(0));
1551 case X86::SUB64i32: {
1552 if (!Inst.getOperand(0).isImm() ||
1553 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1557 TmpInst.setOpcode(X86::SUB64ri8);
1558 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1559 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1560 TmpInst.addOperand(Inst.getOperand(0));
1568 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1569 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1570 MCStreamer &Out, unsigned &ErrorInfo,
1571 bool MatchingInlineAsm) {
1572 assert(!Operands.empty() && "Unexpect empty operand list!");
1573 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1574 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1575 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1577 // First, handle aliases that expand to multiple instructions.
1578 // FIXME: This should be replaced with a real .td file alias mechanism.
1579 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1581 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1582 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1583 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1584 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1586 Inst.setOpcode(X86::WAIT);
1588 if (!MatchingInlineAsm)
1589 Out.EmitInstruction(Inst);
1592 StringSwitch<const char*>(Op->getToken())
1593 .Case("finit", "fninit")
1594 .Case("fsave", "fnsave")
1595 .Case("fstcw", "fnstcw")
1596 .Case("fstcww", "fnstcw")
1597 .Case("fstenv", "fnstenv")
1598 .Case("fstsw", "fnstsw")
1599 .Case("fstsww", "fnstsw")
1600 .Case("fclex", "fnclex")
1602 assert(Repl && "Unknown wait-prefixed instruction");
1604 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1607 bool WasOriginallyInvalidOperand = false;
1610 // First, try a direct match.
1611 switch (MatchInstructionImpl(Operands, Inst,
1612 ErrorInfo, MatchingInlineAsm,
1613 isParsingIntelSyntax())) {
1616 // Some instructions need post-processing to, for example, tweak which
1617 // encoding is selected. Loop on it while changes happen so the
1618 // individual transformations can chain off each other.
1619 if (!MatchingInlineAsm)
1620 while (processInstruction(Inst, Operands))
1624 if (!MatchingInlineAsm)
1625 Out.EmitInstruction(Inst);
1626 Opcode = Inst.getOpcode();
1628 case Match_MissingFeature:
1629 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1630 EmptyRanges, MatchingInlineAsm);
1632 case Match_InvalidOperand:
1633 WasOriginallyInvalidOperand = true;
1635 case Match_MnemonicFail:
1639 // FIXME: Ideally, we would only attempt suffix matches for things which are
1640 // valid prefixes, and we could just infer the right unambiguous
1641 // type. However, that requires substantially more matcher support than the
1644 // Change the operand to point to a temporary token.
1645 StringRef Base = Op->getToken();
1646 SmallString<16> Tmp;
1649 Op->setTokenValue(Tmp.str());
1651 // If this instruction starts with an 'f', then it is a floating point stack
1652 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1653 // 80-bit floating point, which use the suffixes s,l,t respectively.
1655 // Otherwise, we assume that this may be an integer instruction, which comes
1656 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1657 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1659 // Check for the various suffix matches.
1660 Tmp[Base.size()] = Suffixes[0];
1661 unsigned ErrorInfoIgnore;
1662 unsigned Match1, Match2, Match3, Match4;
1664 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1665 isParsingIntelSyntax());
1666 Tmp[Base.size()] = Suffixes[1];
1667 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1668 isParsingIntelSyntax());
1669 Tmp[Base.size()] = Suffixes[2];
1670 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1671 isParsingIntelSyntax());
1672 Tmp[Base.size()] = Suffixes[3];
1673 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1674 isParsingIntelSyntax());
1676 // Restore the old token.
1677 Op->setTokenValue(Base);
1679 // If exactly one matched, then we treat that as a successful match (and the
1680 // instruction will already have been filled in correctly, since the failing
1681 // matches won't have modified it).
1682 unsigned NumSuccessfulMatches =
1683 (Match1 == Match_Success) + (Match2 == Match_Success) +
1684 (Match3 == Match_Success) + (Match4 == Match_Success);
1685 if (NumSuccessfulMatches == 1) {
1687 if (!MatchingInlineAsm)
1688 Out.EmitInstruction(Inst);
1689 Opcode = Inst.getOpcode();
1693 // Otherwise, the match failed, try to produce a decent error message.
1695 // If we had multiple suffix matches, then identify this as an ambiguous
1697 if (NumSuccessfulMatches > 1) {
1699 unsigned NumMatches = 0;
1700 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1701 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1702 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1703 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1705 SmallString<126> Msg;
1706 raw_svector_ostream OS(Msg);
1707 OS << "ambiguous instructions require an explicit suffix (could be ";
1708 for (unsigned i = 0; i != NumMatches; ++i) {
1711 if (i + 1 == NumMatches)
1713 OS << "'" << Base << MatchChars[i] << "'";
1716 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1720 // Okay, we know that none of the variants matched successfully.
1722 // If all of the instructions reported an invalid mnemonic, then the original
1723 // mnemonic was invalid.
1724 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1725 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1726 if (!WasOriginallyInvalidOperand) {
1727 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1729 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1730 Ranges, MatchingInlineAsm);
1733 // Recover location info for the operand if we know which was the problem.
1734 if (ErrorInfo != ~0U) {
1735 if (ErrorInfo >= Operands.size())
1736 return Error(IDLoc, "too few operands for instruction",
1737 EmptyRanges, MatchingInlineAsm);
1739 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
1740 if (Operand->getStartLoc().isValid()) {
1741 SMRange OperandRange = Operand->getLocRange();
1742 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1743 OperandRange, MatchingInlineAsm);
1747 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1751 // If one instruction matched with a missing feature, report this as a
1753 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1754 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1755 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1756 EmptyRanges, MatchingInlineAsm);
1760 // If one instruction matched with an invalid operand, report this as an
1762 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1763 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1764 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1769 // If all of these were an outright failure, report it in a useless way.
1770 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1771 EmptyRanges, MatchingInlineAsm);
1776 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1777 StringRef IDVal = DirectiveID.getIdentifier();
1778 if (IDVal == ".word")
1779 return ParseDirectiveWord(2, DirectiveID.getLoc());
1780 else if (IDVal.startswith(".code"))
1781 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1782 else if (IDVal.startswith(".att_syntax")) {
1783 getParser().setAssemblerDialect(0);
1785 } else if (IDVal.startswith(".intel_syntax")) {
1786 getParser().setAssemblerDialect(1);
1787 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1788 if(Parser.getTok().getString() == "noprefix") {
1789 // FIXME : Handle noprefix
1799 /// ParseDirectiveWord
1800 /// ::= .word [ expression (, expression)* ]
1801 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1802 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1804 const MCExpr *Value;
1805 if (getParser().ParseExpression(Value))
1808 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1810 if (getLexer().is(AsmToken::EndOfStatement))
1813 // FIXME: Improve diagnostic.
1814 if (getLexer().isNot(AsmToken::Comma))
1815 return Error(L, "unexpected token in directive");
1824 /// ParseDirectiveCode
1825 /// ::= .code32 | .code64
1826 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1827 if (IDVal == ".code32") {
1829 if (is64BitMode()) {
1831 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1833 } else if (IDVal == ".code64") {
1835 if (!is64BitMode()) {
1837 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1840 return Error(L, "unexpected directive " + IDVal);
1847 extern "C" void LLVMInitializeX86AsmLexer();
1849 // Force static initialization.
1850 extern "C" void LLVMInitializeX86AsmParser() {
1851 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1852 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1853 LLVMInitializeX86AsmLexer();
1856 #define GET_REGISTER_MATCHER
1857 #define GET_MATCHER_IMPLEMENTATION
1858 #include "X86GenAsmMatcher.inc"