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[] = {
48 class X86AsmParser : public MCTargetAsmParser {
51 ParseInstructionInfo *InstInfo;
53 enum InfixCalculatorTok {
64 class InfixCalculator {
65 typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
66 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
67 SmallVector<ICToken, 4> PostfixStack;
70 int64_t popOperand() {
71 assert (!PostfixStack.empty() && "Poped an empty stack!");
72 ICToken Op = PostfixStack.pop_back_val();
73 assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
74 && "Expected and immediate or register!");
77 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
78 assert ((Op == IC_IMM || Op == IC_REGISTER) &&
79 "Unexpected operand!");
80 PostfixStack.push_back(std::make_pair(Op, Val));
83 void popOperator() { InfixOperatorStack.pop_back(); }
84 void pushOperator(InfixCalculatorTok Op) {
85 // Push the new operator if the stack is empty.
86 if (InfixOperatorStack.empty()) {
87 InfixOperatorStack.push_back(Op);
91 // Push the new operator if it has a higher precedence than the operator
92 // on the top of the stack or the operator on the top of the stack is a
94 unsigned Idx = InfixOperatorStack.size() - 1;
95 InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
96 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
97 InfixOperatorStack.push_back(Op);
101 // The operator on the top of the stack has higher precedence than the
103 unsigned ParenCount = 0;
105 // Nothing to process.
106 if (InfixOperatorStack.empty())
109 Idx = InfixOperatorStack.size() - 1;
110 StackOp = InfixOperatorStack[Idx];
111 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
114 // If we have an even parentheses count and we see a left parentheses,
115 // then stop processing.
116 if (!ParenCount && StackOp == IC_LPAREN)
119 if (StackOp == IC_RPAREN) {
121 InfixOperatorStack.pop_back();
122 } else if (StackOp == IC_LPAREN) {
124 InfixOperatorStack.pop_back();
126 InfixOperatorStack.pop_back();
127 PostfixStack.push_back(std::make_pair(StackOp, 0));
130 // Push the new operator.
131 InfixOperatorStack.push_back(Op);
134 // Push any remaining operators onto the postfix stack.
135 while (!InfixOperatorStack.empty()) {
136 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
137 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
138 PostfixStack.push_back(std::make_pair(StackOp, 0));
141 if (PostfixStack.empty())
144 SmallVector<ICToken, 16> OperandStack;
145 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
146 ICToken Op = PostfixStack[i];
147 if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
148 OperandStack.push_back(Op);
150 assert (OperandStack.size() > 1 && "Too few operands.");
152 ICToken Op2 = OperandStack.pop_back_val();
153 ICToken Op1 = OperandStack.pop_back_val();
156 report_fatal_error("Unexpected operator!");
159 Val = Op1.second + Op2.second;
160 OperandStack.push_back(std::make_pair(IC_IMM, Val));
163 Val = Op1.second - Op2.second;
164 OperandStack.push_back(std::make_pair(IC_IMM, Val));
167 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
168 "Multiply operation with an immediate and a register!");
169 Val = Op1.second * Op2.second;
170 OperandStack.push_back(std::make_pair(IC_IMM, Val));
173 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
174 "Divide operation with an immediate and a register!");
175 assert (Op2.second != 0 && "Division by zero!");
176 Val = Op1.second / Op2.second;
177 OperandStack.push_back(std::make_pair(IC_IMM, Val));
182 assert (OperandStack.size() == 1 && "Expected a single result.");
183 return OperandStack.pop_back_val().second;
187 enum IntelExprState {
202 class IntelExprStateMachine {
203 IntelExprState State, PrevState;
204 unsigned BaseReg, IndexReg, TmpReg, Scale;
208 bool StopOnLBrac, AddImmPrefix;
210 InlineAsmIdentifierInfo Info;
212 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
213 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
214 Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac),
215 AddImmPrefix(addimmprefix) { Info.clear(); }
217 unsigned getBaseReg() { return BaseReg; }
218 unsigned getIndexReg() { return IndexReg; }
219 unsigned getScale() { return Scale; }
220 const MCExpr *getSym() { return Sym; }
221 StringRef getSymName() { return SymName; }
222 int64_t getImm() { return Imm + IC.execute(); }
223 bool isValidEndState() {
224 return State == IES_RBRAC || State == IES_INTEGER;
226 bool getStopOnLBrac() { return StopOnLBrac; }
227 bool getAddImmPrefix() { return AddImmPrefix; }
228 bool hadError() { return State == IES_ERROR; }
230 InlineAsmIdentifierInfo &getIdentifierInfo() {
235 IntelExprState CurrState = State;
244 IC.pushOperator(IC_PLUS);
245 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
246 // If we already have a BaseReg, then assume this is the IndexReg with
251 assert (!IndexReg && "BaseReg/IndexReg already set!");
258 PrevState = CurrState;
261 IntelExprState CurrState = State;
276 // Only push the minus operator if it is not a unary operator.
277 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
278 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
279 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
280 IC.pushOperator(IC_MINUS);
281 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
282 // If we already have a BaseReg, then assume this is the IndexReg with
287 assert (!IndexReg && "BaseReg/IndexReg already set!");
294 PrevState = CurrState;
296 void onRegister(unsigned Reg) {
297 IntelExprState CurrState = State;
304 State = IES_REGISTER;
306 IC.pushOperand(IC_REGISTER);
309 // Index Register - Scale * Register
310 if (PrevState == IES_INTEGER) {
311 assert (!IndexReg && "IndexReg already set!");
312 State = IES_REGISTER;
314 // Get the scale and replace the 'Scale * Register' with '0'.
315 Scale = IC.popOperand();
316 IC.pushOperand(IC_IMM);
323 PrevState = CurrState;
325 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
335 SymName = SymRefName;
336 IC.pushOperand(IC_IMM);
340 void onInteger(int64_t TmpInt) {
341 IntelExprState CurrState = State;
352 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
353 // Index Register - Register * Scale
354 assert (!IndexReg && "IndexReg already set!");
357 // Get the scale and replace the 'Register * Scale' with '0'.
359 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
360 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
361 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
362 CurrState == IES_MINUS) {
363 // Unary minus. No need to pop the minus operand because it was never
365 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
367 IC.pushOperand(IC_IMM, TmpInt);
371 PrevState = CurrState;
382 State = IES_MULTIPLY;
383 IC.pushOperator(IC_MULTIPLY);
396 IC.pushOperator(IC_DIVIDE);
408 IC.pushOperator(IC_PLUS);
413 IntelExprState CurrState = State;
422 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
423 // If we already have a BaseReg, then assume this is the IndexReg with
428 assert (!IndexReg && "BaseReg/IndexReg already set!");
435 PrevState = CurrState;
438 IntelExprState CurrState = State;
448 // FIXME: We don't handle this type of unary minus, yet.
449 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
450 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
451 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
452 CurrState == IES_MINUS) {
457 IC.pushOperator(IC_LPAREN);
460 PrevState = CurrState;
472 IC.pushOperator(IC_RPAREN);
478 MCAsmParser &getParser() const { return Parser; }
480 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
482 bool Error(SMLoc L, const Twine &Msg,
483 ArrayRef<SMRange> Ranges = None,
484 bool MatchingInlineAsm = false) {
485 if (MatchingInlineAsm) return true;
486 return Parser.Error(L, Msg, Ranges);
489 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
494 X86Operand *ParseOperand();
495 X86Operand *ParseATTOperand();
496 X86Operand *ParseIntelOperand();
497 X86Operand *ParseIntelOffsetOfOperator();
498 X86Operand *ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
499 X86Operand *ParseIntelOperator(unsigned OpKind);
500 X86Operand *ParseIntelMemOperand(unsigned SegReg, int64_t ImmDisp,
502 X86Operand *ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
503 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
504 int64_t ImmDisp, unsigned Size);
505 X86Operand *ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
506 InlineAsmIdentifierInfo &Info,
507 bool IsUnevaluatedOperand, SMLoc &End);
509 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
511 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
512 unsigned BaseReg, unsigned IndexReg,
513 unsigned Scale, SMLoc Start, SMLoc End,
514 unsigned Size, StringRef Identifier,
515 InlineAsmIdentifierInfo &Info);
517 bool ParseDirectiveWord(unsigned Size, SMLoc L);
518 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
520 bool processInstruction(MCInst &Inst,
521 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
523 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
524 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
525 MCStreamer &Out, unsigned &ErrorInfo,
526 bool MatchingInlineAsm);
528 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
529 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
530 bool isSrcOp(X86Operand &Op);
532 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
533 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
534 bool isDstOp(X86Operand &Op);
536 bool is64BitMode() const {
537 // FIXME: Can tablegen auto-generate this?
538 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
541 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
542 setAvailableFeatures(FB);
545 bool isParsingIntelSyntax() {
546 return getParser().getAssemblerDialect();
549 /// @name Auto-generated Matcher Functions
552 #define GET_ASSEMBLER_HEADER
553 #include "X86GenAsmMatcher.inc"
558 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
559 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
561 // Initialize the set of available features.
562 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
564 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
566 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
568 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
570 virtual bool ParseDirective(AsmToken DirectiveID);
572 } // end anonymous namespace
574 /// @name Auto-generated Match Functions
577 static unsigned MatchRegisterName(StringRef Name);
581 static bool isImmSExti16i8Value(uint64_t Value) {
582 return (( Value <= 0x000000000000007FULL)||
583 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
584 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
587 static bool isImmSExti32i8Value(uint64_t Value) {
588 return (( Value <= 0x000000000000007FULL)||
589 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
590 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
593 static bool isImmZExtu32u8Value(uint64_t Value) {
594 return (Value <= 0x00000000000000FFULL);
597 static bool isImmSExti64i8Value(uint64_t Value) {
598 return (( Value <= 0x000000000000007FULL)||
599 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
602 static bool isImmSExti64i32Value(uint64_t Value) {
603 return (( Value <= 0x000000007FFFFFFFULL)||
604 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
608 /// X86Operand - Instances of this class represent a parsed X86 machine
610 struct X86Operand : public MCParsedAsmOperand {
618 SMLoc StartLoc, EndLoc;
653 X86Operand(KindTy K, SMLoc Start, SMLoc End)
654 : Kind(K), StartLoc(Start), EndLoc(End) {}
656 StringRef getSymName() { return SymName; }
657 void *getOpDecl() { return OpDecl; }
659 /// getStartLoc - Get the location of the first token of this operand.
660 SMLoc getStartLoc() const { return StartLoc; }
661 /// getEndLoc - Get the location of the last token of this operand.
662 SMLoc getEndLoc() const { return EndLoc; }
663 /// getLocRange - Get the range between the first and last token of this
665 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
666 /// getOffsetOfLoc - Get the location of the offset operator.
667 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
669 virtual void print(raw_ostream &OS) const {}
671 StringRef getToken() const {
672 assert(Kind == Token && "Invalid access!");
673 return StringRef(Tok.Data, Tok.Length);
675 void setTokenValue(StringRef Value) {
676 assert(Kind == Token && "Invalid access!");
677 Tok.Data = Value.data();
678 Tok.Length = Value.size();
681 unsigned getReg() const {
682 assert(Kind == Register && "Invalid access!");
686 const MCExpr *getImm() const {
687 assert(Kind == Immediate && "Invalid access!");
691 const MCExpr *getMemDisp() const {
692 assert(Kind == Memory && "Invalid access!");
695 unsigned getMemSegReg() const {
696 assert(Kind == Memory && "Invalid access!");
699 unsigned getMemBaseReg() const {
700 assert(Kind == Memory && "Invalid access!");
703 unsigned getMemIndexReg() const {
704 assert(Kind == Memory && "Invalid access!");
707 unsigned getMemScale() const {
708 assert(Kind == Memory && "Invalid access!");
712 bool isToken() const {return Kind == Token; }
714 bool isImm() const { return Kind == Immediate; }
716 bool isImmSExti16i8() const {
720 // If this isn't a constant expr, just assume it fits and let relaxation
722 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
726 // Otherwise, check the value is in a range that makes sense for this
728 return isImmSExti16i8Value(CE->getValue());
730 bool isImmSExti32i8() const {
734 // If this isn't a constant expr, just assume it fits and let relaxation
736 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
740 // Otherwise, check the value is in a range that makes sense for this
742 return isImmSExti32i8Value(CE->getValue());
744 bool isImmZExtu32u8() const {
748 // If this isn't a constant expr, just assume it fits and let relaxation
750 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
754 // Otherwise, check the value is in a range that makes sense for this
756 return isImmZExtu32u8Value(CE->getValue());
758 bool isImmSExti64i8() const {
762 // If this isn't a constant expr, just assume it fits and let relaxation
764 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
768 // Otherwise, check the value is in a range that makes sense for this
770 return isImmSExti64i8Value(CE->getValue());
772 bool isImmSExti64i32() const {
776 // If this isn't a constant expr, just assume it fits and let relaxation
778 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
782 // Otherwise, check the value is in a range that makes sense for this
784 return isImmSExti64i32Value(CE->getValue());
787 bool isOffsetOf() const {
788 return OffsetOfLoc.getPointer();
791 bool needAddressOf() const {
795 bool isMem() const { return Kind == Memory; }
796 bool isMem8() const {
797 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
799 bool isMem16() const {
800 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
802 bool isMem32() const {
803 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
805 bool isMem64() const {
806 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
808 bool isMem80() const {
809 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
811 bool isMem128() const {
812 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
814 bool isMem256() const {
815 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
817 bool isMem512() const {
818 return Kind == Memory && (!Mem.Size || Mem.Size == 512);
821 bool isMemVX32() const {
822 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
823 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
825 bool isMemVY32() const {
826 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
827 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
829 bool isMemVX64() const {
830 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
831 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
833 bool isMemVY64() const {
834 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
835 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
837 bool isMemVZ32() const {
838 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
839 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
841 bool isMemVZ64() const {
842 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
843 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
846 bool isAbsMem() const {
847 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
848 !getMemIndexReg() && getMemScale() == 1;
851 bool isMemOffs8() const {
852 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
853 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 8);
855 bool isMemOffs16() const {
856 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
857 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 16);
859 bool isMemOffs32() const {
860 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
861 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 32);
863 bool isMemOffs64() const {
864 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
865 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 64);
868 bool isReg() const { return Kind == Register; }
870 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
871 // Add as immediates when possible.
872 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
873 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
875 Inst.addOperand(MCOperand::CreateExpr(Expr));
878 void addRegOperands(MCInst &Inst, unsigned N) const {
879 assert(N == 1 && "Invalid number of operands!");
880 Inst.addOperand(MCOperand::CreateReg(getReg()));
883 void addImmOperands(MCInst &Inst, unsigned N) const {
884 assert(N == 1 && "Invalid number of operands!");
885 addExpr(Inst, getImm());
888 void addMem8Operands(MCInst &Inst, unsigned N) const {
889 addMemOperands(Inst, N);
891 void addMem16Operands(MCInst &Inst, unsigned N) const {
892 addMemOperands(Inst, N);
894 void addMem32Operands(MCInst &Inst, unsigned N) const {
895 addMemOperands(Inst, N);
897 void addMem64Operands(MCInst &Inst, unsigned N) const {
898 addMemOperands(Inst, N);
900 void addMem80Operands(MCInst &Inst, unsigned N) const {
901 addMemOperands(Inst, N);
903 void addMem128Operands(MCInst &Inst, unsigned N) const {
904 addMemOperands(Inst, N);
906 void addMem256Operands(MCInst &Inst, unsigned N) const {
907 addMemOperands(Inst, N);
909 void addMem512Operands(MCInst &Inst, unsigned N) const {
910 addMemOperands(Inst, N);
912 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
913 addMemOperands(Inst, N);
915 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
916 addMemOperands(Inst, N);
918 void addMemVZ32Operands(MCInst &Inst, unsigned N) const {
919 addMemOperands(Inst, N);
921 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
922 addMemOperands(Inst, N);
924 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
925 addMemOperands(Inst, N);
927 void addMemVZ64Operands(MCInst &Inst, unsigned N) const {
928 addMemOperands(Inst, N);
931 void addMemOperands(MCInst &Inst, unsigned N) const {
932 assert((N == 5) && "Invalid number of operands!");
933 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
934 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
935 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
936 addExpr(Inst, getMemDisp());
937 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
940 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
941 assert((N == 1) && "Invalid number of operands!");
942 // Add as immediates when possible.
943 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
944 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
946 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
949 void addMemOffs8Operands(MCInst &Inst, unsigned N) const {
950 addMemOffsOperands(Inst, N);
952 void addMemOffs16Operands(MCInst &Inst, unsigned N) const {
953 addMemOffsOperands(Inst, N);
955 void addMemOffs32Operands(MCInst &Inst, unsigned N) const {
956 addMemOffsOperands(Inst, N);
958 void addMemOffs64Operands(MCInst &Inst, unsigned N) const {
959 addMemOffsOperands(Inst, N);
962 void addMemOffsOperands(MCInst &Inst, unsigned N) const {
963 assert((N == 1) && "Invalid number of operands!");
964 // Add as immediates when possible.
965 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
966 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
968 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
971 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
972 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
973 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
974 Res->Tok.Data = Str.data();
975 Res->Tok.Length = Str.size();
979 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
980 bool AddressOf = false,
981 SMLoc OffsetOfLoc = SMLoc(),
982 StringRef SymName = StringRef(),
984 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
985 Res->Reg.RegNo = RegNo;
986 Res->AddressOf = AddressOf;
987 Res->OffsetOfLoc = OffsetOfLoc;
988 Res->SymName = SymName;
989 Res->OpDecl = OpDecl;
993 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
994 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
999 /// Create an absolute memory operand.
1000 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
1001 unsigned Size = 0, StringRef SymName = StringRef(),
1003 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1004 Res->Mem.SegReg = 0;
1005 Res->Mem.Disp = Disp;
1006 Res->Mem.BaseReg = 0;
1007 Res->Mem.IndexReg = 0;
1009 Res->Mem.Size = Size;
1010 Res->SymName = SymName;
1011 Res->OpDecl = OpDecl;
1012 Res->AddressOf = false;
1016 /// Create a generalized memory operand.
1017 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
1018 unsigned BaseReg, unsigned IndexReg,
1019 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
1021 StringRef SymName = StringRef(),
1023 // We should never just have a displacement, that should be parsed as an
1024 // absolute memory operand.
1025 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
1027 // The scale should always be one of {1,2,4,8}.
1028 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
1030 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1031 Res->Mem.SegReg = SegReg;
1032 Res->Mem.Disp = Disp;
1033 Res->Mem.BaseReg = BaseReg;
1034 Res->Mem.IndexReg = IndexReg;
1035 Res->Mem.Scale = Scale;
1036 Res->Mem.Size = Size;
1037 Res->SymName = SymName;
1038 Res->OpDecl = OpDecl;
1039 Res->AddressOf = false;
1044 } // end anonymous namespace.
1046 bool X86AsmParser::isSrcOp(X86Operand &Op) {
1047 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
1049 return (Op.isMem() &&
1050 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
1051 isa<MCConstantExpr>(Op.Mem.Disp) &&
1052 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1053 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
1056 bool X86AsmParser::isDstOp(X86Operand &Op) {
1057 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
1059 return Op.isMem() &&
1060 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
1061 isa<MCConstantExpr>(Op.Mem.Disp) &&
1062 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1063 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
1066 bool X86AsmParser::ParseRegister(unsigned &RegNo,
1067 SMLoc &StartLoc, SMLoc &EndLoc) {
1069 const AsmToken &PercentTok = Parser.getTok();
1070 StartLoc = PercentTok.getLoc();
1072 // If we encounter a %, ignore it. This code handles registers with and
1073 // without the prefix, unprefixed registers can occur in cfi directives.
1074 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1075 Parser.Lex(); // Eat percent token.
1077 const AsmToken &Tok = Parser.getTok();
1078 EndLoc = Tok.getEndLoc();
1080 if (Tok.isNot(AsmToken::Identifier)) {
1081 if (isParsingIntelSyntax()) return true;
1082 return Error(StartLoc, "invalid register name",
1083 SMRange(StartLoc, EndLoc));
1086 RegNo = MatchRegisterName(Tok.getString());
1088 // If the match failed, try the register name as lowercase.
1090 RegNo = MatchRegisterName(Tok.getString().lower());
1092 if (!is64BitMode()) {
1093 // FIXME: This should be done using Requires<In32BitMode> and
1094 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1096 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1098 if (RegNo == X86::RIZ ||
1099 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1100 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1101 X86II::isX86_64ExtendedReg(RegNo))
1102 return Error(StartLoc, "register %"
1103 + Tok.getString() + " is only available in 64-bit mode",
1104 SMRange(StartLoc, EndLoc));
1107 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1108 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1110 Parser.Lex(); // Eat 'st'
1112 // Check to see if we have '(4)' after %st.
1113 if (getLexer().isNot(AsmToken::LParen))
1118 const AsmToken &IntTok = Parser.getTok();
1119 if (IntTok.isNot(AsmToken::Integer))
1120 return Error(IntTok.getLoc(), "expected stack index");
1121 switch (IntTok.getIntVal()) {
1122 case 0: RegNo = X86::ST0; break;
1123 case 1: RegNo = X86::ST1; break;
1124 case 2: RegNo = X86::ST2; break;
1125 case 3: RegNo = X86::ST3; break;
1126 case 4: RegNo = X86::ST4; break;
1127 case 5: RegNo = X86::ST5; break;
1128 case 6: RegNo = X86::ST6; break;
1129 case 7: RegNo = X86::ST7; break;
1130 default: return Error(IntTok.getLoc(), "invalid stack index");
1133 if (getParser().Lex().isNot(AsmToken::RParen))
1134 return Error(Parser.getTok().getLoc(), "expected ')'");
1136 EndLoc = Parser.getTok().getEndLoc();
1137 Parser.Lex(); // Eat ')'
1141 EndLoc = Parser.getTok().getEndLoc();
1143 // If this is "db[0-7]", match it as an alias
1145 if (RegNo == 0 && Tok.getString().size() == 3 &&
1146 Tok.getString().startswith("db")) {
1147 switch (Tok.getString()[2]) {
1148 case '0': RegNo = X86::DR0; break;
1149 case '1': RegNo = X86::DR1; break;
1150 case '2': RegNo = X86::DR2; break;
1151 case '3': RegNo = X86::DR3; break;
1152 case '4': RegNo = X86::DR4; break;
1153 case '5': RegNo = X86::DR5; break;
1154 case '6': RegNo = X86::DR6; break;
1155 case '7': RegNo = X86::DR7; break;
1159 EndLoc = Parser.getTok().getEndLoc();
1160 Parser.Lex(); // Eat it.
1166 if (isParsingIntelSyntax()) return true;
1167 return Error(StartLoc, "invalid register name",
1168 SMRange(StartLoc, EndLoc));
1171 Parser.Lex(); // Eat identifier token.
1175 X86Operand *X86AsmParser::ParseOperand() {
1176 if (isParsingIntelSyntax())
1177 return ParseIntelOperand();
1178 return ParseATTOperand();
1181 /// getIntelMemOperandSize - Return intel memory operand size.
1182 static unsigned getIntelMemOperandSize(StringRef OpStr) {
1183 unsigned Size = StringSwitch<unsigned>(OpStr)
1184 .Cases("BYTE", "byte", 8)
1185 .Cases("WORD", "word", 16)
1186 .Cases("DWORD", "dword", 32)
1187 .Cases("QWORD", "qword", 64)
1188 .Cases("XWORD", "xword", 80)
1189 .Cases("XMMWORD", "xmmword", 128)
1190 .Cases("YMMWORD", "ymmword", 256)
1196 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1197 unsigned BaseReg, unsigned IndexReg,
1198 unsigned Scale, SMLoc Start, SMLoc End,
1199 unsigned Size, StringRef Identifier,
1200 InlineAsmIdentifierInfo &Info){
1201 if (isa<MCSymbolRefExpr>(Disp)) {
1202 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1203 // reference. We need an 'r' constraint here, so we need to create register
1204 // operand to ensure proper matching. Just pick a GPR based on the size of
1206 if (!Info.IsVarDecl) {
1207 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1208 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1209 SMLoc(), Identifier, Info.OpDecl);
1212 Size = Info.Type * 8; // Size is in terms of bits in this context.
1214 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1219 // When parsing inline assembly we set the base register to a non-zero value
1220 // if we don't know the actual value at this time. This is necessary to
1221 // get the matching correct in some cases.
1222 BaseReg = BaseReg ? BaseReg : 1;
1223 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1224 End, Size, Identifier, Info.OpDecl);
1228 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1229 StringRef SymName, int64_t ImmDisp,
1230 int64_t FinalImmDisp, SMLoc &BracLoc,
1231 SMLoc &StartInBrac, SMLoc &End) {
1232 // Remove the '[' and ']' from the IR string.
1233 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1234 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1236 // If ImmDisp is non-zero, then we parsed a displacement before the
1237 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1238 // If ImmDisp doesn't match the displacement computed by the state machine
1239 // then we have an additional displacement in the bracketed expression.
1240 if (ImmDisp != FinalImmDisp) {
1242 // We have an immediate displacement before the bracketed expression.
1243 // Adjust this to match the final immediate displacement.
1245 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1246 E = AsmRewrites->end(); I != E; ++I) {
1247 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1249 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1250 assert (!Found && "ImmDisp already rewritten.");
1251 (*I).Kind = AOK_Imm;
1252 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1253 (*I).Val = FinalImmDisp;
1258 assert (Found && "Unable to rewrite ImmDisp.");
1261 // We have a symbolic and an immediate displacement, but no displacement
1262 // before the bracketed expression. Put the immediate displacement
1263 // before the bracketed expression.
1264 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1267 // Remove all the ImmPrefix rewrites within the brackets.
1268 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1269 E = AsmRewrites->end(); I != E; ++I) {
1270 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1272 if ((*I).Kind == AOK_ImmPrefix)
1273 (*I).Kind = AOK_Delete;
1275 const char *SymLocPtr = SymName.data();
1276 // Skip everything before the symbol.
1277 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1278 assert(Len > 0 && "Expected a non-negative length.");
1279 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1281 // Skip everything after the symbol.
1282 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1283 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1284 assert(Len > 0 && "Expected a non-negative length.");
1285 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1290 X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1291 const AsmToken &Tok = Parser.getTok();
1295 bool UpdateLocLex = true;
1297 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1298 // identifier. Don't try an parse it as a register.
1299 if (Tok.getString().startswith("."))
1302 // If we're parsing an immediate expression, we don't expect a '['.
1303 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1306 switch (getLexer().getKind()) {
1308 if (SM.isValidEndState()) {
1312 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1314 case AsmToken::EndOfStatement: {
1318 case AsmToken::Identifier: {
1319 // This could be a register or a symbolic displacement.
1322 SMLoc IdentLoc = Tok.getLoc();
1323 StringRef Identifier = Tok.getString();
1324 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1325 SM.onRegister(TmpReg);
1326 UpdateLocLex = false;
1329 if (!isParsingInlineAsm()) {
1330 if (getParser().parsePrimaryExpr(Val, End))
1331 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1333 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1334 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1335 /*Unevaluated*/ false, End))
1338 SM.onIdentifierExpr(Val, Identifier);
1339 UpdateLocLex = false;
1342 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1344 case AsmToken::Integer:
1345 if (isParsingInlineAsm() && SM.getAddImmPrefix())
1346 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1348 SM.onInteger(Tok.getIntVal());
1350 case AsmToken::Plus: SM.onPlus(); break;
1351 case AsmToken::Minus: SM.onMinus(); break;
1352 case AsmToken::Star: SM.onStar(); break;
1353 case AsmToken::Slash: SM.onDivide(); break;
1354 case AsmToken::LBrac: SM.onLBrac(); break;
1355 case AsmToken::RBrac: SM.onRBrac(); break;
1356 case AsmToken::LParen: SM.onLParen(); break;
1357 case AsmToken::RParen: SM.onRParen(); break;
1360 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1362 if (!Done && UpdateLocLex) {
1364 Parser.Lex(); // Consume the token.
1370 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1373 const AsmToken &Tok = Parser.getTok();
1374 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1375 if (getLexer().isNot(AsmToken::LBrac))
1376 return ErrorOperand(BracLoc, "Expected '[' token!");
1377 Parser.Lex(); // Eat '['
1379 SMLoc StartInBrac = Tok.getLoc();
1380 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1381 // may have already parsed an immediate displacement before the bracketed
1383 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1384 if (X86Operand *Err = ParseIntelExpression(SM, End))
1388 if (const MCExpr *Sym = SM.getSym()) {
1389 // A symbolic displacement.
1391 if (isParsingInlineAsm())
1392 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1393 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1396 // An immediate displacement only.
1397 Disp = MCConstantExpr::Create(SM.getImm(), getContext());
1400 // Parse the dot operator (e.g., [ebx].foo.bar).
1401 if (Tok.getString().startswith(".")) {
1402 const MCExpr *NewDisp;
1403 if (X86Operand *Err = ParseIntelDotOperator(Disp, NewDisp))
1406 End = Tok.getEndLoc();
1407 Parser.Lex(); // Eat the field.
1411 int BaseReg = SM.getBaseReg();
1412 int IndexReg = SM.getIndexReg();
1413 int Scale = SM.getScale();
1414 if (!isParsingInlineAsm()) {
1416 if (!BaseReg && !IndexReg) {
1418 return X86Operand::CreateMem(Disp, Start, End, Size);
1420 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1422 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1426 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1427 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1428 End, Size, SM.getSymName(), Info);
1431 // Inline assembly may use variable names with namespace alias qualifiers.
1432 X86Operand *X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1433 StringRef &Identifier,
1434 InlineAsmIdentifierInfo &Info,
1435 bool IsUnevaluatedOperand,
1437 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1440 StringRef LineBuf(Identifier.data());
1441 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
1443 const AsmToken &Tok = Parser.getTok();
1445 // Advance the token stream until the end of the current token is
1446 // after the end of what the frontend claimed.
1447 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
1449 End = Tok.getEndLoc();
1452 assert(End.getPointer() <= EndPtr && "frontend claimed part of a token?");
1453 if (End.getPointer() == EndPtr) break;
1456 // Create the symbol reference.
1457 Identifier = LineBuf;
1458 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1459 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1460 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1464 /// ParseIntelMemOperand - Parse intel style memory operand.
1465 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg,
1468 const AsmToken &Tok = Parser.getTok();
1471 unsigned Size = getIntelMemOperandSize(Tok.getString());
1473 Parser.Lex(); // Eat operand size (e.g., byte, word).
1474 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1475 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1476 Parser.Lex(); // Eat ptr.
1479 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1480 if (getLexer().is(AsmToken::Integer)) {
1481 if (isParsingInlineAsm())
1482 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1484 int64_t ImmDisp = Tok.getIntVal();
1485 Parser.Lex(); // Eat the integer.
1486 if (getLexer().isNot(AsmToken::LBrac))
1487 return ErrorOperand(Start, "Expected '[' token!");
1488 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1491 if (getLexer().is(AsmToken::LBrac))
1492 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1494 if (!ParseRegister(SegReg, Start, End)) {
1495 // Handel SegReg : [ ... ]
1496 if (getLexer().isNot(AsmToken::Colon))
1497 return ErrorOperand(Start, "Expected ':' token!");
1498 Parser.Lex(); // Eat :
1499 if (getLexer().isNot(AsmToken::LBrac))
1500 return ErrorOperand(Start, "Expected '[' token!");
1501 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1505 if (!isParsingInlineAsm()) {
1506 if (getParser().parsePrimaryExpr(Val, End))
1507 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1509 return X86Operand::CreateMem(Val, Start, End, Size);
1512 InlineAsmIdentifierInfo Info;
1513 StringRef Identifier = Tok.getString();
1514 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1515 /*Unevaluated*/ false, End))
1517 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1518 /*Scale=*/1, Start, End, Size, Identifier, Info);
1521 /// Parse the '.' operator.
1522 X86Operand *X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1523 const MCExpr *&NewDisp) {
1524 const AsmToken &Tok = Parser.getTok();
1525 int64_t OrigDispVal, DotDispVal;
1527 // FIXME: Handle non-constant expressions.
1528 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1529 OrigDispVal = OrigDisp->getValue();
1531 return ErrorOperand(Tok.getLoc(), "Non-constant offsets are not supported!");
1534 StringRef DotDispStr = Tok.getString().drop_front(1);
1536 // .Imm gets lexed as a real.
1537 if (Tok.is(AsmToken::Real)) {
1539 DotDispStr.getAsInteger(10, DotDisp);
1540 DotDispVal = DotDisp.getZExtValue();
1541 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1543 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1544 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1546 return ErrorOperand(Tok.getLoc(), "Unable to lookup field reference!");
1547 DotDispVal = DotDisp;
1549 return ErrorOperand(Tok.getLoc(), "Unexpected token type!");
1551 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1552 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1553 unsigned Len = DotDispStr.size();
1554 unsigned Val = OrigDispVal + DotDispVal;
1555 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1559 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1563 /// Parse the 'offset' operator. This operator is used to specify the
1564 /// location rather then the content of a variable.
1565 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1566 const AsmToken &Tok = Parser.getTok();
1567 SMLoc OffsetOfLoc = Tok.getLoc();
1568 Parser.Lex(); // Eat offset.
1571 InlineAsmIdentifierInfo Info;
1572 SMLoc Start = Tok.getLoc(), End;
1573 StringRef Identifier = Tok.getString();
1574 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1575 /*Unevaluated*/ false, End))
1578 // Don't emit the offset operator.
1579 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1581 // The offset operator will have an 'r' constraint, thus we need to create
1582 // register operand to ensure proper matching. Just pick a GPR based on
1583 // the size of a pointer.
1584 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1585 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1586 OffsetOfLoc, Identifier, Info.OpDecl);
1589 enum IntelOperatorKind {
1595 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1596 /// returns the number of elements in an array. It returns the value 1 for
1597 /// non-array variables. The SIZE operator returns the size of a C or C++
1598 /// variable. A variable's size is the product of its LENGTH and TYPE. The
1599 /// TYPE operator returns the size of a C or C++ type or variable. If the
1600 /// variable is an array, TYPE returns the size of a single element.
1601 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1602 const AsmToken &Tok = Parser.getTok();
1603 SMLoc TypeLoc = Tok.getLoc();
1604 Parser.Lex(); // Eat operator.
1606 const MCExpr *Val = 0;
1607 InlineAsmIdentifierInfo Info;
1608 SMLoc Start = Tok.getLoc(), End;
1609 StringRef Identifier = Tok.getString();
1610 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1611 /*Unevaluated*/ true, End))
1616 default: llvm_unreachable("Unexpected operand kind!");
1617 case IOK_LENGTH: CVal = Info.Length; break;
1618 case IOK_SIZE: CVal = Info.Size; break;
1619 case IOK_TYPE: CVal = Info.Type; break;
1622 // Rewrite the type operator and the C or C++ type or variable in terms of an
1623 // immediate. E.g. TYPE foo -> $$4
1624 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1625 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1627 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1628 return X86Operand::CreateImm(Imm, Start, End);
1631 X86Operand *X86AsmParser::ParseIntelOperand() {
1632 const AsmToken &Tok = Parser.getTok();
1633 SMLoc Start = Tok.getLoc(), End;
1635 // Offset, length, type and size operators.
1636 if (isParsingInlineAsm()) {
1637 StringRef AsmTokStr = Tok.getString();
1638 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1639 return ParseIntelOffsetOfOperator();
1640 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1641 return ParseIntelOperator(IOK_LENGTH);
1642 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1643 return ParseIntelOperator(IOK_SIZE);
1644 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1645 return ParseIntelOperator(IOK_TYPE);
1649 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1650 getLexer().is(AsmToken::LParen)) {
1651 AsmToken StartTok = Tok;
1652 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1653 /*AddImmPrefix=*/false);
1654 if (X86Operand *Err = ParseIntelExpression(SM, End))
1657 int64_t Imm = SM.getImm();
1658 if (isParsingInlineAsm()) {
1659 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1660 if (StartTok.getString().size() == Len)
1661 // Just add a prefix if this wasn't a complex immediate expression.
1662 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1664 // Otherwise, rewrite the complex expression as a single immediate.
1665 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1668 if (getLexer().isNot(AsmToken::LBrac)) {
1669 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1670 return X86Operand::CreateImm(ImmExpr, Start, End);
1673 // Only positive immediates are valid.
1675 return ErrorOperand(Start, "expected a positive immediate displacement "
1676 "before bracketed expr.");
1678 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1679 return ParseIntelMemOperand(/*SegReg=*/0, Imm, Start);
1684 if (!ParseRegister(RegNo, Start, End)) {
1685 // If this is a segment register followed by a ':', then this is the start
1686 // of a memory reference, otherwise this is a normal register reference.
1687 if (getLexer().isNot(AsmToken::Colon))
1688 return X86Operand::CreateReg(RegNo, Start, End);
1690 getParser().Lex(); // Eat the colon.
1691 return ParseIntelMemOperand(/*SegReg=*/RegNo, /*Disp=*/0, Start);
1695 return ParseIntelMemOperand(/*SegReg=*/0, /*Disp=*/0, Start);
1698 X86Operand *X86AsmParser::ParseATTOperand() {
1699 switch (getLexer().getKind()) {
1701 // Parse a memory operand with no segment register.
1702 return ParseMemOperand(0, Parser.getTok().getLoc());
1703 case AsmToken::Percent: {
1704 // Read the register.
1707 if (ParseRegister(RegNo, Start, End)) return 0;
1708 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1709 Error(Start, "%eiz and %riz can only be used as index registers",
1710 SMRange(Start, End));
1714 // If this is a segment register followed by a ':', then this is the start
1715 // of a memory reference, otherwise this is a normal register reference.
1716 if (getLexer().isNot(AsmToken::Colon))
1717 return X86Operand::CreateReg(RegNo, Start, End);
1719 getParser().Lex(); // Eat the colon.
1720 return ParseMemOperand(RegNo, Start);
1722 case AsmToken::Dollar: {
1723 // $42 -> immediate.
1724 SMLoc Start = Parser.getTok().getLoc(), End;
1727 if (getParser().parseExpression(Val, End))
1729 return X86Operand::CreateImm(Val, Start, End);
1734 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1735 /// has already been parsed if present.
1736 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1738 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1739 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1740 // only way to do this without lookahead is to eat the '(' and see what is
1742 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1743 if (getLexer().isNot(AsmToken::LParen)) {
1745 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1747 // After parsing the base expression we could either have a parenthesized
1748 // memory address or not. If not, return now. If so, eat the (.
1749 if (getLexer().isNot(AsmToken::LParen)) {
1750 // Unless we have a segment register, treat this as an immediate.
1752 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1753 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1759 // Okay, we have a '('. We don't know if this is an expression or not, but
1760 // so we have to eat the ( to see beyond it.
1761 SMLoc LParenLoc = Parser.getTok().getLoc();
1762 Parser.Lex(); // Eat the '('.
1764 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1765 // Nothing to do here, fall into the code below with the '(' part of the
1766 // memory operand consumed.
1770 // It must be an parenthesized expression, parse it now.
1771 if (getParser().parseParenExpression(Disp, ExprEnd))
1774 // After parsing the base expression we could either have a parenthesized
1775 // memory address or not. If not, return now. If so, eat the (.
1776 if (getLexer().isNot(AsmToken::LParen)) {
1777 // Unless we have a segment register, treat this as an immediate.
1779 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1780 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1788 // If we reached here, then we just ate the ( of the memory operand. Process
1789 // the rest of the memory operand.
1790 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1793 if (getLexer().is(AsmToken::Percent)) {
1794 SMLoc StartLoc, EndLoc;
1795 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1796 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1797 Error(StartLoc, "eiz and riz can only be used as index registers",
1798 SMRange(StartLoc, EndLoc));
1803 if (getLexer().is(AsmToken::Comma)) {
1804 Parser.Lex(); // Eat the comma.
1805 IndexLoc = Parser.getTok().getLoc();
1807 // Following the comma we should have either an index register, or a scale
1808 // value. We don't support the later form, but we want to parse it
1811 // Not that even though it would be completely consistent to support syntax
1812 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1813 if (getLexer().is(AsmToken::Percent)) {
1815 if (ParseRegister(IndexReg, L, L)) return 0;
1817 if (getLexer().isNot(AsmToken::RParen)) {
1818 // Parse the scale amount:
1819 // ::= ',' [scale-expression]
1820 if (getLexer().isNot(AsmToken::Comma)) {
1821 Error(Parser.getTok().getLoc(),
1822 "expected comma in scale expression");
1825 Parser.Lex(); // Eat the comma.
1827 if (getLexer().isNot(AsmToken::RParen)) {
1828 SMLoc Loc = Parser.getTok().getLoc();
1831 if (getParser().parseAbsoluteExpression(ScaleVal)){
1832 Error(Loc, "expected scale expression");
1836 // Validate the scale amount.
1837 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1838 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1841 Scale = (unsigned)ScaleVal;
1844 } else if (getLexer().isNot(AsmToken::RParen)) {
1845 // A scale amount without an index is ignored.
1847 SMLoc Loc = Parser.getTok().getLoc();
1850 if (getParser().parseAbsoluteExpression(Value))
1854 Warning(Loc, "scale factor without index register is ignored");
1859 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1860 if (getLexer().isNot(AsmToken::RParen)) {
1861 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1864 SMLoc MemEnd = Parser.getTok().getEndLoc();
1865 Parser.Lex(); // Eat the ')'.
1867 // If we have both a base register and an index register make sure they are
1868 // both 64-bit or 32-bit registers.
1869 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1870 if (BaseReg != 0 && IndexReg != 0) {
1871 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1872 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1873 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1874 IndexReg != X86::RIZ) {
1875 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1878 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1879 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1880 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1881 IndexReg != X86::EIZ){
1882 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1887 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1892 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1893 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1895 StringRef PatchedName = Name;
1897 // FIXME: Hack to recognize setneb as setne.
1898 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1899 PatchedName != "setb" && PatchedName != "setnb")
1900 PatchedName = PatchedName.substr(0, Name.size()-1);
1902 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1903 const MCExpr *ExtraImmOp = 0;
1904 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1905 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1906 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1907 bool IsVCMP = PatchedName[0] == 'v';
1908 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1909 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1910 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1914 .Case("unord", 0x03)
1919 /* AVX only from here */
1920 .Case("eq_uq", 0x08)
1923 .Case("false", 0x0B)
1924 .Case("neq_oq", 0x0C)
1928 .Case("eq_os", 0x10)
1929 .Case("lt_oq", 0x11)
1930 .Case("le_oq", 0x12)
1931 .Case("unord_s", 0x13)
1932 .Case("neq_us", 0x14)
1933 .Case("nlt_uq", 0x15)
1934 .Case("nle_uq", 0x16)
1935 .Case("ord_s", 0x17)
1936 .Case("eq_us", 0x18)
1937 .Case("nge_uq", 0x19)
1938 .Case("ngt_uq", 0x1A)
1939 .Case("false_os", 0x1B)
1940 .Case("neq_os", 0x1C)
1941 .Case("ge_oq", 0x1D)
1942 .Case("gt_oq", 0x1E)
1943 .Case("true_us", 0x1F)
1945 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1946 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1947 getParser().getContext());
1948 if (PatchedName.endswith("ss")) {
1949 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1950 } else if (PatchedName.endswith("sd")) {
1951 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1952 } else if (PatchedName.endswith("ps")) {
1953 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1955 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1956 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1961 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1963 if (ExtraImmOp && !isParsingIntelSyntax())
1964 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1966 // Determine whether this is an instruction prefix.
1968 Name == "lock" || Name == "rep" ||
1969 Name == "repe" || Name == "repz" ||
1970 Name == "repne" || Name == "repnz" ||
1971 Name == "rex64" || Name == "data16";
1974 // This does the actual operand parsing. Don't parse any more if we have a
1975 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1976 // just want to parse the "lock" as the first instruction and the "incl" as
1978 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1980 // Parse '*' modifier.
1981 if (getLexer().is(AsmToken::Star)) {
1982 SMLoc Loc = Parser.getTok().getLoc();
1983 Operands.push_back(X86Operand::CreateToken("*", Loc));
1984 Parser.Lex(); // Eat the star.
1987 // Read the first operand.
1988 if (X86Operand *Op = ParseOperand())
1989 Operands.push_back(Op);
1991 Parser.eatToEndOfStatement();
1995 while (getLexer().is(AsmToken::Comma)) {
1996 Parser.Lex(); // Eat the comma.
1998 // Parse and remember the operand.
1999 if (X86Operand *Op = ParseOperand())
2000 Operands.push_back(Op);
2002 Parser.eatToEndOfStatement();
2007 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2008 SMLoc Loc = getLexer().getLoc();
2009 Parser.eatToEndOfStatement();
2010 return Error(Loc, "unexpected token in argument list");
2014 if (getLexer().is(AsmToken::EndOfStatement))
2015 Parser.Lex(); // Consume the EndOfStatement
2016 else if (isPrefix && getLexer().is(AsmToken::Slash))
2017 Parser.Lex(); // Consume the prefix separator Slash
2019 if (ExtraImmOp && isParsingIntelSyntax())
2020 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
2022 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
2023 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
2024 // documented form in various unofficial manuals, so a lot of code uses it.
2025 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
2026 Operands.size() == 3) {
2027 X86Operand &Op = *(X86Operand*)Operands.back();
2028 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2029 isa<MCConstantExpr>(Op.Mem.Disp) &&
2030 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2031 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2032 SMLoc Loc = Op.getEndLoc();
2033 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2037 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
2038 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
2039 Operands.size() == 3) {
2040 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2041 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2042 isa<MCConstantExpr>(Op.Mem.Disp) &&
2043 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2044 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2045 SMLoc Loc = Op.getEndLoc();
2046 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2050 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
2051 if (Name.startswith("ins") && Operands.size() == 3 &&
2052 (Name == "insb" || Name == "insw" || Name == "insl")) {
2053 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2054 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2055 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
2056 Operands.pop_back();
2057 Operands.pop_back();
2063 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
2064 if (Name.startswith("outs") && Operands.size() == 3 &&
2065 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
2066 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2067 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2068 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
2069 Operands.pop_back();
2070 Operands.pop_back();
2076 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2077 if (Name.startswith("movs") && Operands.size() == 3 &&
2078 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2079 (is64BitMode() && Name == "movsq"))) {
2080 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2081 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2082 if (isSrcOp(Op) && isDstOp(Op2)) {
2083 Operands.pop_back();
2084 Operands.pop_back();
2089 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2090 if (Name.startswith("lods") && Operands.size() == 3 &&
2091 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2092 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2093 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2094 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2095 if (isSrcOp(*Op1) && Op2->isReg()) {
2097 unsigned reg = Op2->getReg();
2098 bool isLods = Name == "lods";
2099 if (reg == X86::AL && (isLods || Name == "lodsb"))
2101 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2103 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2105 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2110 Operands.pop_back();
2111 Operands.pop_back();
2115 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2119 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2120 if (Name.startswith("stos") && Operands.size() == 3 &&
2121 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2122 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2123 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2124 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2125 if (isDstOp(*Op2) && Op1->isReg()) {
2127 unsigned reg = Op1->getReg();
2128 bool isStos = Name == "stos";
2129 if (reg == X86::AL && (isStos || Name == "stosb"))
2131 else if (reg == X86::AX && (isStos || Name == "stosw"))
2133 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2135 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2140 Operands.pop_back();
2141 Operands.pop_back();
2145 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2150 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2152 if ((Name.startswith("shr") || Name.startswith("sar") ||
2153 Name.startswith("shl") || Name.startswith("sal") ||
2154 Name.startswith("rcl") || Name.startswith("rcr") ||
2155 Name.startswith("rol") || Name.startswith("ror")) &&
2156 Operands.size() == 3) {
2157 if (isParsingIntelSyntax()) {
2159 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2160 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2161 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2163 Operands.pop_back();
2166 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2167 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2168 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2170 Operands.erase(Operands.begin() + 1);
2175 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2176 // instalias with an immediate operand yet.
2177 if (Name == "int" && Operands.size() == 2) {
2178 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2179 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2180 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2182 Operands.erase(Operands.begin() + 1);
2183 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2190 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2193 TmpInst.setOpcode(Opcode);
2195 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2196 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2197 TmpInst.addOperand(Inst.getOperand(0));
2202 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2203 bool isCmp = false) {
2204 if (!Inst.getOperand(0).isImm() ||
2205 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2208 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2211 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2212 bool isCmp = false) {
2213 if (!Inst.getOperand(0).isImm() ||
2214 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2217 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2220 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2221 bool isCmp = false) {
2222 if (!Inst.getOperand(0).isImm() ||
2223 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2226 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2230 processInstruction(MCInst &Inst,
2231 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2232 switch (Inst.getOpcode()) {
2233 default: return false;
2234 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2235 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2236 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2237 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2238 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2239 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2240 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2241 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2242 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2243 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2244 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2245 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2246 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2247 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2248 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2249 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2250 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2251 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2252 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2253 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2254 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2255 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2256 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2257 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2261 static const char *getSubtargetFeatureName(unsigned Val);
2263 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2264 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2265 MCStreamer &Out, unsigned &ErrorInfo,
2266 bool MatchingInlineAsm) {
2267 assert(!Operands.empty() && "Unexpect empty operand list!");
2268 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2269 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2270 ArrayRef<SMRange> EmptyRanges = None;
2272 // First, handle aliases that expand to multiple instructions.
2273 // FIXME: This should be replaced with a real .td file alias mechanism.
2274 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2276 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2277 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2278 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2279 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2281 Inst.setOpcode(X86::WAIT);
2283 if (!MatchingInlineAsm)
2284 Out.EmitInstruction(Inst);
2287 StringSwitch<const char*>(Op->getToken())
2288 .Case("finit", "fninit")
2289 .Case("fsave", "fnsave")
2290 .Case("fstcw", "fnstcw")
2291 .Case("fstcww", "fnstcw")
2292 .Case("fstenv", "fnstenv")
2293 .Case("fstsw", "fnstsw")
2294 .Case("fstsww", "fnstsw")
2295 .Case("fclex", "fnclex")
2297 assert(Repl && "Unknown wait-prefixed instruction");
2299 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2302 bool WasOriginallyInvalidOperand = false;
2305 // First, try a direct match.
2306 switch (MatchInstructionImpl(Operands, Inst,
2307 ErrorInfo, MatchingInlineAsm,
2308 isParsingIntelSyntax())) {
2311 // Some instructions need post-processing to, for example, tweak which
2312 // encoding is selected. Loop on it while changes happen so the
2313 // individual transformations can chain off each other.
2314 if (!MatchingInlineAsm)
2315 while (processInstruction(Inst, Operands))
2319 if (!MatchingInlineAsm)
2320 Out.EmitInstruction(Inst);
2321 Opcode = Inst.getOpcode();
2323 case Match_MissingFeature: {
2324 assert(ErrorInfo && "Unknown missing feature!");
2325 // Special case the error message for the very common case where only
2326 // a single subtarget feature is missing.
2327 std::string Msg = "instruction requires:";
2329 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2330 if (ErrorInfo & Mask) {
2332 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2336 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2338 case Match_InvalidOperand:
2339 WasOriginallyInvalidOperand = true;
2341 case Match_MnemonicFail:
2345 // FIXME: Ideally, we would only attempt suffix matches for things which are
2346 // valid prefixes, and we could just infer the right unambiguous
2347 // type. However, that requires substantially more matcher support than the
2350 // Change the operand to point to a temporary token.
2351 StringRef Base = Op->getToken();
2352 SmallString<16> Tmp;
2355 Op->setTokenValue(Tmp.str());
2357 // If this instruction starts with an 'f', then it is a floating point stack
2358 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2359 // 80-bit floating point, which use the suffixes s,l,t respectively.
2361 // Otherwise, we assume that this may be an integer instruction, which comes
2362 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2363 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2365 // Check for the various suffix matches.
2366 Tmp[Base.size()] = Suffixes[0];
2367 unsigned ErrorInfoIgnore;
2368 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2369 unsigned Match1, Match2, Match3, Match4;
2371 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2372 MatchingInlineAsm, isParsingIntelSyntax());
2373 // If this returned as a missing feature failure, remember that.
2374 if (Match1 == Match_MissingFeature)
2375 ErrorInfoMissingFeature = ErrorInfoIgnore;
2376 Tmp[Base.size()] = Suffixes[1];
2377 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2378 MatchingInlineAsm, isParsingIntelSyntax());
2379 // If this returned as a missing feature failure, remember that.
2380 if (Match2 == Match_MissingFeature)
2381 ErrorInfoMissingFeature = ErrorInfoIgnore;
2382 Tmp[Base.size()] = Suffixes[2];
2383 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2384 MatchingInlineAsm, isParsingIntelSyntax());
2385 // If this returned as a missing feature failure, remember that.
2386 if (Match3 == Match_MissingFeature)
2387 ErrorInfoMissingFeature = ErrorInfoIgnore;
2388 Tmp[Base.size()] = Suffixes[3];
2389 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2390 MatchingInlineAsm, isParsingIntelSyntax());
2391 // If this returned as a missing feature failure, remember that.
2392 if (Match4 == Match_MissingFeature)
2393 ErrorInfoMissingFeature = ErrorInfoIgnore;
2395 // Restore the old token.
2396 Op->setTokenValue(Base);
2398 // If exactly one matched, then we treat that as a successful match (and the
2399 // instruction will already have been filled in correctly, since the failing
2400 // matches won't have modified it).
2401 unsigned NumSuccessfulMatches =
2402 (Match1 == Match_Success) + (Match2 == Match_Success) +
2403 (Match3 == Match_Success) + (Match4 == Match_Success);
2404 if (NumSuccessfulMatches == 1) {
2406 if (!MatchingInlineAsm)
2407 Out.EmitInstruction(Inst);
2408 Opcode = Inst.getOpcode();
2412 // Otherwise, the match failed, try to produce a decent error message.
2414 // If we had multiple suffix matches, then identify this as an ambiguous
2416 if (NumSuccessfulMatches > 1) {
2418 unsigned NumMatches = 0;
2419 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2420 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2421 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2422 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2424 SmallString<126> Msg;
2425 raw_svector_ostream OS(Msg);
2426 OS << "ambiguous instructions require an explicit suffix (could be ";
2427 for (unsigned i = 0; i != NumMatches; ++i) {
2430 if (i + 1 == NumMatches)
2432 OS << "'" << Base << MatchChars[i] << "'";
2435 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2439 // Okay, we know that none of the variants matched successfully.
2441 // If all of the instructions reported an invalid mnemonic, then the original
2442 // mnemonic was invalid.
2443 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2444 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2445 if (!WasOriginallyInvalidOperand) {
2446 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2448 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2449 Ranges, MatchingInlineAsm);
2452 // Recover location info for the operand if we know which was the problem.
2453 if (ErrorInfo != ~0U) {
2454 if (ErrorInfo >= Operands.size())
2455 return Error(IDLoc, "too few operands for instruction",
2456 EmptyRanges, MatchingInlineAsm);
2458 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2459 if (Operand->getStartLoc().isValid()) {
2460 SMRange OperandRange = Operand->getLocRange();
2461 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2462 OperandRange, MatchingInlineAsm);
2466 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2470 // If one instruction matched with a missing feature, report this as a
2472 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2473 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2474 std::string Msg = "instruction requires:";
2476 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2477 if (ErrorInfoMissingFeature & Mask) {
2479 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2483 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2486 // If one instruction matched with an invalid operand, report this as an
2488 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2489 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2490 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2495 // If all of these were an outright failure, report it in a useless way.
2496 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2497 EmptyRanges, MatchingInlineAsm);
2502 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2503 StringRef IDVal = DirectiveID.getIdentifier();
2504 if (IDVal == ".word")
2505 return ParseDirectiveWord(2, DirectiveID.getLoc());
2506 else if (IDVal.startswith(".code"))
2507 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2508 else if (IDVal.startswith(".att_syntax")) {
2509 getParser().setAssemblerDialect(0);
2511 } else if (IDVal.startswith(".intel_syntax")) {
2512 getParser().setAssemblerDialect(1);
2513 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2514 if(Parser.getTok().getString() == "noprefix") {
2515 // FIXME : Handle noprefix
2525 /// ParseDirectiveWord
2526 /// ::= .word [ expression (, expression)* ]
2527 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2528 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2530 const MCExpr *Value;
2531 if (getParser().parseExpression(Value))
2534 getParser().getStreamer().EmitValue(Value, Size);
2536 if (getLexer().is(AsmToken::EndOfStatement))
2539 // FIXME: Improve diagnostic.
2540 if (getLexer().isNot(AsmToken::Comma))
2541 return Error(L, "unexpected token in directive");
2550 /// ParseDirectiveCode
2551 /// ::= .code32 | .code64
2552 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2553 if (IDVal == ".code32") {
2555 if (is64BitMode()) {
2557 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2559 } else if (IDVal == ".code64") {
2561 if (!is64BitMode()) {
2563 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2566 return Error(L, "unexpected directive " + IDVal);
2572 // Force static initialization.
2573 extern "C" void LLVMInitializeX86AsmParser() {
2574 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2575 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2578 #define GET_REGISTER_MATCHER
2579 #define GET_MATCHER_IMPLEMENTATION
2580 #define GET_SUBTARGET_FEATURE_NAME
2581 #include "X86GenAsmMatcher.inc"