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/ADT/APFloat.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCParser/MCAsmLexer.h"
21 #include "llvm/MC/MCParser/MCAsmParser.h"
22 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCTargetAsmParser.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/raw_ostream.h"
37 static const char OpPrecedence[] = {
50 class X86AsmParser : public MCTargetAsmParser {
53 ParseInstructionInfo *InstInfo;
55 SMLoc consumeToken() {
56 SMLoc Result = Parser.getTok().getLoc();
61 enum InfixCalculatorTok {
74 class InfixCalculator {
75 typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
76 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
77 SmallVector<ICToken, 4> PostfixStack;
80 int64_t popOperand() {
81 assert (!PostfixStack.empty() && "Poped an empty stack!");
82 ICToken Op = PostfixStack.pop_back_val();
83 assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
84 && "Expected and immediate or register!");
87 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
88 assert ((Op == IC_IMM || Op == IC_REGISTER) &&
89 "Unexpected operand!");
90 PostfixStack.push_back(std::make_pair(Op, Val));
93 void popOperator() { InfixOperatorStack.pop_back(); }
94 void pushOperator(InfixCalculatorTok Op) {
95 // Push the new operator if the stack is empty.
96 if (InfixOperatorStack.empty()) {
97 InfixOperatorStack.push_back(Op);
101 // Push the new operator if it has a higher precedence than the operator
102 // on the top of the stack or the operator on the top of the stack is a
104 unsigned Idx = InfixOperatorStack.size() - 1;
105 InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
106 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
107 InfixOperatorStack.push_back(Op);
111 // The operator on the top of the stack has higher precedence than the
113 unsigned ParenCount = 0;
115 // Nothing to process.
116 if (InfixOperatorStack.empty())
119 Idx = InfixOperatorStack.size() - 1;
120 StackOp = InfixOperatorStack[Idx];
121 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
124 // If we have an even parentheses count and we see a left parentheses,
125 // then stop processing.
126 if (!ParenCount && StackOp == IC_LPAREN)
129 if (StackOp == IC_RPAREN) {
131 InfixOperatorStack.pop_back();
132 } else if (StackOp == IC_LPAREN) {
134 InfixOperatorStack.pop_back();
136 InfixOperatorStack.pop_back();
137 PostfixStack.push_back(std::make_pair(StackOp, 0));
140 // Push the new operator.
141 InfixOperatorStack.push_back(Op);
144 // Push any remaining operators onto the postfix stack.
145 while (!InfixOperatorStack.empty()) {
146 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
147 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
148 PostfixStack.push_back(std::make_pair(StackOp, 0));
151 if (PostfixStack.empty())
154 SmallVector<ICToken, 16> OperandStack;
155 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
156 ICToken Op = PostfixStack[i];
157 if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
158 OperandStack.push_back(Op);
160 assert (OperandStack.size() > 1 && "Too few operands.");
162 ICToken Op2 = OperandStack.pop_back_val();
163 ICToken Op1 = OperandStack.pop_back_val();
166 report_fatal_error("Unexpected operator!");
169 Val = Op1.second + Op2.second;
170 OperandStack.push_back(std::make_pair(IC_IMM, Val));
173 Val = Op1.second - Op2.second;
174 OperandStack.push_back(std::make_pair(IC_IMM, Val));
177 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
178 "Multiply operation with an immediate and a register!");
179 Val = Op1.second * Op2.second;
180 OperandStack.push_back(std::make_pair(IC_IMM, Val));
183 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
184 "Divide operation with an immediate and a register!");
185 assert (Op2.second != 0 && "Division by zero!");
186 Val = Op1.second / Op2.second;
187 OperandStack.push_back(std::make_pair(IC_IMM, Val));
190 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
191 "Or operation with an immediate and a register!");
192 Val = Op1.second | Op2.second;
193 OperandStack.push_back(std::make_pair(IC_IMM, Val));
196 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
197 "And operation with an immediate and a register!");
198 Val = Op1.second & Op2.second;
199 OperandStack.push_back(std::make_pair(IC_IMM, Val));
204 assert (OperandStack.size() == 1 && "Expected a single result.");
205 return OperandStack.pop_back_val().second;
209 enum IntelExprState {
226 class IntelExprStateMachine {
227 IntelExprState State, PrevState;
228 unsigned BaseReg, IndexReg, TmpReg, Scale;
232 bool StopOnLBrac, AddImmPrefix;
234 InlineAsmIdentifierInfo Info;
236 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
237 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
238 Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac),
239 AddImmPrefix(addimmprefix) { Info.clear(); }
241 unsigned getBaseReg() { return BaseReg; }
242 unsigned getIndexReg() { return IndexReg; }
243 unsigned getScale() { return Scale; }
244 const MCExpr *getSym() { return Sym; }
245 StringRef getSymName() { return SymName; }
246 int64_t getImm() { return Imm + IC.execute(); }
247 bool isValidEndState() {
248 return State == IES_RBRAC || State == IES_INTEGER;
250 bool getStopOnLBrac() { return StopOnLBrac; }
251 bool getAddImmPrefix() { return AddImmPrefix; }
252 bool hadError() { return State == IES_ERROR; }
254 InlineAsmIdentifierInfo &getIdentifierInfo() {
259 IntelExprState CurrState = State;
268 IC.pushOperator(IC_OR);
271 PrevState = CurrState;
274 IntelExprState CurrState = State;
283 IC.pushOperator(IC_AND);
286 PrevState = CurrState;
289 IntelExprState CurrState = State;
298 IC.pushOperator(IC_PLUS);
299 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
300 // If we already have a BaseReg, then assume this is the IndexReg with
305 assert (!IndexReg && "BaseReg/IndexReg already set!");
312 PrevState = CurrState;
315 IntelExprState CurrState = State;
330 // Only push the minus operator if it is not a unary operator.
331 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
332 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
333 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
334 IC.pushOperator(IC_MINUS);
335 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
336 // If we already have a BaseReg, then assume this is the IndexReg with
341 assert (!IndexReg && "BaseReg/IndexReg already set!");
348 PrevState = CurrState;
350 void onRegister(unsigned Reg) {
351 IntelExprState CurrState = State;
358 State = IES_REGISTER;
360 IC.pushOperand(IC_REGISTER);
363 // Index Register - Scale * Register
364 if (PrevState == IES_INTEGER) {
365 assert (!IndexReg && "IndexReg already set!");
366 State = IES_REGISTER;
368 // Get the scale and replace the 'Scale * Register' with '0'.
369 Scale = IC.popOperand();
370 IC.pushOperand(IC_IMM);
377 PrevState = CurrState;
379 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
389 SymName = SymRefName;
390 IC.pushOperand(IC_IMM);
394 void onInteger(int64_t TmpInt) {
395 IntelExprState CurrState = State;
408 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
409 // Index Register - Register * Scale
410 assert (!IndexReg && "IndexReg already set!");
413 // Get the scale and replace the 'Register * Scale' with '0'.
415 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
416 PrevState == IES_OR || PrevState == IES_AND ||
417 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
418 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
419 CurrState == IES_MINUS) {
420 // Unary minus. No need to pop the minus operand because it was never
422 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
424 IC.pushOperand(IC_IMM, TmpInt);
428 PrevState = CurrState;
439 State = IES_MULTIPLY;
440 IC.pushOperator(IC_MULTIPLY);
453 IC.pushOperator(IC_DIVIDE);
465 IC.pushOperator(IC_PLUS);
470 IntelExprState CurrState = State;
479 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
480 // If we already have a BaseReg, then assume this is the IndexReg with
485 assert (!IndexReg && "BaseReg/IndexReg already set!");
492 PrevState = CurrState;
495 IntelExprState CurrState = State;
507 // FIXME: We don't handle this type of unary minus, yet.
508 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
509 PrevState == IES_OR || PrevState == IES_AND ||
510 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
511 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
512 CurrState == IES_MINUS) {
517 IC.pushOperator(IC_LPAREN);
520 PrevState = CurrState;
532 IC.pushOperator(IC_RPAREN);
538 MCAsmParser &getParser() const { return Parser; }
540 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
542 bool Error(SMLoc L, const Twine &Msg,
543 ArrayRef<SMRange> Ranges = None,
544 bool MatchingInlineAsm = false) {
545 if (MatchingInlineAsm) return true;
546 return Parser.Error(L, Msg, Ranges);
549 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
554 X86Operand *ParseOperand();
555 X86Operand *ParseATTOperand();
556 X86Operand *ParseIntelOperand();
557 X86Operand *ParseIntelOffsetOfOperator();
558 bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
559 X86Operand *ParseIntelOperator(unsigned OpKind);
560 X86Operand *ParseIntelSegmentOverride(unsigned SegReg, SMLoc Start, unsigned Size);
561 X86Operand *ParseIntelMemOperand(int64_t ImmDisp, SMLoc StartLoc,
563 bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
564 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
565 int64_t ImmDisp, unsigned Size);
566 bool ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
567 InlineAsmIdentifierInfo &Info,
568 bool IsUnevaluatedOperand, SMLoc &End);
570 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
572 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
573 unsigned BaseReg, unsigned IndexReg,
574 unsigned Scale, SMLoc Start, SMLoc End,
575 unsigned Size, StringRef Identifier,
576 InlineAsmIdentifierInfo &Info);
578 bool ParseDirectiveWord(unsigned Size, SMLoc L);
579 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
581 bool processInstruction(MCInst &Inst,
582 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
584 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
585 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
586 MCStreamer &Out, unsigned &ErrorInfo,
587 bool MatchingInlineAsm);
589 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
590 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
591 bool isSrcOp(X86Operand &Op);
593 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
594 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
595 bool isDstOp(X86Operand &Op);
597 bool is64BitMode() const {
598 // FIXME: Can tablegen auto-generate this?
599 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
601 bool is32BitMode() const {
602 // FIXME: Can tablegen auto-generate this?
603 return (STI.getFeatureBits() & X86::Mode32Bit) != 0;
605 bool is16BitMode() const {
606 // FIXME: Can tablegen auto-generate this?
607 return (STI.getFeatureBits() & X86::Mode16Bit) != 0;
609 void SwitchMode(uint64_t mode) {
610 uint64_t oldMode = STI.getFeatureBits() &
611 (X86::Mode64Bit | X86::Mode32Bit | X86::Mode16Bit);
612 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(oldMode | mode));
613 setAvailableFeatures(FB);
614 assert(mode == (STI.getFeatureBits() &
615 (X86::Mode64Bit | X86::Mode32Bit | X86::Mode16Bit)));
618 bool isParsingIntelSyntax() {
619 return getParser().getAssemblerDialect();
622 /// @name Auto-generated Matcher Functions
625 #define GET_ASSEMBLER_HEADER
626 #include "X86GenAsmMatcher.inc"
631 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
632 const MCInstrInfo &MII)
633 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
635 // Initialize the set of available features.
636 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
638 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
640 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
642 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
644 virtual bool ParseDirective(AsmToken DirectiveID);
646 } // end anonymous namespace
648 /// @name Auto-generated Match Functions
651 static unsigned MatchRegisterName(StringRef Name);
655 static bool isImmSExti16i8Value(uint64_t Value) {
656 return (( Value <= 0x000000000000007FULL)||
657 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
658 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
661 static bool isImmSExti32i8Value(uint64_t Value) {
662 return (( Value <= 0x000000000000007FULL)||
663 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
664 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
667 static bool isImmZExtu32u8Value(uint64_t Value) {
668 return (Value <= 0x00000000000000FFULL);
671 static bool isImmSExti64i8Value(uint64_t Value) {
672 return (( Value <= 0x000000000000007FULL)||
673 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
676 static bool isImmSExti64i32Value(uint64_t Value) {
677 return (( Value <= 0x000000007FFFFFFFULL)||
678 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
682 /// X86Operand - Instances of this class represent a parsed X86 machine
684 struct X86Operand : public MCParsedAsmOperand {
692 SMLoc StartLoc, EndLoc;
727 X86Operand(KindTy K, SMLoc Start, SMLoc End)
728 : Kind(K), StartLoc(Start), EndLoc(End) {}
730 StringRef getSymName() { return SymName; }
731 void *getOpDecl() { return OpDecl; }
733 /// getStartLoc - Get the location of the first token of this operand.
734 SMLoc getStartLoc() const { return StartLoc; }
735 /// getEndLoc - Get the location of the last token of this operand.
736 SMLoc getEndLoc() const { return EndLoc; }
737 /// getLocRange - Get the range between the first and last token of this
739 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
740 /// getOffsetOfLoc - Get the location of the offset operator.
741 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
743 virtual void print(raw_ostream &OS) const {}
745 StringRef getToken() const {
746 assert(Kind == Token && "Invalid access!");
747 return StringRef(Tok.Data, Tok.Length);
749 void setTokenValue(StringRef Value) {
750 assert(Kind == Token && "Invalid access!");
751 Tok.Data = Value.data();
752 Tok.Length = Value.size();
755 unsigned getReg() const {
756 assert(Kind == Register && "Invalid access!");
760 const MCExpr *getImm() const {
761 assert(Kind == Immediate && "Invalid access!");
765 const MCExpr *getMemDisp() const {
766 assert(Kind == Memory && "Invalid access!");
769 unsigned getMemSegReg() const {
770 assert(Kind == Memory && "Invalid access!");
773 unsigned getMemBaseReg() const {
774 assert(Kind == Memory && "Invalid access!");
777 unsigned getMemIndexReg() const {
778 assert(Kind == Memory && "Invalid access!");
781 unsigned getMemScale() const {
782 assert(Kind == Memory && "Invalid access!");
786 bool isToken() const {return Kind == Token; }
788 bool isImm() const { return Kind == Immediate; }
790 bool isImmSExti16i8() const {
794 // If this isn't a constant expr, just assume it fits and let relaxation
796 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
800 // Otherwise, check the value is in a range that makes sense for this
802 return isImmSExti16i8Value(CE->getValue());
804 bool isImmSExti32i8() const {
808 // If this isn't a constant expr, just assume it fits and let relaxation
810 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
814 // Otherwise, check the value is in a range that makes sense for this
816 return isImmSExti32i8Value(CE->getValue());
818 bool isImmZExtu32u8() const {
822 // If this isn't a constant expr, just assume it fits and let relaxation
824 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
828 // Otherwise, check the value is in a range that makes sense for this
830 return isImmZExtu32u8Value(CE->getValue());
832 bool isImmSExti64i8() const {
836 // If this isn't a constant expr, just assume it fits and let relaxation
838 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
842 // Otherwise, check the value is in a range that makes sense for this
844 return isImmSExti64i8Value(CE->getValue());
846 bool isImmSExti64i32() const {
850 // If this isn't a constant expr, just assume it fits and let relaxation
852 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
856 // Otherwise, check the value is in a range that makes sense for this
858 return isImmSExti64i32Value(CE->getValue());
861 bool isOffsetOf() const {
862 return OffsetOfLoc.getPointer();
865 bool needAddressOf() const {
869 bool isMem() const { return Kind == Memory; }
870 bool isMem8() const {
871 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
873 bool isMem16() const {
874 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
876 bool isMem32() const {
877 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
879 bool isMem64() const {
880 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
882 bool isMem80() const {
883 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
885 bool isMem128() const {
886 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
888 bool isMem256() const {
889 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
891 bool isMem512() const {
892 return Kind == Memory && (!Mem.Size || Mem.Size == 512);
895 bool isMemVX32() const {
896 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
897 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
899 bool isMemVY32() const {
900 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
901 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
903 bool isMemVX64() const {
904 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
905 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
907 bool isMemVY64() const {
908 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
909 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
911 bool isMemVZ32() const {
912 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
913 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
915 bool isMemVZ64() const {
916 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
917 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
920 bool isAbsMem() const {
921 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
922 !getMemIndexReg() && getMemScale() == 1;
925 bool isMemOffs8() const {
926 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
927 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 8);
929 bool isMemOffs16() const {
930 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
931 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 16);
933 bool isMemOffs32() const {
934 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
935 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 32);
937 bool isMemOffs64() const {
938 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
939 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 64);
942 bool isReg() const { return Kind == Register; }
944 bool isGR32orGR64() const {
945 return Kind == Register &&
946 (X86MCRegisterClasses[X86::GR32RegClassID].contains(getReg()) ||
947 X86MCRegisterClasses[X86::GR64RegClassID].contains(getReg()));
950 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
951 // Add as immediates when possible.
952 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
953 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
955 Inst.addOperand(MCOperand::CreateExpr(Expr));
958 void addRegOperands(MCInst &Inst, unsigned N) const {
959 assert(N == 1 && "Invalid number of operands!");
960 Inst.addOperand(MCOperand::CreateReg(getReg()));
963 static unsigned getGR32FromGR64(unsigned RegNo) {
965 default: llvm_unreachable("Unexpected register");
966 case X86::RAX: return X86::EAX;
967 case X86::RCX: return X86::ECX;
968 case X86::RDX: return X86::EDX;
969 case X86::RBX: return X86::EBX;
970 case X86::RBP: return X86::EBP;
971 case X86::RSP: return X86::ESP;
972 case X86::RSI: return X86::ESI;
973 case X86::RDI: return X86::EDI;
974 case X86::R8: return X86::R8D;
975 case X86::R9: return X86::R9D;
976 case X86::R10: return X86::R10D;
977 case X86::R11: return X86::R11D;
978 case X86::R12: return X86::R12D;
979 case X86::R13: return X86::R13D;
980 case X86::R14: return X86::R14D;
981 case X86::R15: return X86::R15D;
982 case X86::RIP: return X86::EIP;
986 void addGR32orGR64Operands(MCInst &Inst, unsigned N) const {
987 assert(N == 1 && "Invalid number of operands!");
988 unsigned RegNo = getReg();
989 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo))
990 RegNo = getGR32FromGR64(RegNo);
991 Inst.addOperand(MCOperand::CreateReg(RegNo));
994 void addImmOperands(MCInst &Inst, unsigned N) const {
995 assert(N == 1 && "Invalid number of operands!");
996 addExpr(Inst, getImm());
999 void addMemOperands(MCInst &Inst, unsigned N) const {
1000 assert((N == 5) && "Invalid number of operands!");
1001 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
1002 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
1003 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
1004 addExpr(Inst, getMemDisp());
1005 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
1008 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
1009 assert((N == 1) && "Invalid number of operands!");
1010 // Add as immediates when possible.
1011 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
1012 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1014 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
1017 void addMemOffsOperands(MCInst &Inst, unsigned N) const {
1018 assert((N == 1) && "Invalid number of operands!");
1019 // Add as immediates when possible.
1020 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
1021 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1023 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
1026 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
1027 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
1028 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
1029 Res->Tok.Data = Str.data();
1030 Res->Tok.Length = Str.size();
1034 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
1035 bool AddressOf = false,
1036 SMLoc OffsetOfLoc = SMLoc(),
1037 StringRef SymName = StringRef(),
1039 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
1040 Res->Reg.RegNo = RegNo;
1041 Res->AddressOf = AddressOf;
1042 Res->OffsetOfLoc = OffsetOfLoc;
1043 Res->SymName = SymName;
1044 Res->OpDecl = OpDecl;
1048 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
1049 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
1054 /// Create an absolute memory operand.
1055 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
1056 unsigned Size = 0, StringRef SymName = StringRef(),
1058 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1059 Res->Mem.SegReg = 0;
1060 Res->Mem.Disp = Disp;
1061 Res->Mem.BaseReg = 0;
1062 Res->Mem.IndexReg = 0;
1064 Res->Mem.Size = Size;
1065 Res->SymName = SymName;
1066 Res->OpDecl = OpDecl;
1067 Res->AddressOf = false;
1071 /// Create a generalized memory operand.
1072 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
1073 unsigned BaseReg, unsigned IndexReg,
1074 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
1076 StringRef SymName = StringRef(),
1078 // We should never just have a displacement, that should be parsed as an
1079 // absolute memory operand.
1080 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
1082 // The scale should always be one of {1,2,4,8}.
1083 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
1085 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1086 Res->Mem.SegReg = SegReg;
1087 Res->Mem.Disp = Disp;
1088 Res->Mem.BaseReg = BaseReg;
1089 Res->Mem.IndexReg = IndexReg;
1090 Res->Mem.Scale = Scale;
1091 Res->Mem.Size = Size;
1092 Res->SymName = SymName;
1093 Res->OpDecl = OpDecl;
1094 Res->AddressOf = false;
1099 } // end anonymous namespace.
1101 bool X86AsmParser::isSrcOp(X86Operand &Op) {
1103 is64BitMode() ? X86::RSI : (is32BitMode() ? X86::ESI : X86::SI);
1105 return (Op.isMem() &&
1106 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
1107 isa<MCConstantExpr>(Op.Mem.Disp) &&
1108 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1109 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
1112 bool X86AsmParser::isDstOp(X86Operand &Op) {
1114 is64BitMode() ? X86::RDI : (is32BitMode() ? X86::EDI : X86::DI);
1116 return Op.isMem() &&
1117 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
1118 isa<MCConstantExpr>(Op.Mem.Disp) &&
1119 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1120 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
1123 bool X86AsmParser::ParseRegister(unsigned &RegNo,
1124 SMLoc &StartLoc, SMLoc &EndLoc) {
1126 const AsmToken &PercentTok = Parser.getTok();
1127 StartLoc = PercentTok.getLoc();
1129 // If we encounter a %, ignore it. This code handles registers with and
1130 // without the prefix, unprefixed registers can occur in cfi directives.
1131 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1132 Parser.Lex(); // Eat percent token.
1134 const AsmToken &Tok = Parser.getTok();
1135 EndLoc = Tok.getEndLoc();
1137 if (Tok.isNot(AsmToken::Identifier)) {
1138 if (isParsingIntelSyntax()) return true;
1139 return Error(StartLoc, "invalid register name",
1140 SMRange(StartLoc, EndLoc));
1143 RegNo = MatchRegisterName(Tok.getString());
1145 // If the match failed, try the register name as lowercase.
1147 RegNo = MatchRegisterName(Tok.getString().lower());
1149 if (!is64BitMode()) {
1150 // FIXME: This should be done using Requires<Not64BitMode> and
1151 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1153 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1155 if (RegNo == X86::RIZ ||
1156 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1157 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1158 X86II::isX86_64ExtendedReg(RegNo))
1159 return Error(StartLoc, "register %"
1160 + Tok.getString() + " is only available in 64-bit mode",
1161 SMRange(StartLoc, EndLoc));
1164 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1165 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1167 Parser.Lex(); // Eat 'st'
1169 // Check to see if we have '(4)' after %st.
1170 if (getLexer().isNot(AsmToken::LParen))
1175 const AsmToken &IntTok = Parser.getTok();
1176 if (IntTok.isNot(AsmToken::Integer))
1177 return Error(IntTok.getLoc(), "expected stack index");
1178 switch (IntTok.getIntVal()) {
1179 case 0: RegNo = X86::ST0; break;
1180 case 1: RegNo = X86::ST1; break;
1181 case 2: RegNo = X86::ST2; break;
1182 case 3: RegNo = X86::ST3; break;
1183 case 4: RegNo = X86::ST4; break;
1184 case 5: RegNo = X86::ST5; break;
1185 case 6: RegNo = X86::ST6; break;
1186 case 7: RegNo = X86::ST7; break;
1187 default: return Error(IntTok.getLoc(), "invalid stack index");
1190 if (getParser().Lex().isNot(AsmToken::RParen))
1191 return Error(Parser.getTok().getLoc(), "expected ')'");
1193 EndLoc = Parser.getTok().getEndLoc();
1194 Parser.Lex(); // Eat ')'
1198 EndLoc = Parser.getTok().getEndLoc();
1200 // If this is "db[0-7]", match it as an alias
1202 if (RegNo == 0 && Tok.getString().size() == 3 &&
1203 Tok.getString().startswith("db")) {
1204 switch (Tok.getString()[2]) {
1205 case '0': RegNo = X86::DR0; break;
1206 case '1': RegNo = X86::DR1; break;
1207 case '2': RegNo = X86::DR2; break;
1208 case '3': RegNo = X86::DR3; break;
1209 case '4': RegNo = X86::DR4; break;
1210 case '5': RegNo = X86::DR5; break;
1211 case '6': RegNo = X86::DR6; break;
1212 case '7': RegNo = X86::DR7; break;
1216 EndLoc = Parser.getTok().getEndLoc();
1217 Parser.Lex(); // Eat it.
1223 if (isParsingIntelSyntax()) return true;
1224 return Error(StartLoc, "invalid register name",
1225 SMRange(StartLoc, EndLoc));
1228 Parser.Lex(); // Eat identifier token.
1232 X86Operand *X86AsmParser::ParseOperand() {
1233 if (isParsingIntelSyntax())
1234 return ParseIntelOperand();
1235 return ParseATTOperand();
1238 /// getIntelMemOperandSize - Return intel memory operand size.
1239 static unsigned getIntelMemOperandSize(StringRef OpStr) {
1240 unsigned Size = StringSwitch<unsigned>(OpStr)
1241 .Cases("BYTE", "byte", 8)
1242 .Cases("WORD", "word", 16)
1243 .Cases("DWORD", "dword", 32)
1244 .Cases("QWORD", "qword", 64)
1245 .Cases("XWORD", "xword", 80)
1246 .Cases("XMMWORD", "xmmword", 128)
1247 .Cases("YMMWORD", "ymmword", 256)
1253 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1254 unsigned BaseReg, unsigned IndexReg,
1255 unsigned Scale, SMLoc Start, SMLoc End,
1256 unsigned Size, StringRef Identifier,
1257 InlineAsmIdentifierInfo &Info){
1258 if (isa<MCSymbolRefExpr>(Disp)) {
1259 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1260 // reference. We need an 'r' constraint here, so we need to create register
1261 // operand to ensure proper matching. Just pick a GPR based on the size of
1263 if (!Info.IsVarDecl) {
1265 is64BitMode() ? X86::RBX : (is32BitMode() ? X86::EBX : X86::BX);
1266 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1267 SMLoc(), Identifier, Info.OpDecl);
1270 Size = Info.Type * 8; // Size is in terms of bits in this context.
1272 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1277 // When parsing inline assembly we set the base register to a non-zero value
1278 // if we don't know the actual value at this time. This is necessary to
1279 // get the matching correct in some cases.
1280 BaseReg = BaseReg ? BaseReg : 1;
1281 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1282 End, Size, Identifier, Info.OpDecl);
1286 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1287 StringRef SymName, int64_t ImmDisp,
1288 int64_t FinalImmDisp, SMLoc &BracLoc,
1289 SMLoc &StartInBrac, SMLoc &End) {
1290 // Remove the '[' and ']' from the IR string.
1291 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1292 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1294 // If ImmDisp is non-zero, then we parsed a displacement before the
1295 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1296 // If ImmDisp doesn't match the displacement computed by the state machine
1297 // then we have an additional displacement in the bracketed expression.
1298 if (ImmDisp != FinalImmDisp) {
1300 // We have an immediate displacement before the bracketed expression.
1301 // Adjust this to match the final immediate displacement.
1303 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1304 E = AsmRewrites->end(); I != E; ++I) {
1305 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1307 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1308 assert (!Found && "ImmDisp already rewritten.");
1309 (*I).Kind = AOK_Imm;
1310 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1311 (*I).Val = FinalImmDisp;
1316 assert (Found && "Unable to rewrite ImmDisp.");
1319 // We have a symbolic and an immediate displacement, but no displacement
1320 // before the bracketed expression. Put the immediate displacement
1321 // before the bracketed expression.
1322 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1325 // Remove all the ImmPrefix rewrites within the brackets.
1326 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1327 E = AsmRewrites->end(); I != E; ++I) {
1328 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1330 if ((*I).Kind == AOK_ImmPrefix)
1331 (*I).Kind = AOK_Delete;
1333 const char *SymLocPtr = SymName.data();
1334 // Skip everything before the symbol.
1335 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1336 assert(Len > 0 && "Expected a non-negative length.");
1337 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1339 // Skip everything after the symbol.
1340 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1341 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1342 assert(Len > 0 && "Expected a non-negative length.");
1343 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1347 bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1348 const AsmToken &Tok = Parser.getTok();
1352 bool UpdateLocLex = true;
1354 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1355 // identifier. Don't try an parse it as a register.
1356 if (Tok.getString().startswith("."))
1359 // If we're parsing an immediate expression, we don't expect a '['.
1360 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1363 switch (getLexer().getKind()) {
1365 if (SM.isValidEndState()) {
1369 return Error(Tok.getLoc(), "unknown token in expression");
1371 case AsmToken::EndOfStatement: {
1375 case AsmToken::Identifier: {
1376 // This could be a register or a symbolic displacement.
1379 SMLoc IdentLoc = Tok.getLoc();
1380 StringRef Identifier = Tok.getString();
1381 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1382 SM.onRegister(TmpReg);
1383 UpdateLocLex = false;
1386 if (!isParsingInlineAsm()) {
1387 if (getParser().parsePrimaryExpr(Val, End))
1388 return Error(Tok.getLoc(), "Unexpected identifier!");
1390 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1391 if (ParseIntelIdentifier(Val, Identifier, Info,
1392 /*Unevaluated=*/false, End))
1395 SM.onIdentifierExpr(Val, Identifier);
1396 UpdateLocLex = false;
1399 return Error(Tok.getLoc(), "Unexpected identifier!");
1401 case AsmToken::Integer: {
1402 if (isParsingInlineAsm() && SM.getAddImmPrefix())
1403 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1405 // Look for 'b' or 'f' following an Integer as a directional label
1406 SMLoc Loc = getTok().getLoc();
1407 int64_t IntVal = getTok().getIntVal();
1408 End = consumeToken();
1409 UpdateLocLex = false;
1410 if (getLexer().getKind() == AsmToken::Identifier) {
1411 StringRef IDVal = getTok().getString();
1412 if (IDVal == "f" || IDVal == "b") {
1414 getContext().GetDirectionalLocalSymbol(IntVal,
1415 IDVal == "f" ? 1 : 0);
1416 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1418 MCSymbolRefExpr::Create(Sym, Variant, getContext());
1419 if (IDVal == "b" && Sym->isUndefined())
1420 return Error(Loc, "invalid reference to undefined symbol");
1421 StringRef Identifier = Sym->getName();
1422 SM.onIdentifierExpr(Val, Identifier);
1423 End = consumeToken();
1425 SM.onInteger(IntVal);
1428 SM.onInteger(IntVal);
1432 case AsmToken::Plus: SM.onPlus(); break;
1433 case AsmToken::Minus: SM.onMinus(); break;
1434 case AsmToken::Star: SM.onStar(); break;
1435 case AsmToken::Slash: SM.onDivide(); break;
1436 case AsmToken::Pipe: SM.onOr(); break;
1437 case AsmToken::Amp: SM.onAnd(); break;
1438 case AsmToken::LBrac: SM.onLBrac(); break;
1439 case AsmToken::RBrac: SM.onRBrac(); break;
1440 case AsmToken::LParen: SM.onLParen(); break;
1441 case AsmToken::RParen: SM.onRParen(); break;
1444 return Error(Tok.getLoc(), "unknown token in expression");
1446 if (!Done && UpdateLocLex)
1447 End = consumeToken();
1452 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1455 const AsmToken &Tok = Parser.getTok();
1456 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1457 if (getLexer().isNot(AsmToken::LBrac))
1458 return ErrorOperand(BracLoc, "Expected '[' token!");
1459 Parser.Lex(); // Eat '['
1461 SMLoc StartInBrac = Tok.getLoc();
1462 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1463 // may have already parsed an immediate displacement before the bracketed
1465 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1466 if (ParseIntelExpression(SM, End))
1470 if (const MCExpr *Sym = SM.getSym()) {
1471 // A symbolic displacement.
1473 if (isParsingInlineAsm())
1474 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1475 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1478 // An immediate displacement only.
1479 Disp = MCConstantExpr::Create(SM.getImm(), getContext());
1482 // Parse the dot operator (e.g., [ebx].foo.bar).
1483 if (Tok.getString().startswith(".")) {
1484 const MCExpr *NewDisp;
1485 if (ParseIntelDotOperator(Disp, NewDisp))
1488 End = Tok.getEndLoc();
1489 Parser.Lex(); // Eat the field.
1493 int BaseReg = SM.getBaseReg();
1494 int IndexReg = SM.getIndexReg();
1495 int Scale = SM.getScale();
1496 if (!isParsingInlineAsm()) {
1498 if (!BaseReg && !IndexReg) {
1500 return X86Operand::CreateMem(Disp, Start, End, Size);
1502 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1504 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1508 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1509 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1510 End, Size, SM.getSymName(), Info);
1513 // Inline assembly may use variable names with namespace alias qualifiers.
1514 bool X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1515 StringRef &Identifier,
1516 InlineAsmIdentifierInfo &Info,
1517 bool IsUnevaluatedOperand, SMLoc &End) {
1518 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1521 StringRef LineBuf(Identifier.data());
1522 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
1524 const AsmToken &Tok = Parser.getTok();
1526 // Advance the token stream until the end of the current token is
1527 // after the end of what the frontend claimed.
1528 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
1530 End = Tok.getEndLoc();
1533 assert(End.getPointer() <= EndPtr && "frontend claimed part of a token?");
1534 if (End.getPointer() == EndPtr) break;
1537 // Create the symbol reference.
1538 Identifier = LineBuf;
1539 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1540 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1541 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1545 /// \brief Parse intel style segment override.
1546 X86Operand *X86AsmParser::ParseIntelSegmentOverride(unsigned SegReg,
1549 assert(SegReg != 0 && "Tried to parse a segment override without a segment!");
1550 const AsmToken &Tok = Parser.getTok(); // Eat colon.
1551 if (Tok.isNot(AsmToken::Colon))
1552 return ErrorOperand(Tok.getLoc(), "Expected ':' token!");
1553 Parser.Lex(); // Eat ':'
1555 int64_t ImmDisp = 0;
1556 if (getLexer().is(AsmToken::Integer)) {
1557 ImmDisp = Tok.getIntVal();
1558 AsmToken ImmDispToken = Parser.Lex(); // Eat the integer.
1560 if (isParsingInlineAsm())
1561 InstInfo->AsmRewrites->push_back(
1562 AsmRewrite(AOK_ImmPrefix, ImmDispToken.getLoc()));
1564 if (getLexer().isNot(AsmToken::LBrac)) {
1565 // An immediate following a 'segment register', 'colon' token sequence can
1566 // be followed by a bracketed expression. If it isn't we know we have our
1567 // final segment override.
1568 const MCExpr *Disp = MCConstantExpr::Create(ImmDisp, getContext());
1569 return X86Operand::CreateMem(SegReg, Disp, /*BaseReg=*/0, /*IndexReg=*/0,
1570 /*Scale=*/1, Start, ImmDispToken.getEndLoc(),
1575 if (getLexer().is(AsmToken::LBrac))
1576 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1580 if (!isParsingInlineAsm()) {
1581 if (getParser().parsePrimaryExpr(Val, End))
1582 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1584 return X86Operand::CreateMem(Val, Start, End, Size);
1587 InlineAsmIdentifierInfo Info;
1588 StringRef Identifier = Tok.getString();
1589 if (ParseIntelIdentifier(Val, Identifier, Info,
1590 /*Unevaluated=*/false, End))
1592 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1593 /*Scale=*/1, Start, End, Size, Identifier, Info);
1596 /// ParseIntelMemOperand - Parse intel style memory operand.
1597 X86Operand *X86AsmParser::ParseIntelMemOperand(int64_t ImmDisp, SMLoc Start,
1599 const AsmToken &Tok = Parser.getTok();
1602 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1603 if (getLexer().is(AsmToken::LBrac))
1604 return ParseIntelBracExpression(/*SegReg=*/0, Start, ImmDisp, Size);
1607 if (!isParsingInlineAsm()) {
1608 if (getParser().parsePrimaryExpr(Val, End))
1609 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1611 return X86Operand::CreateMem(Val, Start, End, Size);
1614 InlineAsmIdentifierInfo Info;
1615 StringRef Identifier = Tok.getString();
1616 if (ParseIntelIdentifier(Val, Identifier, Info,
1617 /*Unevaluated=*/false, End))
1619 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0, /*IndexReg=*/0,
1620 /*Scale=*/1, Start, End, Size, Identifier, Info);
1623 /// Parse the '.' operator.
1624 bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1625 const MCExpr *&NewDisp) {
1626 const AsmToken &Tok = Parser.getTok();
1627 int64_t OrigDispVal, DotDispVal;
1629 // FIXME: Handle non-constant expressions.
1630 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1631 OrigDispVal = OrigDisp->getValue();
1633 return Error(Tok.getLoc(), "Non-constant offsets are not supported!");
1636 StringRef DotDispStr = Tok.getString().drop_front(1);
1638 // .Imm gets lexed as a real.
1639 if (Tok.is(AsmToken::Real)) {
1641 DotDispStr.getAsInteger(10, DotDisp);
1642 DotDispVal = DotDisp.getZExtValue();
1643 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1645 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1646 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1648 return Error(Tok.getLoc(), "Unable to lookup field reference!");
1649 DotDispVal = DotDisp;
1651 return Error(Tok.getLoc(), "Unexpected token type!");
1653 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1654 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1655 unsigned Len = DotDispStr.size();
1656 unsigned Val = OrigDispVal + DotDispVal;
1657 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1661 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1665 /// Parse the 'offset' operator. This operator is used to specify the
1666 /// location rather then the content of a variable.
1667 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1668 const AsmToken &Tok = Parser.getTok();
1669 SMLoc OffsetOfLoc = Tok.getLoc();
1670 Parser.Lex(); // Eat offset.
1673 InlineAsmIdentifierInfo Info;
1674 SMLoc Start = Tok.getLoc(), End;
1675 StringRef Identifier = Tok.getString();
1676 if (ParseIntelIdentifier(Val, Identifier, Info,
1677 /*Unevaluated=*/false, End))
1680 // Don't emit the offset operator.
1681 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1683 // The offset operator will have an 'r' constraint, thus we need to create
1684 // register operand to ensure proper matching. Just pick a GPR based on
1685 // the size of a pointer.
1687 is64BitMode() ? X86::RBX : (is32BitMode() ? X86::EBX : X86::BX);
1688 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1689 OffsetOfLoc, Identifier, Info.OpDecl);
1692 enum IntelOperatorKind {
1698 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1699 /// returns the number of elements in an array. It returns the value 1 for
1700 /// non-array variables. The SIZE operator returns the size of a C or C++
1701 /// variable. A variable's size is the product of its LENGTH and TYPE. The
1702 /// TYPE operator returns the size of a C or C++ type or variable. If the
1703 /// variable is an array, TYPE returns the size of a single element.
1704 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1705 const AsmToken &Tok = Parser.getTok();
1706 SMLoc TypeLoc = Tok.getLoc();
1707 Parser.Lex(); // Eat operator.
1709 const MCExpr *Val = 0;
1710 InlineAsmIdentifierInfo Info;
1711 SMLoc Start = Tok.getLoc(), End;
1712 StringRef Identifier = Tok.getString();
1713 if (ParseIntelIdentifier(Val, Identifier, Info,
1714 /*Unevaluated=*/true, End))
1718 return ErrorOperand(Start, "unable to lookup expression");
1722 default: llvm_unreachable("Unexpected operand kind!");
1723 case IOK_LENGTH: CVal = Info.Length; break;
1724 case IOK_SIZE: CVal = Info.Size; break;
1725 case IOK_TYPE: CVal = Info.Type; break;
1728 // Rewrite the type operator and the C or C++ type or variable in terms of an
1729 // immediate. E.g. TYPE foo -> $$4
1730 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1731 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1733 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1734 return X86Operand::CreateImm(Imm, Start, End);
1737 X86Operand *X86AsmParser::ParseIntelOperand() {
1738 const AsmToken &Tok = Parser.getTok();
1741 // Offset, length, type and size operators.
1742 if (isParsingInlineAsm()) {
1743 StringRef AsmTokStr = Tok.getString();
1744 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1745 return ParseIntelOffsetOfOperator();
1746 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1747 return ParseIntelOperator(IOK_LENGTH);
1748 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1749 return ParseIntelOperator(IOK_SIZE);
1750 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1751 return ParseIntelOperator(IOK_TYPE);
1754 unsigned Size = getIntelMemOperandSize(Tok.getString());
1756 Parser.Lex(); // Eat operand size (e.g., byte, word).
1757 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1758 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1759 Parser.Lex(); // Eat ptr.
1761 Start = Tok.getLoc();
1764 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1765 getLexer().is(AsmToken::LParen)) {
1766 AsmToken StartTok = Tok;
1767 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1768 /*AddImmPrefix=*/false);
1769 if (ParseIntelExpression(SM, End))
1772 int64_t Imm = SM.getImm();
1773 if (isParsingInlineAsm()) {
1774 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1775 if (StartTok.getString().size() == Len)
1776 // Just add a prefix if this wasn't a complex immediate expression.
1777 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1779 // Otherwise, rewrite the complex expression as a single immediate.
1780 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1783 if (getLexer().isNot(AsmToken::LBrac)) {
1784 // If a directional label (ie. 1f or 2b) was parsed above from
1785 // ParseIntelExpression() then SM.getSym() was set to a pointer to
1786 // to the MCExpr with the directional local symbol and this is a
1787 // memory operand not an immediate operand.
1789 return X86Operand::CreateMem(SM.getSym(), Start, End, Size);
1791 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1792 return X86Operand::CreateImm(ImmExpr, Start, End);
1795 // Only positive immediates are valid.
1797 return ErrorOperand(Start, "expected a positive immediate displacement "
1798 "before bracketed expr.");
1800 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1801 return ParseIntelMemOperand(Imm, Start, Size);
1806 if (!ParseRegister(RegNo, Start, End)) {
1807 // If this is a segment register followed by a ':', then this is the start
1808 // of a segment override, otherwise this is a normal register reference.
1809 if (getLexer().isNot(AsmToken::Colon))
1810 return X86Operand::CreateReg(RegNo, Start, End);
1812 return ParseIntelSegmentOverride(/*SegReg=*/RegNo, Start, Size);
1816 return ParseIntelMemOperand(/*Disp=*/0, Start, Size);
1819 X86Operand *X86AsmParser::ParseATTOperand() {
1820 switch (getLexer().getKind()) {
1822 // Parse a memory operand with no segment register.
1823 return ParseMemOperand(0, Parser.getTok().getLoc());
1824 case AsmToken::Percent: {
1825 // Read the register.
1828 if (ParseRegister(RegNo, Start, End)) return 0;
1829 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1830 Error(Start, "%eiz and %riz can only be used as index registers",
1831 SMRange(Start, End));
1835 // If this is a segment register followed by a ':', then this is the start
1836 // of a memory reference, otherwise this is a normal register reference.
1837 if (getLexer().isNot(AsmToken::Colon))
1838 return X86Operand::CreateReg(RegNo, Start, End);
1840 getParser().Lex(); // Eat the colon.
1841 return ParseMemOperand(RegNo, Start);
1843 case AsmToken::Dollar: {
1844 // $42 -> immediate.
1845 SMLoc Start = Parser.getTok().getLoc(), End;
1848 if (getParser().parseExpression(Val, End))
1850 return X86Operand::CreateImm(Val, Start, End);
1855 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1856 /// has already been parsed if present.
1857 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1859 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1860 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1861 // only way to do this without lookahead is to eat the '(' and see what is
1863 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1864 if (getLexer().isNot(AsmToken::LParen)) {
1866 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1868 // After parsing the base expression we could either have a parenthesized
1869 // memory address or not. If not, return now. If so, eat the (.
1870 if (getLexer().isNot(AsmToken::LParen)) {
1871 // Unless we have a segment register, treat this as an immediate.
1873 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1874 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1880 // Okay, we have a '('. We don't know if this is an expression or not, but
1881 // so we have to eat the ( to see beyond it.
1882 SMLoc LParenLoc = Parser.getTok().getLoc();
1883 Parser.Lex(); // Eat the '('.
1885 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1886 // Nothing to do here, fall into the code below with the '(' part of the
1887 // memory operand consumed.
1891 // It must be an parenthesized expression, parse it now.
1892 if (getParser().parseParenExpression(Disp, ExprEnd))
1895 // After parsing the base expression we could either have a parenthesized
1896 // memory address or not. If not, return now. If so, eat the (.
1897 if (getLexer().isNot(AsmToken::LParen)) {
1898 // Unless we have a segment register, treat this as an immediate.
1900 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1901 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1909 // If we reached here, then we just ate the ( of the memory operand. Process
1910 // the rest of the memory operand.
1911 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1912 SMLoc IndexLoc, BaseLoc;
1914 if (getLexer().is(AsmToken::Percent)) {
1915 SMLoc StartLoc, EndLoc;
1916 BaseLoc = Parser.getTok().getLoc();
1917 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1918 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1919 Error(StartLoc, "eiz and riz can only be used as index registers",
1920 SMRange(StartLoc, EndLoc));
1925 if (getLexer().is(AsmToken::Comma)) {
1926 Parser.Lex(); // Eat the comma.
1927 IndexLoc = Parser.getTok().getLoc();
1929 // Following the comma we should have either an index register, or a scale
1930 // value. We don't support the later form, but we want to parse it
1933 // Not that even though it would be completely consistent to support syntax
1934 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1935 if (getLexer().is(AsmToken::Percent)) {
1937 if (ParseRegister(IndexReg, L, L)) return 0;
1939 if (getLexer().isNot(AsmToken::RParen)) {
1940 // Parse the scale amount:
1941 // ::= ',' [scale-expression]
1942 if (getLexer().isNot(AsmToken::Comma)) {
1943 Error(Parser.getTok().getLoc(),
1944 "expected comma in scale expression");
1947 Parser.Lex(); // Eat the comma.
1949 if (getLexer().isNot(AsmToken::RParen)) {
1950 SMLoc Loc = Parser.getTok().getLoc();
1953 if (getParser().parseAbsoluteExpression(ScaleVal)){
1954 Error(Loc, "expected scale expression");
1958 // Validate the scale amount.
1959 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) &&
1961 Error(Loc, "scale factor in 16-bit address must be 1");
1964 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1965 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1968 Scale = (unsigned)ScaleVal;
1971 } else if (getLexer().isNot(AsmToken::RParen)) {
1972 // A scale amount without an index is ignored.
1974 SMLoc Loc = Parser.getTok().getLoc();
1977 if (getParser().parseAbsoluteExpression(Value))
1981 Warning(Loc, "scale factor without index register is ignored");
1986 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1987 if (getLexer().isNot(AsmToken::RParen)) {
1988 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1991 SMLoc MemEnd = Parser.getTok().getEndLoc();
1992 Parser.Lex(); // Eat the ')'.
1994 // Check for use of invalid 16-bit registers. Only BX/BP/SI/DI are allowed,
1995 // and then only in non-64-bit modes. Except for DX, which is a special case
1996 // because an unofficial form of in/out instructions uses it.
1997 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) &&
1998 (is64BitMode() || (BaseReg != X86::BX && BaseReg != X86::BP &&
1999 BaseReg != X86::SI && BaseReg != X86::DI)) &&
2000 BaseReg != X86::DX) {
2001 Error(BaseLoc, "invalid 16-bit base register");
2005 X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)) {
2006 Error(IndexLoc, "16-bit memory operand may not include only index register");
2009 // If we have both a base register and an index register make sure they are
2010 // both 64-bit or 32-bit registers.
2011 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
2012 if (BaseReg != 0 && IndexReg != 0) {
2013 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
2014 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
2015 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
2016 IndexReg != X86::RIZ) {
2017 Error(BaseLoc, "base register is 64-bit, but index register is not");
2020 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
2021 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
2022 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
2023 IndexReg != X86::EIZ){
2024 Error(BaseLoc, "base register is 32-bit, but index register is not");
2027 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg)) {
2028 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) ||
2029 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) {
2030 Error(BaseLoc, "base register is 16-bit, but index register is not");
2033 if (((BaseReg == X86::BX || BaseReg == X86::BP) &&
2034 IndexReg != X86::SI && IndexReg != X86::DI) ||
2035 ((BaseReg == X86::SI || BaseReg == X86::DI) &&
2036 IndexReg != X86::BX && IndexReg != X86::BP)) {
2037 Error(BaseLoc, "invalid 16-bit base/index register combination");
2043 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
2048 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
2049 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2051 StringRef PatchedName = Name;
2053 // FIXME: Hack to recognize setneb as setne.
2054 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
2055 PatchedName != "setb" && PatchedName != "setnb")
2056 PatchedName = PatchedName.substr(0, Name.size()-1);
2058 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
2059 const MCExpr *ExtraImmOp = 0;
2060 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
2061 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
2062 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
2063 bool IsVCMP = PatchedName[0] == 'v';
2064 unsigned SSECCIdx = IsVCMP ? 4 : 3;
2065 unsigned SSEComparisonCode = StringSwitch<unsigned>(
2066 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
2070 .Case("unord", 0x03)
2075 /* AVX only from here */
2076 .Case("eq_uq", 0x08)
2079 .Case("false", 0x0B)
2080 .Case("neq_oq", 0x0C)
2084 .Case("eq_os", 0x10)
2085 .Case("lt_oq", 0x11)
2086 .Case("le_oq", 0x12)
2087 .Case("unord_s", 0x13)
2088 .Case("neq_us", 0x14)
2089 .Case("nlt_uq", 0x15)
2090 .Case("nle_uq", 0x16)
2091 .Case("ord_s", 0x17)
2092 .Case("eq_us", 0x18)
2093 .Case("nge_uq", 0x19)
2094 .Case("ngt_uq", 0x1A)
2095 .Case("false_os", 0x1B)
2096 .Case("neq_os", 0x1C)
2097 .Case("ge_oq", 0x1D)
2098 .Case("gt_oq", 0x1E)
2099 .Case("true_us", 0x1F)
2101 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
2102 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
2103 getParser().getContext());
2104 if (PatchedName.endswith("ss")) {
2105 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
2106 } else if (PatchedName.endswith("sd")) {
2107 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
2108 } else if (PatchedName.endswith("ps")) {
2109 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
2111 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
2112 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
2117 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
2119 if (ExtraImmOp && !isParsingIntelSyntax())
2120 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
2122 // Determine whether this is an instruction prefix.
2124 Name == "lock" || Name == "rep" ||
2125 Name == "repe" || Name == "repz" ||
2126 Name == "repne" || Name == "repnz" ||
2127 Name == "rex64" || Name == "data16";
2130 // This does the actual operand parsing. Don't parse any more if we have a
2131 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
2132 // just want to parse the "lock" as the first instruction and the "incl" as
2134 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
2136 // Parse '*' modifier.
2137 if (getLexer().is(AsmToken::Star))
2138 Operands.push_back(X86Operand::CreateToken("*", consumeToken()));
2140 // Read the first operand.
2141 if (X86Operand *Op = ParseOperand())
2142 Operands.push_back(Op);
2144 Parser.eatToEndOfStatement();
2148 while (getLexer().is(AsmToken::Comma)) {
2149 Parser.Lex(); // Eat the comma.
2151 // Parse and remember the operand.
2152 if (X86Operand *Op = ParseOperand())
2153 Operands.push_back(Op);
2155 Parser.eatToEndOfStatement();
2160 if (STI.getFeatureBits() & X86::FeatureAVX512) {
2161 // Parse mask register {%k1}
2162 if (getLexer().is(AsmToken::LCurly)) {
2163 Operands.push_back(X86Operand::CreateToken("{", consumeToken()));
2164 if (X86Operand *Op = ParseOperand()) {
2165 Operands.push_back(Op);
2166 if (!getLexer().is(AsmToken::RCurly)) {
2167 SMLoc Loc = getLexer().getLoc();
2168 Parser.eatToEndOfStatement();
2169 return Error(Loc, "Expected } at this point");
2171 Operands.push_back(X86Operand::CreateToken("}", consumeToken()));
2173 Parser.eatToEndOfStatement();
2177 // TODO: add parsing of broadcasts {1to8}, {1to16}
2178 // Parse "zeroing non-masked" semantic {z}
2179 if (getLexer().is(AsmToken::LCurly)) {
2180 Operands.push_back(X86Operand::CreateToken("{z}", consumeToken()));
2181 if (!getLexer().is(AsmToken::Identifier) || getLexer().getTok().getIdentifier() != "z") {
2182 SMLoc Loc = getLexer().getLoc();
2183 Parser.eatToEndOfStatement();
2184 return Error(Loc, "Expected z at this point");
2186 Parser.Lex(); // Eat the z
2187 if (!getLexer().is(AsmToken::RCurly)) {
2188 SMLoc Loc = getLexer().getLoc();
2189 Parser.eatToEndOfStatement();
2190 return Error(Loc, "Expected } at this point");
2192 Parser.Lex(); // Eat the }
2196 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2197 SMLoc Loc = getLexer().getLoc();
2198 Parser.eatToEndOfStatement();
2199 return Error(Loc, "unexpected token in argument list");
2203 if (getLexer().is(AsmToken::EndOfStatement))
2204 Parser.Lex(); // Consume the EndOfStatement
2205 else if (isPrefix && getLexer().is(AsmToken::Slash))
2206 Parser.Lex(); // Consume the prefix separator Slash
2208 if (ExtraImmOp && isParsingIntelSyntax())
2209 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
2211 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
2212 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
2213 // documented form in various unofficial manuals, so a lot of code uses it.
2214 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
2215 Operands.size() == 3) {
2216 X86Operand &Op = *(X86Operand*)Operands.back();
2217 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2218 isa<MCConstantExpr>(Op.Mem.Disp) &&
2219 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2220 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2221 SMLoc Loc = Op.getEndLoc();
2222 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2226 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
2227 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
2228 Operands.size() == 3) {
2229 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2230 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2231 isa<MCConstantExpr>(Op.Mem.Disp) &&
2232 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2233 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2234 SMLoc Loc = Op.getEndLoc();
2235 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2239 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
2240 if (Name.startswith("ins") && Operands.size() == 3 &&
2241 (Name == "insb" || Name == "insw" || Name == "insl")) {
2242 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2243 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2244 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
2245 Operands.pop_back();
2246 Operands.pop_back();
2252 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
2253 if (Name.startswith("outs") && Operands.size() == 3 &&
2254 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
2255 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2256 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2257 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
2258 Operands.pop_back();
2259 Operands.pop_back();
2265 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2266 if (Name.startswith("movs") && Operands.size() == 3 &&
2267 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2268 (is64BitMode() && Name == "movsq"))) {
2269 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2270 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2271 if (isSrcOp(Op) && isDstOp(Op2)) {
2272 Operands.pop_back();
2273 Operands.pop_back();
2278 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2279 if (Name.startswith("lods") && Operands.size() == 3 &&
2280 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2281 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2282 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2283 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2284 if (isSrcOp(*Op1) && Op2->isReg()) {
2286 unsigned reg = Op2->getReg();
2287 bool isLods = Name == "lods";
2288 if (reg == X86::AL && (isLods || Name == "lodsb"))
2290 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2292 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2294 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2299 Operands.pop_back();
2300 Operands.pop_back();
2304 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2308 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2309 if (Name.startswith("stos") && Operands.size() == 3 &&
2310 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2311 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2312 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2313 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2314 if (isDstOp(*Op2) && Op1->isReg()) {
2316 unsigned reg = Op1->getReg();
2317 bool isStos = Name == "stos";
2318 if (reg == X86::AL && (isStos || Name == "stosb"))
2320 else if (reg == X86::AX && (isStos || Name == "stosw"))
2322 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2324 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2329 Operands.pop_back();
2330 Operands.pop_back();
2334 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2339 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2341 if ((Name.startswith("shr") || Name.startswith("sar") ||
2342 Name.startswith("shl") || Name.startswith("sal") ||
2343 Name.startswith("rcl") || Name.startswith("rcr") ||
2344 Name.startswith("rol") || Name.startswith("ror")) &&
2345 Operands.size() == 3) {
2346 if (isParsingIntelSyntax()) {
2348 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2349 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2350 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2352 Operands.pop_back();
2355 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2356 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2357 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2359 Operands.erase(Operands.begin() + 1);
2364 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2365 // instalias with an immediate operand yet.
2366 if (Name == "int" && Operands.size() == 2) {
2367 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2368 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2369 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2371 Operands.erase(Operands.begin() + 1);
2372 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2379 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2382 TmpInst.setOpcode(Opcode);
2384 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2385 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2386 TmpInst.addOperand(Inst.getOperand(0));
2391 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2392 bool isCmp = false) {
2393 if (!Inst.getOperand(0).isImm() ||
2394 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2397 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2400 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2401 bool isCmp = false) {
2402 if (!Inst.getOperand(0).isImm() ||
2403 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2406 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2409 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2410 bool isCmp = false) {
2411 if (!Inst.getOperand(0).isImm() ||
2412 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2415 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2419 processInstruction(MCInst &Inst,
2420 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2421 switch (Inst.getOpcode()) {
2422 default: return false;
2423 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2424 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2425 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2426 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2427 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2428 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2429 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2430 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2431 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2432 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2433 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2434 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2435 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2436 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2437 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2438 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2439 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2440 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2441 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2442 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2443 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2444 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2445 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2446 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2447 case X86::VMOVAPDrr:
2448 case X86::VMOVAPDYrr:
2449 case X86::VMOVAPSrr:
2450 case X86::VMOVAPSYrr:
2451 case X86::VMOVDQArr:
2452 case X86::VMOVDQAYrr:
2453 case X86::VMOVDQUrr:
2454 case X86::VMOVDQUYrr:
2455 case X86::VMOVUPDrr:
2456 case X86::VMOVUPDYrr:
2457 case X86::VMOVUPSrr:
2458 case X86::VMOVUPSYrr: {
2459 if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) ||
2460 !X86II::isX86_64ExtendedReg(Inst.getOperand(1).getReg()))
2464 switch (Inst.getOpcode()) {
2465 default: llvm_unreachable("Invalid opcode");
2466 case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break;
2467 case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
2468 case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break;
2469 case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
2470 case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break;
2471 case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
2472 case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break;
2473 case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
2474 case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break;
2475 case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
2476 case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break;
2477 case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
2479 Inst.setOpcode(NewOpc);
2483 case X86::VMOVSSrr: {
2484 if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) ||
2485 !X86II::isX86_64ExtendedReg(Inst.getOperand(2).getReg()))
2488 switch (Inst.getOpcode()) {
2489 default: llvm_unreachable("Invalid opcode");
2490 case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
2491 case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
2493 Inst.setOpcode(NewOpc);
2499 static const char *getSubtargetFeatureName(unsigned Val);
2501 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2502 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2503 MCStreamer &Out, unsigned &ErrorInfo,
2504 bool MatchingInlineAsm) {
2505 assert(!Operands.empty() && "Unexpect empty operand list!");
2506 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2507 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2508 ArrayRef<SMRange> EmptyRanges = None;
2510 // First, handle aliases that expand to multiple instructions.
2511 // FIXME: This should be replaced with a real .td file alias mechanism.
2512 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2514 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2515 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2516 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2517 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2519 Inst.setOpcode(X86::WAIT);
2521 if (!MatchingInlineAsm)
2522 Out.EmitInstruction(Inst);
2525 StringSwitch<const char*>(Op->getToken())
2526 .Case("finit", "fninit")
2527 .Case("fsave", "fnsave")
2528 .Case("fstcw", "fnstcw")
2529 .Case("fstcww", "fnstcw")
2530 .Case("fstenv", "fnstenv")
2531 .Case("fstsw", "fnstsw")
2532 .Case("fstsww", "fnstsw")
2533 .Case("fclex", "fnclex")
2535 assert(Repl && "Unknown wait-prefixed instruction");
2537 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2540 bool WasOriginallyInvalidOperand = false;
2543 // First, try a direct match.
2544 switch (MatchInstructionImpl(Operands, Inst,
2545 ErrorInfo, MatchingInlineAsm,
2546 isParsingIntelSyntax())) {
2549 // Some instructions need post-processing to, for example, tweak which
2550 // encoding is selected. Loop on it while changes happen so the
2551 // individual transformations can chain off each other.
2552 if (!MatchingInlineAsm)
2553 while (processInstruction(Inst, Operands))
2557 if (!MatchingInlineAsm)
2558 Out.EmitInstruction(Inst);
2559 Opcode = Inst.getOpcode();
2561 case Match_MissingFeature: {
2562 assert(ErrorInfo && "Unknown missing feature!");
2563 // Special case the error message for the very common case where only
2564 // a single subtarget feature is missing.
2565 std::string Msg = "instruction requires:";
2567 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2568 if (ErrorInfo & Mask) {
2570 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2574 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2576 case Match_InvalidOperand:
2577 WasOriginallyInvalidOperand = true;
2579 case Match_MnemonicFail:
2583 // FIXME: Ideally, we would only attempt suffix matches for things which are
2584 // valid prefixes, and we could just infer the right unambiguous
2585 // type. However, that requires substantially more matcher support than the
2588 // Change the operand to point to a temporary token.
2589 StringRef Base = Op->getToken();
2590 SmallString<16> Tmp;
2593 Op->setTokenValue(Tmp.str());
2595 // If this instruction starts with an 'f', then it is a floating point stack
2596 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2597 // 80-bit floating point, which use the suffixes s,l,t respectively.
2599 // Otherwise, we assume that this may be an integer instruction, which comes
2600 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2601 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2603 // Check for the various suffix matches.
2604 Tmp[Base.size()] = Suffixes[0];
2605 unsigned ErrorInfoIgnore;
2606 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2607 unsigned Match1, Match2, Match3, Match4;
2609 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2610 MatchingInlineAsm, isParsingIntelSyntax());
2611 // If this returned as a missing feature failure, remember that.
2612 if (Match1 == Match_MissingFeature)
2613 ErrorInfoMissingFeature = ErrorInfoIgnore;
2614 Tmp[Base.size()] = Suffixes[1];
2615 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2616 MatchingInlineAsm, isParsingIntelSyntax());
2617 // If this returned as a missing feature failure, remember that.
2618 if (Match2 == Match_MissingFeature)
2619 ErrorInfoMissingFeature = ErrorInfoIgnore;
2620 Tmp[Base.size()] = Suffixes[2];
2621 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2622 MatchingInlineAsm, isParsingIntelSyntax());
2623 // If this returned as a missing feature failure, remember that.
2624 if (Match3 == Match_MissingFeature)
2625 ErrorInfoMissingFeature = ErrorInfoIgnore;
2626 Tmp[Base.size()] = Suffixes[3];
2627 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2628 MatchingInlineAsm, isParsingIntelSyntax());
2629 // If this returned as a missing feature failure, remember that.
2630 if (Match4 == Match_MissingFeature)
2631 ErrorInfoMissingFeature = ErrorInfoIgnore;
2633 // Restore the old token.
2634 Op->setTokenValue(Base);
2636 // If exactly one matched, then we treat that as a successful match (and the
2637 // instruction will already have been filled in correctly, since the failing
2638 // matches won't have modified it).
2639 unsigned NumSuccessfulMatches =
2640 (Match1 == Match_Success) + (Match2 == Match_Success) +
2641 (Match3 == Match_Success) + (Match4 == Match_Success);
2642 if (NumSuccessfulMatches == 1) {
2644 if (!MatchingInlineAsm)
2645 Out.EmitInstruction(Inst);
2646 Opcode = Inst.getOpcode();
2650 // Otherwise, the match failed, try to produce a decent error message.
2652 // If we had multiple suffix matches, then identify this as an ambiguous
2654 if (NumSuccessfulMatches > 1) {
2656 unsigned NumMatches = 0;
2657 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2658 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2659 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2660 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2662 SmallString<126> Msg;
2663 raw_svector_ostream OS(Msg);
2664 OS << "ambiguous instructions require an explicit suffix (could be ";
2665 for (unsigned i = 0; i != NumMatches; ++i) {
2668 if (i + 1 == NumMatches)
2670 OS << "'" << Base << MatchChars[i] << "'";
2673 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2677 // Okay, we know that none of the variants matched successfully.
2679 // If all of the instructions reported an invalid mnemonic, then the original
2680 // mnemonic was invalid.
2681 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2682 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2683 if (!WasOriginallyInvalidOperand) {
2684 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2686 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2687 Ranges, MatchingInlineAsm);
2690 // Recover location info for the operand if we know which was the problem.
2691 if (ErrorInfo != ~0U) {
2692 if (ErrorInfo >= Operands.size())
2693 return Error(IDLoc, "too few operands for instruction",
2694 EmptyRanges, MatchingInlineAsm);
2696 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2697 if (Operand->getStartLoc().isValid()) {
2698 SMRange OperandRange = Operand->getLocRange();
2699 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2700 OperandRange, MatchingInlineAsm);
2704 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2708 // If one instruction matched with a missing feature, report this as a
2710 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2711 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2712 std::string Msg = "instruction requires:";
2714 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2715 if (ErrorInfoMissingFeature & Mask) {
2717 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2721 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2724 // If one instruction matched with an invalid operand, report this as an
2726 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2727 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2728 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2733 // If all of these were an outright failure, report it in a useless way.
2734 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2735 EmptyRanges, MatchingInlineAsm);
2740 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2741 StringRef IDVal = DirectiveID.getIdentifier();
2742 if (IDVal == ".word")
2743 return ParseDirectiveWord(2, DirectiveID.getLoc());
2744 else if (IDVal.startswith(".code"))
2745 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2746 else if (IDVal.startswith(".att_syntax")) {
2747 getParser().setAssemblerDialect(0);
2749 } else if (IDVal.startswith(".intel_syntax")) {
2750 getParser().setAssemblerDialect(1);
2751 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2752 // FIXME: Handle noprefix
2753 if (Parser.getTok().getString() == "noprefix")
2761 /// ParseDirectiveWord
2762 /// ::= .word [ expression (, expression)* ]
2763 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2764 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2766 const MCExpr *Value;
2767 if (getParser().parseExpression(Value))
2770 getParser().getStreamer().EmitValue(Value, Size);
2772 if (getLexer().is(AsmToken::EndOfStatement))
2775 // FIXME: Improve diagnostic.
2776 if (getLexer().isNot(AsmToken::Comma)) {
2777 Error(L, "unexpected token in directive");
2788 /// ParseDirectiveCode
2789 /// ::= .code16 | .code32 | .code64
2790 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2791 if (IDVal == ".code16") {
2793 if (!is16BitMode()) {
2794 SwitchMode(X86::Mode16Bit);
2795 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
2797 } else if (IDVal == ".code32") {
2799 if (!is32BitMode()) {
2800 SwitchMode(X86::Mode32Bit);
2801 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2803 } else if (IDVal == ".code64") {
2805 if (!is64BitMode()) {
2806 SwitchMode(X86::Mode64Bit);
2807 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2810 Error(L, "unknown directive " + IDVal);
2817 // Force static initialization.
2818 extern "C" void LLVMInitializeX86AsmParser() {
2819 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2820 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2823 #define GET_REGISTER_MATCHER
2824 #define GET_MATCHER_IMPLEMENTATION
2825 #define GET_SUBTARGET_FEATURE_NAME
2826 #include "X86GenAsmMatcher.inc"