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 *ParseIntelOffsetOfOperator(SMLoc StartLoc);
58 X86Operand *ParseIntelMemOperand(unsigned SegReg, SMLoc StartLoc);
59 X86Operand *ParseIntelBracExpression(unsigned SegReg, unsigned Size);
60 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
62 bool ParseDirectiveWord(unsigned Size, SMLoc L);
63 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
65 bool processInstruction(MCInst &Inst,
66 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
68 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
69 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
70 MCStreamer &Out, unsigned &ErrorInfo,
71 bool MatchingInlineAsm);
73 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
74 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
75 bool isSrcOp(X86Operand &Op);
77 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
78 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
79 bool isDstOp(X86Operand &Op);
81 bool is64BitMode() const {
82 // FIXME: Can tablegen auto-generate this?
83 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
86 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
87 setAvailableFeatures(FB);
90 /// @name Auto-generated Matcher Functions
93 #define GET_ASSEMBLER_HEADER
94 #include "X86GenAsmMatcher.inc"
99 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
100 : MCTargetAsmParser(), STI(sti), Parser(parser) {
102 // Initialize the set of available features.
103 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
105 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
107 virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
108 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
110 virtual bool ParseDirective(AsmToken DirectiveID);
112 bool isParsingIntelSyntax() {
113 return getParser().getAssemblerDialect();
116 } // end anonymous namespace
118 /// @name Auto-generated Match Functions
121 static unsigned MatchRegisterName(StringRef Name);
125 static bool isImmSExti16i8Value(uint64_t Value) {
126 return (( Value <= 0x000000000000007FULL)||
127 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
128 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
131 static bool isImmSExti32i8Value(uint64_t Value) {
132 return (( Value <= 0x000000000000007FULL)||
133 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
134 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
137 static bool isImmZExtu32u8Value(uint64_t Value) {
138 return (Value <= 0x00000000000000FFULL);
141 static bool isImmSExti64i8Value(uint64_t Value) {
142 return (( Value <= 0x000000000000007FULL)||
143 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
146 static bool isImmSExti64i32Value(uint64_t Value) {
147 return (( Value <= 0x000000007FFFFFFFULL)||
148 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
152 /// X86Operand - Instances of this class represent a parsed X86 machine
154 struct X86Operand : public MCParsedAsmOperand {
162 SMLoc StartLoc, EndLoc;
190 X86Operand(KindTy K, SMLoc Start, SMLoc End)
191 : Kind(K), StartLoc(Start), EndLoc(End) {}
193 /// getStartLoc - Get the location of the first token of this operand.
194 SMLoc getStartLoc() const { return StartLoc; }
195 /// getEndLoc - Get the location of the last token of this operand.
196 SMLoc getEndLoc() const { return EndLoc; }
197 /// getLocRange - Get the range between the first and last token of this
199 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
200 /// getOffsetOfLoc - Get the location of the offset operator.
201 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
203 virtual void print(raw_ostream &OS) const {}
205 StringRef getToken() const {
206 assert(Kind == Token && "Invalid access!");
207 return StringRef(Tok.Data, Tok.Length);
209 void setTokenValue(StringRef Value) {
210 assert(Kind == Token && "Invalid access!");
211 Tok.Data = Value.data();
212 Tok.Length = Value.size();
215 unsigned getReg() const {
216 assert(Kind == Register && "Invalid access!");
220 const MCExpr *getImm() const {
221 assert(Kind == Immediate && "Invalid access!");
225 const MCExpr *getMemDisp() const {
226 assert(Kind == Memory && "Invalid access!");
229 unsigned getMemSegReg() const {
230 assert(Kind == Memory && "Invalid access!");
233 unsigned getMemBaseReg() const {
234 assert(Kind == Memory && "Invalid access!");
237 unsigned getMemIndexReg() const {
238 assert(Kind == Memory && "Invalid access!");
241 unsigned getMemScale() const {
242 assert(Kind == Memory && "Invalid access!");
246 bool isToken() const {return Kind == Token; }
248 bool isImm() const { return Kind == Immediate; }
250 bool isImmSExti16i8() const {
254 // If this isn't a constant expr, just assume it fits and let relaxation
256 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
260 // Otherwise, check the value is in a range that makes sense for this
262 return isImmSExti16i8Value(CE->getValue());
264 bool isImmSExti32i8() const {
268 // If this isn't a constant expr, just assume it fits and let relaxation
270 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
274 // Otherwise, check the value is in a range that makes sense for this
276 return isImmSExti32i8Value(CE->getValue());
278 bool isImmZExtu32u8() const {
282 // If this isn't a constant expr, just assume it fits and let relaxation
284 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
288 // Otherwise, check the value is in a range that makes sense for this
290 return isImmZExtu32u8Value(CE->getValue());
292 bool isImmSExti64i8() const {
296 // If this isn't a constant expr, just assume it fits and let relaxation
298 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
302 // Otherwise, check the value is in a range that makes sense for this
304 return isImmSExti64i8Value(CE->getValue());
306 bool isImmSExti64i32() const {
310 // If this isn't a constant expr, just assume it fits and let relaxation
312 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
316 // Otherwise, check the value is in a range that makes sense for this
318 return isImmSExti64i32Value(CE->getValue());
321 unsigned getMemSize() const {
322 assert(Kind == Memory && "Invalid access!");
326 bool isOffsetOf() const {
327 return OffsetOfLoc.getPointer();
330 bool needSizeDirective() const {
331 assert(Kind == Memory && "Invalid access!");
332 return Mem.NeedSizeDir;
335 bool isMem() const { return Kind == Memory; }
336 bool isMem8() const {
337 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
339 bool isMem16() const {
340 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
342 bool isMem32() const {
343 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
345 bool isMem64() const {
346 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
348 bool isMem80() const {
349 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
351 bool isMem128() const {
352 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
354 bool isMem256() const {
355 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
358 bool isMemVX32() const {
359 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
360 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
362 bool isMemVY32() const {
363 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
364 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
366 bool isMemVX64() const {
367 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
368 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
370 bool isMemVY64() const {
371 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
372 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
375 bool isAbsMem() const {
376 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
377 !getMemIndexReg() && getMemScale() == 1;
380 bool isReg() const { return Kind == Register; }
382 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
383 // Add as immediates when possible.
384 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
385 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
387 Inst.addOperand(MCOperand::CreateExpr(Expr));
390 void addRegOperands(MCInst &Inst, unsigned N) const {
391 assert(N == 1 && "Invalid number of operands!");
392 Inst.addOperand(MCOperand::CreateReg(getReg()));
395 void addImmOperands(MCInst &Inst, unsigned N) const {
396 assert(N == 1 && "Invalid number of operands!");
397 addExpr(Inst, getImm());
400 void addMem8Operands(MCInst &Inst, unsigned N) const {
401 addMemOperands(Inst, N);
403 void addMem16Operands(MCInst &Inst, unsigned N) const {
404 addMemOperands(Inst, N);
406 void addMem32Operands(MCInst &Inst, unsigned N) const {
407 addMemOperands(Inst, N);
409 void addMem64Operands(MCInst &Inst, unsigned N) const {
410 addMemOperands(Inst, N);
412 void addMem80Operands(MCInst &Inst, unsigned N) const {
413 addMemOperands(Inst, N);
415 void addMem128Operands(MCInst &Inst, unsigned N) const {
416 addMemOperands(Inst, N);
418 void addMem256Operands(MCInst &Inst, unsigned N) const {
419 addMemOperands(Inst, N);
421 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
422 addMemOperands(Inst, N);
424 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
425 addMemOperands(Inst, N);
427 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
428 addMemOperands(Inst, N);
430 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
431 addMemOperands(Inst, N);
434 void addMemOperands(MCInst &Inst, unsigned N) const {
435 assert((N == 5) && "Invalid number of operands!");
436 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
437 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
438 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
439 addExpr(Inst, getMemDisp());
440 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
443 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
444 assert((N == 1) && "Invalid number of operands!");
445 // Add as immediates when possible.
446 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
447 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
449 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
452 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
453 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size() - 1);
454 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
455 Res->Tok.Data = Str.data();
456 Res->Tok.Length = Str.size();
460 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
461 SMLoc OffsetOfLoc = SMLoc()) {
462 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
463 Res->Reg.RegNo = RegNo;
464 Res->OffsetOfLoc = OffsetOfLoc;
468 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
469 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
474 /// Create an absolute memory operand.
475 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
476 SMLoc EndLoc, unsigned Size = 0,
477 bool NeedSizeDir = false){
478 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
480 Res->Mem.Disp = Disp;
481 Res->Mem.BaseReg = 0;
482 Res->Mem.IndexReg = 0;
484 Res->Mem.Size = Size;
485 Res->Mem.NeedSizeDir = NeedSizeDir;
489 /// Create a generalized memory operand.
490 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
491 unsigned BaseReg, unsigned IndexReg,
492 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
493 unsigned Size = 0, bool NeedSizeDir = false) {
494 // We should never just have a displacement, that should be parsed as an
495 // absolute memory operand.
496 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
498 // The scale should always be one of {1,2,4,8}.
499 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
501 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
502 Res->Mem.SegReg = SegReg;
503 Res->Mem.Disp = Disp;
504 Res->Mem.BaseReg = BaseReg;
505 Res->Mem.IndexReg = IndexReg;
506 Res->Mem.Scale = Scale;
507 Res->Mem.Size = Size;
508 Res->Mem.NeedSizeDir = NeedSizeDir;
513 } // end anonymous namespace.
515 bool X86AsmParser::isSrcOp(X86Operand &Op) {
516 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
518 return (Op.isMem() &&
519 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
520 isa<MCConstantExpr>(Op.Mem.Disp) &&
521 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
522 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
525 bool X86AsmParser::isDstOp(X86Operand &Op) {
526 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
529 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
530 isa<MCConstantExpr>(Op.Mem.Disp) &&
531 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
532 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
535 bool X86AsmParser::ParseRegister(unsigned &RegNo,
536 SMLoc &StartLoc, SMLoc &EndLoc) {
538 const AsmToken &PercentTok = Parser.getTok();
539 StartLoc = PercentTok.getLoc();
541 // If we encounter a %, ignore it. This code handles registers with and
542 // without the prefix, unprefixed registers can occur in cfi directives.
543 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
544 Parser.Lex(); // Eat percent token.
546 const AsmToken &Tok = Parser.getTok();
547 if (Tok.isNot(AsmToken::Identifier)) {
548 if (isParsingIntelSyntax()) return true;
549 return Error(StartLoc, "invalid register name",
550 SMRange(StartLoc, Tok.getEndLoc()));
553 RegNo = MatchRegisterName(Tok.getString());
555 // If the match failed, try the register name as lowercase.
557 RegNo = MatchRegisterName(Tok.getString().lower());
559 if (!is64BitMode()) {
560 // FIXME: This should be done using Requires<In32BitMode> and
561 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
563 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
565 if (RegNo == X86::RIZ ||
566 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
567 X86II::isX86_64NonExtLowByteReg(RegNo) ||
568 X86II::isX86_64ExtendedReg(RegNo))
569 return Error(StartLoc, "register %"
570 + Tok.getString() + " is only available in 64-bit mode",
571 SMRange(StartLoc, Tok.getEndLoc()));
574 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
575 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
577 EndLoc = Tok.getLoc();
578 Parser.Lex(); // Eat 'st'
580 // Check to see if we have '(4)' after %st.
581 if (getLexer().isNot(AsmToken::LParen))
586 const AsmToken &IntTok = Parser.getTok();
587 if (IntTok.isNot(AsmToken::Integer))
588 return Error(IntTok.getLoc(), "expected stack index");
589 switch (IntTok.getIntVal()) {
590 case 0: RegNo = X86::ST0; break;
591 case 1: RegNo = X86::ST1; break;
592 case 2: RegNo = X86::ST2; break;
593 case 3: RegNo = X86::ST3; break;
594 case 4: RegNo = X86::ST4; break;
595 case 5: RegNo = X86::ST5; break;
596 case 6: RegNo = X86::ST6; break;
597 case 7: RegNo = X86::ST7; break;
598 default: return Error(IntTok.getLoc(), "invalid stack index");
601 if (getParser().Lex().isNot(AsmToken::RParen))
602 return Error(Parser.getTok().getLoc(), "expected ')'");
604 EndLoc = Tok.getLoc();
605 Parser.Lex(); // Eat ')'
609 // If this is "db[0-7]", match it as an alias
611 if (RegNo == 0 && Tok.getString().size() == 3 &&
612 Tok.getString().startswith("db")) {
613 switch (Tok.getString()[2]) {
614 case '0': RegNo = X86::DR0; break;
615 case '1': RegNo = X86::DR1; break;
616 case '2': RegNo = X86::DR2; break;
617 case '3': RegNo = X86::DR3; break;
618 case '4': RegNo = X86::DR4; break;
619 case '5': RegNo = X86::DR5; break;
620 case '6': RegNo = X86::DR6; break;
621 case '7': RegNo = X86::DR7; break;
625 EndLoc = Tok.getLoc();
626 Parser.Lex(); // Eat it.
632 if (isParsingIntelSyntax()) return true;
633 return Error(StartLoc, "invalid register name",
634 SMRange(StartLoc, Tok.getEndLoc()));
637 EndLoc = Tok.getEndLoc();
638 Parser.Lex(); // Eat identifier token.
642 X86Operand *X86AsmParser::ParseOperand() {
643 if (isParsingIntelSyntax())
644 return ParseIntelOperand();
645 return ParseATTOperand();
648 /// getIntelMemOperandSize - Return intel memory operand size.
649 static unsigned getIntelMemOperandSize(StringRef OpStr) {
650 unsigned Size = StringSwitch<unsigned>(OpStr)
651 .Cases("BYTE", "byte", 8)
652 .Cases("WORD", "word", 16)
653 .Cases("DWORD", "dword", 32)
654 .Cases("QWORD", "qword", 64)
655 .Cases("XWORD", "xword", 80)
656 .Cases("XMMWORD", "xmmword", 128)
657 .Cases("YMMWORD", "ymmword", 256)
662 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg,
664 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
665 SMLoc Start = Parser.getTok().getLoc(), End;
667 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
668 // Parse [ BaseReg + Scale*IndexReg + Disp ] or [ symbol ]
671 if (getLexer().isNot(AsmToken::LBrac))
672 return ErrorOperand(Start, "Expected '[' token!");
675 if (getLexer().is(AsmToken::Identifier)) {
677 if (ParseRegister(BaseReg, Start, End)) {
678 // Handle '[' 'symbol' ']'
679 if (getParser().ParseExpression(Disp, End)) return 0;
680 if (getLexer().isNot(AsmToken::RBrac))
681 return ErrorOperand(Start, "Expected ']' token!");
683 return X86Operand::CreateMem(Disp, Start, End, Size);
685 } else if (getLexer().is(AsmToken::Integer)) {
686 int64_t Val = Parser.getTok().getIntVal();
688 SMLoc Loc = Parser.getTok().getLoc();
689 if (getLexer().is(AsmToken::RBrac)) {
690 // Handle '[' number ']'
692 const MCExpr *Disp = MCConstantExpr::Create(Val, getContext());
694 return X86Operand::CreateMem(SegReg, Disp, 0, 0, Scale,
696 return X86Operand::CreateMem(Disp, Start, End, Size);
697 } else if (getLexer().is(AsmToken::Star)) {
698 // Handle '[' Scale*IndexReg ']'
700 SMLoc IdxRegLoc = Parser.getTok().getLoc();
701 if (ParseRegister(IndexReg, IdxRegLoc, End))
702 return ErrorOperand(IdxRegLoc, "Expected register");
705 return ErrorOperand(Loc, "Unexpected token");
708 if (getLexer().is(AsmToken::Plus) || getLexer().is(AsmToken::Minus)) {
709 bool isPlus = getLexer().is(AsmToken::Plus);
711 SMLoc PlusLoc = Parser.getTok().getLoc();
712 if (getLexer().is(AsmToken::Integer)) {
713 int64_t Val = Parser.getTok().getIntVal();
715 if (getLexer().is(AsmToken::Star)) {
717 SMLoc IdxRegLoc = Parser.getTok().getLoc();
718 if (ParseRegister(IndexReg, IdxRegLoc, End))
719 return ErrorOperand(IdxRegLoc, "Expected register");
721 } else if (getLexer().is(AsmToken::RBrac)) {
722 const MCExpr *ValExpr = MCConstantExpr::Create(Val, getContext());
723 Disp = isPlus ? ValExpr : MCConstantExpr::Create(0-Val, getContext());
725 return ErrorOperand(PlusLoc, "unexpected token after +");
726 } else if (getLexer().is(AsmToken::Identifier)) {
727 // This could be an index register or a displacement expression.
728 End = Parser.getTok().getLoc();
730 ParseRegister(IndexReg, Start, End);
731 else if (getParser().ParseExpression(Disp, End)) return 0;
735 if (getLexer().isNot(AsmToken::RBrac))
736 if (getParser().ParseExpression(Disp, End)) return 0;
738 End = Parser.getTok().getLoc();
739 if (getLexer().isNot(AsmToken::RBrac))
740 return ErrorOperand(End, "expected ']' token!");
742 End = Parser.getTok().getLoc();
745 if (!BaseReg && !IndexReg)
746 return X86Operand::CreateMem(Disp, Start, End, Size);
748 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
752 /// ParseIntelMemOperand - Parse intel style memory operand.
753 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg, SMLoc Start) {
754 const AsmToken &Tok = Parser.getTok();
757 unsigned Size = getIntelMemOperandSize(Tok.getString());
760 assert ((Tok.getString() == "PTR" || Tok.getString() == "ptr") &&
761 "Unexpected token!");
765 if (getLexer().is(AsmToken::LBrac))
766 return ParseIntelBracExpression(SegReg, Size);
768 if (!ParseRegister(SegReg, Start, End)) {
769 // Handel SegReg : [ ... ]
770 if (getLexer().isNot(AsmToken::Colon))
771 return ErrorOperand(Start, "Expected ':' token!");
772 Parser.Lex(); // Eat :
773 if (getLexer().isNot(AsmToken::LBrac))
774 return ErrorOperand(Start, "Expected '[' token!");
775 return ParseIntelBracExpression(SegReg, Size);
778 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
779 if (getParser().ParseExpression(Disp, End)) return 0;
780 End = Parser.getTok().getLoc();
782 bool NeedSizeDir = false;
783 if (!Size && isParsingInlineAsm()) {
784 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
785 const MCSymbol &Sym = SymRef->getSymbol();
786 // FIXME: The SemaLookup will fail if the name is anything other then an
788 // FIXME: Pass a valid SMLoc.
789 SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Size);
790 NeedSizeDir = Size > 0;
793 if (!isParsingInlineAsm())
794 return X86Operand::CreateMem(Disp, Start, End, Size);
796 // When parsing inline assembly we set the base register to a non-zero value
797 // as we don't know the actual value at this time. This is necessary to
798 // get the matching correct in some cases.
799 return X86Operand::CreateMem(/*SegReg*/0, Disp, /*BaseReg*/1, /*IndexReg*/0,
800 /*Scale*/1, Start, End, Size, NeedSizeDir);
803 /// Parse the 'offset' operator. This operator is used to specify the
804 /// location rather then the content of a variable.
805 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator(SMLoc Start) {
806 SMLoc OffsetOfLoc = Start;
807 Parser.Lex(); // Eat offset.
808 Start = Parser.getTok().getLoc();
809 assert (Parser.getTok().is(AsmToken::Identifier) && "Expected an identifier");
813 if (getParser().ParseExpression(Val, End))
816 End = Parser.getTok().getLoc();
818 // The offset operator will have an 'r' constraint, thus we need to create
819 // register operand to ensure proper matching. Just pick a GPR based on
820 // the size of a pointer.
821 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
822 return X86Operand::CreateReg(RegNo, Start, End, OffsetOfLoc);
825 X86Operand *X86AsmParser::ParseIntelOperand() {
826 SMLoc Start = Parser.getTok().getLoc(), End;
829 const AsmToken &Tok = Parser.getTok();
830 if ((Tok.getString() == "offset" || Tok.getString() == "OFFSET") &&
831 isParsingInlineAsm())
832 return ParseIntelOffsetOfOperator(Start);
835 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Real) ||
836 getLexer().is(AsmToken::Minus)) {
838 if (!getParser().ParseExpression(Val, End)) {
839 End = Parser.getTok().getLoc();
840 return X86Operand::CreateImm(Val, Start, End);
846 if (!ParseRegister(RegNo, Start, End)) {
847 // If this is a segment register followed by a ':', then this is the start
848 // of a memory reference, otherwise this is a normal register reference.
849 if (getLexer().isNot(AsmToken::Colon))
850 return X86Operand::CreateReg(RegNo, Start, Parser.getTok().getLoc());
852 getParser().Lex(); // Eat the colon.
853 return ParseIntelMemOperand(RegNo, Start);
857 return ParseIntelMemOperand(0, Start);
860 X86Operand *X86AsmParser::ParseATTOperand() {
861 switch (getLexer().getKind()) {
863 // Parse a memory operand with no segment register.
864 return ParseMemOperand(0, Parser.getTok().getLoc());
865 case AsmToken::Percent: {
866 // Read the register.
869 if (ParseRegister(RegNo, Start, End)) return 0;
870 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
871 Error(Start, "%eiz and %riz can only be used as index registers",
872 SMRange(Start, End));
876 // If this is a segment register followed by a ':', then this is the start
877 // of a memory reference, otherwise this is a normal register reference.
878 if (getLexer().isNot(AsmToken::Colon))
879 return X86Operand::CreateReg(RegNo, Start, End);
882 getParser().Lex(); // Eat the colon.
883 return ParseMemOperand(RegNo, Start);
885 case AsmToken::Dollar: {
887 SMLoc Start = Parser.getTok().getLoc(), End;
890 if (getParser().ParseExpression(Val, End))
892 return X86Operand::CreateImm(Val, Start, End);
897 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
898 /// has already been parsed if present.
899 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
901 // We have to disambiguate a parenthesized expression "(4+5)" from the start
902 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
903 // only way to do this without lookahead is to eat the '(' and see what is
905 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
906 if (getLexer().isNot(AsmToken::LParen)) {
908 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
910 // After parsing the base expression we could either have a parenthesized
911 // memory address or not. If not, return now. If so, eat the (.
912 if (getLexer().isNot(AsmToken::LParen)) {
913 // Unless we have a segment register, treat this as an immediate.
915 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
916 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
922 // Okay, we have a '('. We don't know if this is an expression or not, but
923 // so we have to eat the ( to see beyond it.
924 SMLoc LParenLoc = Parser.getTok().getLoc();
925 Parser.Lex(); // Eat the '('.
927 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
928 // Nothing to do here, fall into the code below with the '(' part of the
929 // memory operand consumed.
933 // It must be an parenthesized expression, parse it now.
934 if (getParser().ParseParenExpression(Disp, ExprEnd))
937 // After parsing the base expression we could either have a parenthesized
938 // memory address or not. If not, return now. If so, eat the (.
939 if (getLexer().isNot(AsmToken::LParen)) {
940 // Unless we have a segment register, treat this as an immediate.
942 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
943 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
951 // If we reached here, then we just ate the ( of the memory operand. Process
952 // the rest of the memory operand.
953 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
956 if (getLexer().is(AsmToken::Percent)) {
957 SMLoc StartLoc, EndLoc;
958 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
959 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
960 Error(StartLoc, "eiz and riz can only be used as index registers",
961 SMRange(StartLoc, EndLoc));
966 if (getLexer().is(AsmToken::Comma)) {
967 Parser.Lex(); // Eat the comma.
968 IndexLoc = Parser.getTok().getLoc();
970 // Following the comma we should have either an index register, or a scale
971 // value. We don't support the later form, but we want to parse it
974 // Not that even though it would be completely consistent to support syntax
975 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
976 if (getLexer().is(AsmToken::Percent)) {
978 if (ParseRegister(IndexReg, L, L)) return 0;
980 if (getLexer().isNot(AsmToken::RParen)) {
981 // Parse the scale amount:
982 // ::= ',' [scale-expression]
983 if (getLexer().isNot(AsmToken::Comma)) {
984 Error(Parser.getTok().getLoc(),
985 "expected comma in scale expression");
988 Parser.Lex(); // Eat the comma.
990 if (getLexer().isNot(AsmToken::RParen)) {
991 SMLoc Loc = Parser.getTok().getLoc();
994 if (getParser().ParseAbsoluteExpression(ScaleVal)){
995 Error(Loc, "expected scale expression");
999 // Validate the scale amount.
1000 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1001 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1004 Scale = (unsigned)ScaleVal;
1007 } else if (getLexer().isNot(AsmToken::RParen)) {
1008 // A scale amount without an index is ignored.
1010 SMLoc Loc = Parser.getTok().getLoc();
1013 if (getParser().ParseAbsoluteExpression(Value))
1017 Warning(Loc, "scale factor without index register is ignored");
1022 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1023 if (getLexer().isNot(AsmToken::RParen)) {
1024 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1027 SMLoc MemEnd = Parser.getTok().getLoc();
1028 Parser.Lex(); // Eat the ')'.
1030 // If we have both a base register and an index register make sure they are
1031 // both 64-bit or 32-bit registers.
1032 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1033 if (BaseReg != 0 && IndexReg != 0) {
1034 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1035 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1036 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1037 IndexReg != X86::RIZ) {
1038 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1041 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1042 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1043 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1044 IndexReg != X86::EIZ){
1045 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1050 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1055 ParseInstruction(StringRef Name, SMLoc NameLoc,
1056 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1057 StringRef PatchedName = Name;
1059 // FIXME: Hack to recognize setneb as setne.
1060 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1061 PatchedName != "setb" && PatchedName != "setnb")
1062 PatchedName = PatchedName.substr(0, Name.size()-1);
1064 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1065 const MCExpr *ExtraImmOp = 0;
1066 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1067 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1068 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1069 bool IsVCMP = PatchedName[0] == 'v';
1070 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1071 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1072 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1076 .Case("unord", 0x03)
1081 /* AVX only from here */
1082 .Case("eq_uq", 0x08)
1085 .Case("false", 0x0B)
1086 .Case("neq_oq", 0x0C)
1090 .Case("eq_os", 0x10)
1091 .Case("lt_oq", 0x11)
1092 .Case("le_oq", 0x12)
1093 .Case("unord_s", 0x13)
1094 .Case("neq_us", 0x14)
1095 .Case("nlt_uq", 0x15)
1096 .Case("nle_uq", 0x16)
1097 .Case("ord_s", 0x17)
1098 .Case("eq_us", 0x18)
1099 .Case("nge_uq", 0x19)
1100 .Case("ngt_uq", 0x1A)
1101 .Case("false_os", 0x1B)
1102 .Case("neq_os", 0x1C)
1103 .Case("ge_oq", 0x1D)
1104 .Case("gt_oq", 0x1E)
1105 .Case("true_us", 0x1F)
1107 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1108 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1109 getParser().getContext());
1110 if (PatchedName.endswith("ss")) {
1111 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1112 } else if (PatchedName.endswith("sd")) {
1113 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1114 } else if (PatchedName.endswith("ps")) {
1115 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1117 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1118 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1123 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1125 if (ExtraImmOp && !isParsingIntelSyntax())
1126 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1128 // Determine whether this is an instruction prefix.
1130 Name == "lock" || Name == "rep" ||
1131 Name == "repe" || Name == "repz" ||
1132 Name == "repne" || Name == "repnz" ||
1133 Name == "rex64" || Name == "data16";
1136 // This does the actual operand parsing. Don't parse any more if we have a
1137 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1138 // just want to parse the "lock" as the first instruction and the "incl" as
1140 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1142 // Parse '*' modifier.
1143 if (getLexer().is(AsmToken::Star)) {
1144 SMLoc Loc = Parser.getTok().getLoc();
1145 Operands.push_back(X86Operand::CreateToken("*", Loc));
1146 Parser.Lex(); // Eat the star.
1149 // Read the first operand.
1150 if (X86Operand *Op = ParseOperand())
1151 Operands.push_back(Op);
1153 Parser.EatToEndOfStatement();
1157 while (getLexer().is(AsmToken::Comma)) {
1158 Parser.Lex(); // Eat the comma.
1160 // Parse and remember the operand.
1161 if (X86Operand *Op = ParseOperand())
1162 Operands.push_back(Op);
1164 Parser.EatToEndOfStatement();
1169 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1170 SMLoc Loc = getLexer().getLoc();
1171 Parser.EatToEndOfStatement();
1172 return Error(Loc, "unexpected token in argument list");
1176 if (getLexer().is(AsmToken::EndOfStatement))
1177 Parser.Lex(); // Consume the EndOfStatement
1178 else if (isPrefix && getLexer().is(AsmToken::Slash))
1179 Parser.Lex(); // Consume the prefix separator Slash
1181 if (ExtraImmOp && isParsingIntelSyntax())
1182 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1184 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1185 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1186 // documented form in various unofficial manuals, so a lot of code uses it.
1187 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1188 Operands.size() == 3) {
1189 X86Operand &Op = *(X86Operand*)Operands.back();
1190 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1191 isa<MCConstantExpr>(Op.Mem.Disp) &&
1192 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1193 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1194 SMLoc Loc = Op.getEndLoc();
1195 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1199 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1200 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1201 Operands.size() == 3) {
1202 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1203 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1204 isa<MCConstantExpr>(Op.Mem.Disp) &&
1205 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1206 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1207 SMLoc Loc = Op.getEndLoc();
1208 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1212 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1213 if (Name.startswith("ins") && Operands.size() == 3 &&
1214 (Name == "insb" || Name == "insw" || Name == "insl")) {
1215 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1216 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1217 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1218 Operands.pop_back();
1219 Operands.pop_back();
1225 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1226 if (Name.startswith("outs") && Operands.size() == 3 &&
1227 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1228 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1229 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1230 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1231 Operands.pop_back();
1232 Operands.pop_back();
1238 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
1239 if (Name.startswith("movs") && Operands.size() == 3 &&
1240 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
1241 (is64BitMode() && Name == "movsq"))) {
1242 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1243 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1244 if (isSrcOp(Op) && isDstOp(Op2)) {
1245 Operands.pop_back();
1246 Operands.pop_back();
1251 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
1252 if (Name.startswith("lods") && Operands.size() == 3 &&
1253 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
1254 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
1255 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1256 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1257 if (isSrcOp(*Op1) && Op2->isReg()) {
1259 unsigned reg = Op2->getReg();
1260 bool isLods = Name == "lods";
1261 if (reg == X86::AL && (isLods || Name == "lodsb"))
1263 else if (reg == X86::AX && (isLods || Name == "lodsw"))
1265 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
1267 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
1272 Operands.pop_back();
1273 Operands.pop_back();
1277 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1281 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
1282 if (Name.startswith("stos") && Operands.size() == 3 &&
1283 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
1284 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
1285 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1286 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
1287 if (isDstOp(*Op2) && Op1->isReg()) {
1289 unsigned reg = Op1->getReg();
1290 bool isStos = Name == "stos";
1291 if (reg == X86::AL && (isStos || Name == "stosb"))
1293 else if (reg == X86::AX && (isStos || Name == "stosw"))
1295 else if (reg == X86::EAX && (isStos || Name == "stosl"))
1297 else if (reg == X86::RAX && (isStos || Name == "stosq"))
1302 Operands.pop_back();
1303 Operands.pop_back();
1307 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
1312 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
1314 if ((Name.startswith("shr") || Name.startswith("sar") ||
1315 Name.startswith("shl") || Name.startswith("sal") ||
1316 Name.startswith("rcl") || Name.startswith("rcr") ||
1317 Name.startswith("rol") || Name.startswith("ror")) &&
1318 Operands.size() == 3) {
1319 if (isParsingIntelSyntax()) {
1321 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
1322 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1323 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1325 Operands.pop_back();
1328 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1329 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1330 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
1332 Operands.erase(Operands.begin() + 1);
1337 // Transforms "int $3" into "int3" as a size optimization. We can't write an
1338 // instalias with an immediate operand yet.
1339 if (Name == "int" && Operands.size() == 2) {
1340 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
1341 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
1342 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
1344 Operands.erase(Operands.begin() + 1);
1345 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
1353 processInstruction(MCInst &Inst,
1354 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
1355 switch (Inst.getOpcode()) {
1356 default: return false;
1357 case X86::AND16i16: {
1358 if (!Inst.getOperand(0).isImm() ||
1359 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1363 TmpInst.setOpcode(X86::AND16ri8);
1364 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1365 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1366 TmpInst.addOperand(Inst.getOperand(0));
1370 case X86::AND32i32: {
1371 if (!Inst.getOperand(0).isImm() ||
1372 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1376 TmpInst.setOpcode(X86::AND32ri8);
1377 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1378 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1379 TmpInst.addOperand(Inst.getOperand(0));
1383 case X86::AND64i32: {
1384 if (!Inst.getOperand(0).isImm() ||
1385 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1389 TmpInst.setOpcode(X86::AND64ri8);
1390 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1391 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1392 TmpInst.addOperand(Inst.getOperand(0));
1396 case X86::XOR16i16: {
1397 if (!Inst.getOperand(0).isImm() ||
1398 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1402 TmpInst.setOpcode(X86::XOR16ri8);
1403 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1404 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1405 TmpInst.addOperand(Inst.getOperand(0));
1409 case X86::XOR32i32: {
1410 if (!Inst.getOperand(0).isImm() ||
1411 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1415 TmpInst.setOpcode(X86::XOR32ri8);
1416 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1417 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1418 TmpInst.addOperand(Inst.getOperand(0));
1422 case X86::XOR64i32: {
1423 if (!Inst.getOperand(0).isImm() ||
1424 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1428 TmpInst.setOpcode(X86::XOR64ri8);
1429 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1430 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1431 TmpInst.addOperand(Inst.getOperand(0));
1435 case X86::OR16i16: {
1436 if (!Inst.getOperand(0).isImm() ||
1437 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1441 TmpInst.setOpcode(X86::OR16ri8);
1442 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1443 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1444 TmpInst.addOperand(Inst.getOperand(0));
1448 case X86::OR32i32: {
1449 if (!Inst.getOperand(0).isImm() ||
1450 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1454 TmpInst.setOpcode(X86::OR32ri8);
1455 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1456 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1457 TmpInst.addOperand(Inst.getOperand(0));
1461 case X86::OR64i32: {
1462 if (!Inst.getOperand(0).isImm() ||
1463 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1467 TmpInst.setOpcode(X86::OR64ri8);
1468 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1469 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1470 TmpInst.addOperand(Inst.getOperand(0));
1474 case X86::CMP16i16: {
1475 if (!Inst.getOperand(0).isImm() ||
1476 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1480 TmpInst.setOpcode(X86::CMP16ri8);
1481 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1482 TmpInst.addOperand(Inst.getOperand(0));
1486 case X86::CMP32i32: {
1487 if (!Inst.getOperand(0).isImm() ||
1488 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1492 TmpInst.setOpcode(X86::CMP32ri8);
1493 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1494 TmpInst.addOperand(Inst.getOperand(0));
1498 case X86::CMP64i32: {
1499 if (!Inst.getOperand(0).isImm() ||
1500 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1504 TmpInst.setOpcode(X86::CMP64ri8);
1505 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1506 TmpInst.addOperand(Inst.getOperand(0));
1510 case X86::ADD16i16: {
1511 if (!Inst.getOperand(0).isImm() ||
1512 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1516 TmpInst.setOpcode(X86::ADD16ri8);
1517 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1518 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1519 TmpInst.addOperand(Inst.getOperand(0));
1523 case X86::ADD32i32: {
1524 if (!Inst.getOperand(0).isImm() ||
1525 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1529 TmpInst.setOpcode(X86::ADD32ri8);
1530 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1531 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1532 TmpInst.addOperand(Inst.getOperand(0));
1536 case X86::ADD64i32: {
1537 if (!Inst.getOperand(0).isImm() ||
1538 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1542 TmpInst.setOpcode(X86::ADD64ri8);
1543 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1544 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1545 TmpInst.addOperand(Inst.getOperand(0));
1549 case X86::SUB16i16: {
1550 if (!Inst.getOperand(0).isImm() ||
1551 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
1555 TmpInst.setOpcode(X86::SUB16ri8);
1556 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1557 TmpInst.addOperand(MCOperand::CreateReg(X86::AX));
1558 TmpInst.addOperand(Inst.getOperand(0));
1562 case X86::SUB32i32: {
1563 if (!Inst.getOperand(0).isImm() ||
1564 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
1568 TmpInst.setOpcode(X86::SUB32ri8);
1569 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1570 TmpInst.addOperand(MCOperand::CreateReg(X86::EAX));
1571 TmpInst.addOperand(Inst.getOperand(0));
1575 case X86::SUB64i32: {
1576 if (!Inst.getOperand(0).isImm() ||
1577 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
1581 TmpInst.setOpcode(X86::SUB64ri8);
1582 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1583 TmpInst.addOperand(MCOperand::CreateReg(X86::RAX));
1584 TmpInst.addOperand(Inst.getOperand(0));
1592 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
1593 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1594 MCStreamer &Out, unsigned &ErrorInfo,
1595 bool MatchingInlineAsm) {
1596 assert(!Operands.empty() && "Unexpect empty operand list!");
1597 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
1598 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
1599 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
1601 // First, handle aliases that expand to multiple instructions.
1602 // FIXME: This should be replaced with a real .td file alias mechanism.
1603 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
1605 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
1606 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
1607 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
1608 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
1610 Inst.setOpcode(X86::WAIT);
1612 if (!MatchingInlineAsm)
1613 Out.EmitInstruction(Inst);
1616 StringSwitch<const char*>(Op->getToken())
1617 .Case("finit", "fninit")
1618 .Case("fsave", "fnsave")
1619 .Case("fstcw", "fnstcw")
1620 .Case("fstcww", "fnstcw")
1621 .Case("fstenv", "fnstenv")
1622 .Case("fstsw", "fnstsw")
1623 .Case("fstsww", "fnstsw")
1624 .Case("fclex", "fnclex")
1626 assert(Repl && "Unknown wait-prefixed instruction");
1628 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
1631 bool WasOriginallyInvalidOperand = false;
1634 // First, try a direct match.
1635 switch (MatchInstructionImpl(Operands, Inst,
1636 ErrorInfo, MatchingInlineAsm,
1637 isParsingIntelSyntax())) {
1640 // Some instructions need post-processing to, for example, tweak which
1641 // encoding is selected. Loop on it while changes happen so the
1642 // individual transformations can chain off each other.
1643 if (!MatchingInlineAsm)
1644 while (processInstruction(Inst, Operands))
1648 if (!MatchingInlineAsm)
1649 Out.EmitInstruction(Inst);
1650 Opcode = Inst.getOpcode();
1652 case Match_MissingFeature:
1653 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1654 EmptyRanges, MatchingInlineAsm);
1656 case Match_InvalidOperand:
1657 WasOriginallyInvalidOperand = true;
1659 case Match_MnemonicFail:
1663 // FIXME: Ideally, we would only attempt suffix matches for things which are
1664 // valid prefixes, and we could just infer the right unambiguous
1665 // type. However, that requires substantially more matcher support than the
1668 // Change the operand to point to a temporary token.
1669 StringRef Base = Op->getToken();
1670 SmallString<16> Tmp;
1673 Op->setTokenValue(Tmp.str());
1675 // If this instruction starts with an 'f', then it is a floating point stack
1676 // instruction. These come in up to three forms for 32-bit, 64-bit, and
1677 // 80-bit floating point, which use the suffixes s,l,t respectively.
1679 // Otherwise, we assume that this may be an integer instruction, which comes
1680 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
1681 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
1683 // Check for the various suffix matches.
1684 Tmp[Base.size()] = Suffixes[0];
1685 unsigned ErrorInfoIgnore;
1686 unsigned Match1, Match2, Match3, Match4;
1688 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1689 isParsingIntelSyntax());
1690 Tmp[Base.size()] = Suffixes[1];
1691 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1692 isParsingIntelSyntax());
1693 Tmp[Base.size()] = Suffixes[2];
1694 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1695 isParsingIntelSyntax());
1696 Tmp[Base.size()] = Suffixes[3];
1697 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
1698 isParsingIntelSyntax());
1700 // Restore the old token.
1701 Op->setTokenValue(Base);
1703 // If exactly one matched, then we treat that as a successful match (and the
1704 // instruction will already have been filled in correctly, since the failing
1705 // matches won't have modified it).
1706 unsigned NumSuccessfulMatches =
1707 (Match1 == Match_Success) + (Match2 == Match_Success) +
1708 (Match3 == Match_Success) + (Match4 == Match_Success);
1709 if (NumSuccessfulMatches == 1) {
1711 if (!MatchingInlineAsm)
1712 Out.EmitInstruction(Inst);
1713 Opcode = Inst.getOpcode();
1717 // Otherwise, the match failed, try to produce a decent error message.
1719 // If we had multiple suffix matches, then identify this as an ambiguous
1721 if (NumSuccessfulMatches > 1) {
1723 unsigned NumMatches = 0;
1724 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
1725 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
1726 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
1727 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
1729 SmallString<126> Msg;
1730 raw_svector_ostream OS(Msg);
1731 OS << "ambiguous instructions require an explicit suffix (could be ";
1732 for (unsigned i = 0; i != NumMatches; ++i) {
1735 if (i + 1 == NumMatches)
1737 OS << "'" << Base << MatchChars[i] << "'";
1740 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
1744 // Okay, we know that none of the variants matched successfully.
1746 // If all of the instructions reported an invalid mnemonic, then the original
1747 // mnemonic was invalid.
1748 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
1749 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
1750 if (!WasOriginallyInvalidOperand) {
1751 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
1753 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
1754 Ranges, MatchingInlineAsm);
1757 // Recover location info for the operand if we know which was the problem.
1758 if (ErrorInfo != ~0U) {
1759 if (ErrorInfo >= Operands.size())
1760 return Error(IDLoc, "too few operands for instruction",
1761 EmptyRanges, MatchingInlineAsm);
1763 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
1764 if (Operand->getStartLoc().isValid()) {
1765 SMRange OperandRange = Operand->getLocRange();
1766 return Error(Operand->getStartLoc(), "invalid operand for instruction",
1767 OperandRange, MatchingInlineAsm);
1771 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1775 // If one instruction matched with a missing feature, report this as a
1777 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
1778 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
1779 Error(IDLoc, "instruction requires a CPU feature not currently enabled",
1780 EmptyRanges, MatchingInlineAsm);
1784 // If one instruction matched with an invalid operand, report this as an
1786 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
1787 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
1788 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
1793 // If all of these were an outright failure, report it in a useless way.
1794 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
1795 EmptyRanges, MatchingInlineAsm);
1800 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
1801 StringRef IDVal = DirectiveID.getIdentifier();
1802 if (IDVal == ".word")
1803 return ParseDirectiveWord(2, DirectiveID.getLoc());
1804 else if (IDVal.startswith(".code"))
1805 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
1806 else if (IDVal.startswith(".att_syntax")) {
1807 getParser().setAssemblerDialect(0);
1809 } else if (IDVal.startswith(".intel_syntax")) {
1810 getParser().setAssemblerDialect(1);
1811 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1812 if(Parser.getTok().getString() == "noprefix") {
1813 // FIXME : Handle noprefix
1823 /// ParseDirectiveWord
1824 /// ::= .word [ expression (, expression)* ]
1825 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1826 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1828 const MCExpr *Value;
1829 if (getParser().ParseExpression(Value))
1832 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
1834 if (getLexer().is(AsmToken::EndOfStatement))
1837 // FIXME: Improve diagnostic.
1838 if (getLexer().isNot(AsmToken::Comma))
1839 return Error(L, "unexpected token in directive");
1848 /// ParseDirectiveCode
1849 /// ::= .code32 | .code64
1850 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
1851 if (IDVal == ".code32") {
1853 if (is64BitMode()) {
1855 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1857 } else if (IDVal == ".code64") {
1859 if (!is64BitMode()) {
1861 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
1864 return Error(L, "unexpected directive " + IDVal);
1871 extern "C" void LLVMInitializeX86AsmLexer();
1873 // Force static initialization.
1874 extern "C" void LLVMInitializeX86AsmParser() {
1875 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
1876 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
1877 LLVMInitializeX86AsmLexer();
1880 #define GET_REGISTER_MATCHER
1881 #define GET_MATCHER_IMPLEMENTATION
1882 #include "X86GenAsmMatcher.inc"