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/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCParser/MCAsmLexer.h"
20 #include "llvm/MC/MCParser/MCAsmParser.h"
21 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCTargetAsmParser.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
36 static const char OpPrecedence[] = {
47 class X86AsmParser : public MCTargetAsmParser {
50 ParseInstructionInfo *InstInfo;
52 enum InfixCalculatorTok {
63 class InfixCalculator {
64 typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
65 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
66 SmallVector<ICToken, 4> PostfixStack;
69 int64_t popOperand() {
70 assert (!PostfixStack.empty() && "Poped an empty stack!");
71 ICToken Op = PostfixStack.pop_back_val();
72 assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
73 && "Expected and immediate or register!");
76 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
77 assert ((Op == IC_IMM || Op == IC_REGISTER) &&
78 "Unexpected operand!");
79 PostfixStack.push_back(std::make_pair(Op, Val));
82 void popOperator() { InfixOperatorStack.pop_back_val(); }
83 void pushOperator(InfixCalculatorTok Op) {
84 // Push the new operator if the stack is empty.
85 if (InfixOperatorStack.empty()) {
86 InfixOperatorStack.push_back(Op);
90 // Push the new operator if it has a higher precedence than the operator
91 // on the top of the stack or the operator on the top of the stack is a
93 unsigned Idx = InfixOperatorStack.size() - 1;
94 InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
95 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
96 InfixOperatorStack.push_back(Op);
100 // The operator on the top of the stack has higher precedence than the
102 unsigned ParenCount = 0;
104 // Nothing to process.
105 if (InfixOperatorStack.empty())
108 Idx = InfixOperatorStack.size() - 1;
109 StackOp = InfixOperatorStack[Idx];
110 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
113 // If we have an even parentheses count and we see a left parentheses,
114 // then stop processing.
115 if (!ParenCount && StackOp == IC_LPAREN)
118 if (StackOp == IC_RPAREN) {
120 InfixOperatorStack.pop_back_val();
121 } else if (StackOp == IC_LPAREN) {
123 InfixOperatorStack.pop_back_val();
125 InfixOperatorStack.pop_back_val();
126 PostfixStack.push_back(std::make_pair(StackOp, 0));
129 // Push the new operator.
130 InfixOperatorStack.push_back(Op);
133 // Push any remaining operators onto the postfix stack.
134 while (!InfixOperatorStack.empty()) {
135 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
136 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
137 PostfixStack.push_back(std::make_pair(StackOp, 0));
140 if (PostfixStack.empty())
143 SmallVector<ICToken, 16> OperandStack;
144 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
145 ICToken Op = PostfixStack[i];
146 if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
147 OperandStack.push_back(Op);
149 assert (OperandStack.size() > 1 && "Too few operands.");
151 ICToken Op2 = OperandStack.pop_back_val();
152 ICToken Op1 = OperandStack.pop_back_val();
155 report_fatal_error("Unexpected operator!");
158 Val = Op1.second + Op2.second;
159 OperandStack.push_back(std::make_pair(IC_IMM, Val));
162 Val = Op1.second - Op2.second;
163 OperandStack.push_back(std::make_pair(IC_IMM, Val));
166 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
167 "Multiply operation with an immediate and a register!");
168 Val = Op1.second * Op2.second;
169 OperandStack.push_back(std::make_pair(IC_IMM, Val));
172 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
173 "Divide operation with an immediate and a register!");
174 assert (Op2.second != 0 && "Division by zero!");
175 Val = Op1.second / Op2.second;
176 OperandStack.push_back(std::make_pair(IC_IMM, Val));
181 assert (OperandStack.size() == 1 && "Expected a single result.");
182 return OperandStack.pop_back_val().second;
186 enum IntelExprState {
201 class IntelExprStateMachine {
202 IntelExprState State, PrevState;
203 unsigned BaseReg, IndexReg, TmpReg, Scale;
207 bool StopOnLBrac, AddImmPrefix;
210 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
211 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
212 Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac),
213 AddImmPrefix(addimmprefix) {}
215 unsigned getBaseReg() { return BaseReg; }
216 unsigned getIndexReg() { return IndexReg; }
217 unsigned getScale() { return Scale; }
218 const MCExpr *getSym() { return Sym; }
219 StringRef getSymName() { return SymName; }
220 int64_t getImm() { return Imm + IC.execute(); }
221 bool isValidEndState() { return State == IES_RBRAC; }
222 bool getStopOnLBrac() { return StopOnLBrac; }
223 bool getAddImmPrefix() { return AddImmPrefix; }
224 bool hadError() { return State == IES_ERROR; }
227 IntelExprState CurrState = State;
236 IC.pushOperator(IC_PLUS);
237 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
238 // If we already have a BaseReg, then assume this is the IndexReg with
243 assert (!IndexReg && "BaseReg/IndexReg already set!");
250 PrevState = CurrState;
253 IntelExprState CurrState = State;
268 // Only push the minus operator if it is not a unary operator.
269 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
270 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
271 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
272 IC.pushOperator(IC_MINUS);
273 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
274 // If we already have a BaseReg, then assume this is the IndexReg with
279 assert (!IndexReg && "BaseReg/IndexReg already set!");
286 PrevState = CurrState;
288 void onRegister(unsigned Reg) {
289 IntelExprState CurrState = State;
296 State = IES_REGISTER;
298 IC.pushOperand(IC_REGISTER);
301 // Index Register - Scale * Register
302 if (PrevState == IES_INTEGER) {
303 assert (!IndexReg && "IndexReg already set!");
304 State = IES_REGISTER;
306 // Get the scale and replace the 'Scale * Register' with '0'.
307 Scale = IC.popOperand();
308 IC.pushOperand(IC_IMM);
315 PrevState = CurrState;
317 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
327 SymName = SymRefName;
328 IC.pushOperand(IC_IMM);
332 void onInteger(int64_t TmpInt) {
333 IntelExprState CurrState = State;
344 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
345 // Index Register - Register * Scale
346 assert (!IndexReg && "IndexReg already set!");
349 // Get the scale and replace the 'Register * Scale' with '0'.
351 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
352 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
353 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
354 CurrState == IES_MINUS) {
355 // Unary minus. No need to pop the minus operand because it was never
357 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
359 IC.pushOperand(IC_IMM, TmpInt);
363 PrevState = CurrState;
374 State = IES_MULTIPLY;
375 IC.pushOperator(IC_MULTIPLY);
388 IC.pushOperator(IC_DIVIDE);
400 IC.pushOperator(IC_PLUS);
405 IntelExprState CurrState = State;
414 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
415 // If we already have a BaseReg, then assume this is the IndexReg with
420 assert (!IndexReg && "BaseReg/IndexReg already set!");
427 PrevState = CurrState;
430 IntelExprState CurrState = State;
440 // FIXME: We don't handle this type of unary minus, yet.
441 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
442 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
443 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
444 CurrState == IES_MINUS) {
449 IC.pushOperator(IC_LPAREN);
452 PrevState = CurrState;
464 IC.pushOperator(IC_RPAREN);
470 MCAsmParser &getParser() const { return Parser; }
472 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
474 bool Error(SMLoc L, const Twine &Msg,
475 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
476 bool MatchingInlineAsm = false) {
477 if (MatchingInlineAsm) return true;
478 return Parser.Error(L, Msg, Ranges);
481 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
486 X86Operand *ParseOperand();
487 X86Operand *ParseATTOperand();
488 X86Operand *ParseIntelOperand();
489 X86Operand *ParseIntelOffsetOfOperator();
490 X86Operand *ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
491 X86Operand *ParseIntelOperator(unsigned OpKind);
492 X86Operand *ParseIntelMemOperand(unsigned SegReg, int64_t ImmDisp,
494 X86Operand *ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
495 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
496 int64_t ImmDisp, unsigned Size);
497 X86Operand *ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
499 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
501 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
502 unsigned BaseReg, unsigned IndexReg,
503 unsigned Scale, SMLoc Start, SMLoc End,
504 unsigned Size, StringRef SymName);
506 bool ParseDirectiveWord(unsigned Size, SMLoc L);
507 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
509 bool processInstruction(MCInst &Inst,
510 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
512 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
513 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
514 MCStreamer &Out, unsigned &ErrorInfo,
515 bool MatchingInlineAsm);
517 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
518 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
519 bool isSrcOp(X86Operand &Op);
521 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
522 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
523 bool isDstOp(X86Operand &Op);
525 bool is64BitMode() const {
526 // FIXME: Can tablegen auto-generate this?
527 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
530 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
531 setAvailableFeatures(FB);
534 bool isParsingIntelSyntax() {
535 return getParser().getAssemblerDialect();
538 /// @name Auto-generated Matcher Functions
541 #define GET_ASSEMBLER_HEADER
542 #include "X86GenAsmMatcher.inc"
547 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
548 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
550 // Initialize the set of available features.
551 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
553 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
555 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
557 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
559 virtual bool ParseDirective(AsmToken DirectiveID);
561 } // end anonymous namespace
563 /// @name Auto-generated Match Functions
566 static unsigned MatchRegisterName(StringRef Name);
570 static bool isImmSExti16i8Value(uint64_t Value) {
571 return (( Value <= 0x000000000000007FULL)||
572 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
573 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
576 static bool isImmSExti32i8Value(uint64_t Value) {
577 return (( Value <= 0x000000000000007FULL)||
578 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
579 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
582 static bool isImmZExtu32u8Value(uint64_t Value) {
583 return (Value <= 0x00000000000000FFULL);
586 static bool isImmSExti64i8Value(uint64_t Value) {
587 return (( Value <= 0x000000000000007FULL)||
588 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
591 static bool isImmSExti64i32Value(uint64_t Value) {
592 return (( Value <= 0x000000007FFFFFFFULL)||
593 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
597 /// X86Operand - Instances of this class represent a parsed X86 machine
599 struct X86Operand : public MCParsedAsmOperand {
607 SMLoc StartLoc, EndLoc;
641 X86Operand(KindTy K, SMLoc Start, SMLoc End)
642 : Kind(K), StartLoc(Start), EndLoc(End) {}
644 StringRef getSymName() { return SymName; }
646 /// getStartLoc - Get the location of the first token of this operand.
647 SMLoc getStartLoc() const { return StartLoc; }
648 /// getEndLoc - Get the location of the last token of this operand.
649 SMLoc getEndLoc() const { return EndLoc; }
650 /// getLocRange - Get the range between the first and last token of this
652 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
653 /// getOffsetOfLoc - Get the location of the offset operator.
654 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
656 virtual void print(raw_ostream &OS) const {}
658 StringRef getToken() const {
659 assert(Kind == Token && "Invalid access!");
660 return StringRef(Tok.Data, Tok.Length);
662 void setTokenValue(StringRef Value) {
663 assert(Kind == Token && "Invalid access!");
664 Tok.Data = Value.data();
665 Tok.Length = Value.size();
668 unsigned getReg() const {
669 assert(Kind == Register && "Invalid access!");
673 const MCExpr *getImm() const {
674 assert(Kind == Immediate && "Invalid access!");
678 const MCExpr *getMemDisp() const {
679 assert(Kind == Memory && "Invalid access!");
682 unsigned getMemSegReg() const {
683 assert(Kind == Memory && "Invalid access!");
686 unsigned getMemBaseReg() const {
687 assert(Kind == Memory && "Invalid access!");
690 unsigned getMemIndexReg() const {
691 assert(Kind == Memory && "Invalid access!");
694 unsigned getMemScale() const {
695 assert(Kind == Memory && "Invalid access!");
699 bool isToken() const {return Kind == Token; }
701 bool isImm() const { return Kind == Immediate; }
703 bool isImmSExti16i8() const {
707 // If this isn't a constant expr, just assume it fits and let relaxation
709 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
713 // Otherwise, check the value is in a range that makes sense for this
715 return isImmSExti16i8Value(CE->getValue());
717 bool isImmSExti32i8() const {
721 // If this isn't a constant expr, just assume it fits and let relaxation
723 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
727 // Otherwise, check the value is in a range that makes sense for this
729 return isImmSExti32i8Value(CE->getValue());
731 bool isImmZExtu32u8() const {
735 // If this isn't a constant expr, just assume it fits and let relaxation
737 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
741 // Otherwise, check the value is in a range that makes sense for this
743 return isImmZExtu32u8Value(CE->getValue());
745 bool isImmSExti64i8() const {
749 // If this isn't a constant expr, just assume it fits and let relaxation
751 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
755 // Otherwise, check the value is in a range that makes sense for this
757 return isImmSExti64i8Value(CE->getValue());
759 bool isImmSExti64i32() const {
763 // If this isn't a constant expr, just assume it fits and let relaxation
765 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
769 // Otherwise, check the value is in a range that makes sense for this
771 return isImmSExti64i32Value(CE->getValue());
774 bool isOffsetOf() const {
775 return OffsetOfLoc.getPointer();
778 bool needAddressOf() const {
782 bool isMem() const { return Kind == Memory; }
783 bool isMem8() const {
784 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
786 bool isMem16() const {
787 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
789 bool isMem32() const {
790 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
792 bool isMem64() const {
793 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
795 bool isMem80() const {
796 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
798 bool isMem128() const {
799 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
801 bool isMem256() const {
802 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
805 bool isMemVX32() const {
806 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
807 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
809 bool isMemVY32() const {
810 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
811 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
813 bool isMemVX64() const {
814 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
815 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
817 bool isMemVY64() const {
818 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
819 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
822 bool isAbsMem() const {
823 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
824 !getMemIndexReg() && getMemScale() == 1;
827 bool isReg() const { return Kind == Register; }
829 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
830 // Add as immediates when possible.
831 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
832 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
834 Inst.addOperand(MCOperand::CreateExpr(Expr));
837 void addRegOperands(MCInst &Inst, unsigned N) const {
838 assert(N == 1 && "Invalid number of operands!");
839 Inst.addOperand(MCOperand::CreateReg(getReg()));
842 void addImmOperands(MCInst &Inst, unsigned N) const {
843 assert(N == 1 && "Invalid number of operands!");
844 addExpr(Inst, getImm());
847 void addMem8Operands(MCInst &Inst, unsigned N) const {
848 addMemOperands(Inst, N);
850 void addMem16Operands(MCInst &Inst, unsigned N) const {
851 addMemOperands(Inst, N);
853 void addMem32Operands(MCInst &Inst, unsigned N) const {
854 addMemOperands(Inst, N);
856 void addMem64Operands(MCInst &Inst, unsigned N) const {
857 addMemOperands(Inst, N);
859 void addMem80Operands(MCInst &Inst, unsigned N) const {
860 addMemOperands(Inst, N);
862 void addMem128Operands(MCInst &Inst, unsigned N) const {
863 addMemOperands(Inst, N);
865 void addMem256Operands(MCInst &Inst, unsigned N) const {
866 addMemOperands(Inst, N);
868 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
869 addMemOperands(Inst, N);
871 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
872 addMemOperands(Inst, N);
874 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
875 addMemOperands(Inst, N);
877 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
878 addMemOperands(Inst, N);
881 void addMemOperands(MCInst &Inst, unsigned N) const {
882 assert((N == 5) && "Invalid number of operands!");
883 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
884 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
885 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
886 addExpr(Inst, getMemDisp());
887 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
890 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
891 assert((N == 1) && "Invalid number of operands!");
892 // Add as immediates when possible.
893 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
894 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
896 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
899 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
900 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
901 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
902 Res->Tok.Data = Str.data();
903 Res->Tok.Length = Str.size();
907 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
908 bool AddressOf = false,
909 SMLoc OffsetOfLoc = SMLoc(),
910 StringRef SymName = StringRef()) {
911 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
912 Res->Reg.RegNo = RegNo;
913 Res->AddressOf = AddressOf;
914 Res->OffsetOfLoc = OffsetOfLoc;
915 Res->SymName = SymName;
919 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
920 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
925 /// Create an absolute memory operand.
926 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
928 StringRef SymName = StringRef()) {
929 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
931 Res->Mem.Disp = Disp;
932 Res->Mem.BaseReg = 0;
933 Res->Mem.IndexReg = 0;
935 Res->Mem.Size = Size;
936 Res->SymName = SymName;
937 Res->AddressOf = false;
941 /// Create a generalized memory operand.
942 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
943 unsigned BaseReg, unsigned IndexReg,
944 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
946 StringRef SymName = StringRef()) {
947 // We should never just have a displacement, that should be parsed as an
948 // absolute memory operand.
949 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
951 // The scale should always be one of {1,2,4,8}.
952 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
954 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
955 Res->Mem.SegReg = SegReg;
956 Res->Mem.Disp = Disp;
957 Res->Mem.BaseReg = BaseReg;
958 Res->Mem.IndexReg = IndexReg;
959 Res->Mem.Scale = Scale;
960 Res->Mem.Size = Size;
961 Res->SymName = SymName;
962 Res->AddressOf = false;
967 } // end anonymous namespace.
969 bool X86AsmParser::isSrcOp(X86Operand &Op) {
970 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
972 return (Op.isMem() &&
973 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
974 isa<MCConstantExpr>(Op.Mem.Disp) &&
975 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
976 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
979 bool X86AsmParser::isDstOp(X86Operand &Op) {
980 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
983 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
984 isa<MCConstantExpr>(Op.Mem.Disp) &&
985 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
986 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
989 bool X86AsmParser::ParseRegister(unsigned &RegNo,
990 SMLoc &StartLoc, SMLoc &EndLoc) {
992 const AsmToken &PercentTok = Parser.getTok();
993 StartLoc = PercentTok.getLoc();
995 // If we encounter a %, ignore it. This code handles registers with and
996 // without the prefix, unprefixed registers can occur in cfi directives.
997 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
998 Parser.Lex(); // Eat percent token.
1000 const AsmToken &Tok = Parser.getTok();
1001 EndLoc = Tok.getEndLoc();
1003 if (Tok.isNot(AsmToken::Identifier)) {
1004 if (isParsingIntelSyntax()) return true;
1005 return Error(StartLoc, "invalid register name",
1006 SMRange(StartLoc, EndLoc));
1009 RegNo = MatchRegisterName(Tok.getString());
1011 // If the match failed, try the register name as lowercase.
1013 RegNo = MatchRegisterName(Tok.getString().lower());
1015 if (!is64BitMode()) {
1016 // FIXME: This should be done using Requires<In32BitMode> and
1017 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1019 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1021 if (RegNo == X86::RIZ ||
1022 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1023 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1024 X86II::isX86_64ExtendedReg(RegNo))
1025 return Error(StartLoc, "register %"
1026 + Tok.getString() + " is only available in 64-bit mode",
1027 SMRange(StartLoc, EndLoc));
1030 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1031 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1033 Parser.Lex(); // Eat 'st'
1035 // Check to see if we have '(4)' after %st.
1036 if (getLexer().isNot(AsmToken::LParen))
1041 const AsmToken &IntTok = Parser.getTok();
1042 if (IntTok.isNot(AsmToken::Integer))
1043 return Error(IntTok.getLoc(), "expected stack index");
1044 switch (IntTok.getIntVal()) {
1045 case 0: RegNo = X86::ST0; break;
1046 case 1: RegNo = X86::ST1; break;
1047 case 2: RegNo = X86::ST2; break;
1048 case 3: RegNo = X86::ST3; break;
1049 case 4: RegNo = X86::ST4; break;
1050 case 5: RegNo = X86::ST5; break;
1051 case 6: RegNo = X86::ST6; break;
1052 case 7: RegNo = X86::ST7; break;
1053 default: return Error(IntTok.getLoc(), "invalid stack index");
1056 if (getParser().Lex().isNot(AsmToken::RParen))
1057 return Error(Parser.getTok().getLoc(), "expected ')'");
1059 EndLoc = Parser.getTok().getEndLoc();
1060 Parser.Lex(); // Eat ')'
1064 EndLoc = Parser.getTok().getEndLoc();
1066 // If this is "db[0-7]", match it as an alias
1068 if (RegNo == 0 && Tok.getString().size() == 3 &&
1069 Tok.getString().startswith("db")) {
1070 switch (Tok.getString()[2]) {
1071 case '0': RegNo = X86::DR0; break;
1072 case '1': RegNo = X86::DR1; break;
1073 case '2': RegNo = X86::DR2; break;
1074 case '3': RegNo = X86::DR3; break;
1075 case '4': RegNo = X86::DR4; break;
1076 case '5': RegNo = X86::DR5; break;
1077 case '6': RegNo = X86::DR6; break;
1078 case '7': RegNo = X86::DR7; break;
1082 EndLoc = Parser.getTok().getEndLoc();
1083 Parser.Lex(); // Eat it.
1089 if (isParsingIntelSyntax()) return true;
1090 return Error(StartLoc, "invalid register name",
1091 SMRange(StartLoc, EndLoc));
1094 Parser.Lex(); // Eat identifier token.
1098 X86Operand *X86AsmParser::ParseOperand() {
1099 if (isParsingIntelSyntax())
1100 return ParseIntelOperand();
1101 return ParseATTOperand();
1104 /// getIntelMemOperandSize - Return intel memory operand size.
1105 static unsigned getIntelMemOperandSize(StringRef OpStr) {
1106 unsigned Size = StringSwitch<unsigned>(OpStr)
1107 .Cases("BYTE", "byte", 8)
1108 .Cases("WORD", "word", 16)
1109 .Cases("DWORD", "dword", 32)
1110 .Cases("QWORD", "qword", 64)
1111 .Cases("XWORD", "xword", 80)
1112 .Cases("XMMWORD", "xmmword", 128)
1113 .Cases("YMMWORD", "ymmword", 256)
1119 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1120 unsigned BaseReg, unsigned IndexReg,
1121 unsigned Scale, SMLoc Start, SMLoc End,
1122 unsigned Size, StringRef SymName) {
1123 bool NeedSizeDir = false;
1124 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
1125 const MCSymbol &Sym = SymRef->getSymbol();
1126 // FIXME: The SemaLookup will fail if the name is anything other then an
1128 // FIXME: Pass a valid SMLoc.
1129 bool IsVarDecl = false;
1130 unsigned tLength, tSize, tType;
1131 SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, tLength, tSize,
1134 Size = tType * 8; // Size is in terms of bits in this context.
1135 NeedSizeDir = Size > 0;
1137 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1138 // reference. We need an 'r' constraint here, so we need to create register
1139 // operand to ensure proper matching. Just pick a GPR based on the size of
1142 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1143 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1149 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1152 // When parsing inline assembly we set the base register to a non-zero value
1153 // if we don't know the actual value at this time. This is necessary to
1154 // get the matching correct in some cases.
1155 BaseReg = BaseReg ? BaseReg : 1;
1156 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1157 End, Size, SymName);
1161 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1162 StringRef SymName, int64_t ImmDisp,
1163 int64_t FinalImmDisp, SMLoc &BracLoc,
1164 SMLoc &StartInBrac, SMLoc &End) {
1165 // Remove the '[' and ']' from the IR string.
1166 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1167 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1169 // If ImmDisp is non-zero, then we parsed a displacement before the
1170 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1171 // If ImmDisp doesn't match the displacement computed by the state machine
1172 // then we have an additional displacement in the bracketed expression.
1173 if (ImmDisp != FinalImmDisp) {
1175 // We have an immediate displacement before the bracketed expression.
1176 // Adjust this to match the final immediate displacement.
1178 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1179 E = AsmRewrites->end(); I != E; ++I) {
1180 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1182 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1183 assert (!Found && "ImmDisp already rewritten.");
1184 (*I).Kind = AOK_Imm;
1185 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1186 (*I).Val = FinalImmDisp;
1191 assert (Found && "Unable to rewrite ImmDisp.");
1193 // We have a symbolic and an immediate displacement, but no displacement
1194 // before the bracketed expression. Put the immediate displacement
1195 // before the bracketed expression.
1196 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1199 // Remove all the ImmPrefix rewrites within the brackets.
1200 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1201 E = AsmRewrites->end(); I != E; ++I) {
1202 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1204 if ((*I).Kind == AOK_ImmPrefix)
1205 (*I).Kind = AOK_Delete;
1207 const char *SymLocPtr = SymName.data();
1208 // Skip everything before the symbol.
1209 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1210 assert(Len > 0 && "Expected a non-negative length.");
1211 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1213 // Skip everything after the symbol.
1214 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1215 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1216 assert(Len > 0 && "Expected a non-negative length.");
1217 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1222 X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1223 const AsmToken &Tok = Parser.getTok();
1227 bool UpdateLocLex = true;
1229 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1230 // identifier. Don't try an parse it as a register.
1231 if (Tok.getString().startswith("."))
1234 // If we're parsing an immediate expression, we don't expect a '['.
1235 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1238 switch (getLexer().getKind()) {
1240 if (SM.isValidEndState()) {
1244 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1246 case AsmToken::EndOfStatement: {
1250 case AsmToken::Identifier: {
1251 // This could be a register or a symbolic displacement.
1254 SMLoc IdentLoc = Tok.getLoc();
1255 StringRef Identifier = Tok.getString();
1256 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1257 SM.onRegister(TmpReg);
1258 UpdateLocLex = false;
1261 if (!isParsingInlineAsm()) {
1262 if (getParser().parsePrimaryExpr(Val, End))
1263 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1265 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, End))
1268 SM.onIdentifierExpr(Val, Identifier);
1269 UpdateLocLex = false;
1272 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1274 case AsmToken::Integer:
1275 if (isParsingInlineAsm() && SM.getAddImmPrefix())
1276 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1278 SM.onInteger(Tok.getIntVal());
1280 case AsmToken::Plus: SM.onPlus(); break;
1281 case AsmToken::Minus: SM.onMinus(); break;
1282 case AsmToken::Star: SM.onStar(); break;
1283 case AsmToken::Slash: SM.onDivide(); break;
1284 case AsmToken::LBrac: SM.onLBrac(); break;
1285 case AsmToken::RBrac: SM.onRBrac(); break;
1286 case AsmToken::LParen: SM.onLParen(); break;
1287 case AsmToken::RParen: SM.onRParen(); break;
1290 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1292 if (!Done && UpdateLocLex) {
1294 Parser.Lex(); // Consume the token.
1300 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1303 const AsmToken &Tok = Parser.getTok();
1304 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1305 if (getLexer().isNot(AsmToken::LBrac))
1306 return ErrorOperand(BracLoc, "Expected '[' token!");
1307 Parser.Lex(); // Eat '['
1309 SMLoc StartInBrac = Tok.getLoc();
1310 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1311 // may have already parsed an immediate displacement before the bracketed
1313 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1314 if (X86Operand *Err = ParseIntelExpression(SM, End))
1318 if (const MCExpr *Sym = SM.getSym()) {
1319 // A symbolic displacement.
1321 if (isParsingInlineAsm())
1322 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1323 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1326 // An immediate displacement only.
1327 Disp = MCConstantExpr::Create(SM.getImm(), getContext());
1330 // Parse the dot operator (e.g., [ebx].foo.bar).
1331 if (Tok.getString().startswith(".")) {
1332 const MCExpr *NewDisp;
1333 if (X86Operand *Err = ParseIntelDotOperator(Disp, NewDisp))
1336 End = Tok.getEndLoc();
1337 Parser.Lex(); // Eat the field.
1341 int BaseReg = SM.getBaseReg();
1342 int IndexReg = SM.getIndexReg();
1343 int Scale = SM.getScale();
1344 if (!isParsingInlineAsm()) {
1346 if (!BaseReg && !IndexReg) {
1348 return X86Operand::CreateMem(Disp, Start, End, Size);
1350 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1352 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1356 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1357 End, Size, SM.getSymName());
1360 // Inline assembly may use variable names with namespace alias qualifiers.
1361 X86Operand *X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1362 StringRef &Identifier,
1364 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1368 const AsmToken &Tok = Parser.getTok();
1369 AsmToken IdentEnd = Tok;
1372 switch (getLexer().getKind()) {
1376 case AsmToken::Colon:
1378 getLexer().Lex(); // Consume ':'.
1379 if (getLexer().isNot(AsmToken::Colon))
1380 return ErrorOperand(Tok.getLoc(), "Expected ':' token!");
1381 getLexer().Lex(); // Consume second ':'.
1382 if (getLexer().isNot(AsmToken::Identifier))
1383 return ErrorOperand(Tok.getLoc(), "Expected an identifier token!");
1385 case AsmToken::Identifier:
1387 getLexer().Lex(); // Consume the identifier.
1392 unsigned Len = IdentEnd.getLoc().getPointer() - Identifier.data();
1393 Identifier = StringRef(Identifier.data(), Len + IdentEnd.getString().size());
1394 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1395 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1396 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1400 /// ParseIntelMemOperand - Parse intel style memory operand.
1401 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg,
1404 const AsmToken &Tok = Parser.getTok();
1407 unsigned Size = getIntelMemOperandSize(Tok.getString());
1409 Parser.Lex(); // Eat operand size (e.g., byte, word).
1410 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1411 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1412 Parser.Lex(); // Eat ptr.
1415 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1416 if (getLexer().is(AsmToken::Integer)) {
1417 if (isParsingInlineAsm())
1418 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1420 int64_t ImmDisp = Tok.getIntVal();
1421 Parser.Lex(); // Eat the integer.
1422 if (getLexer().isNot(AsmToken::LBrac))
1423 return ErrorOperand(Start, "Expected '[' token!");
1424 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1427 if (getLexer().is(AsmToken::LBrac))
1428 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1430 if (!ParseRegister(SegReg, Start, End)) {
1431 // Handel SegReg : [ ... ]
1432 if (getLexer().isNot(AsmToken::Colon))
1433 return ErrorOperand(Start, "Expected ':' token!");
1434 Parser.Lex(); // Eat :
1435 if (getLexer().isNot(AsmToken::LBrac))
1436 return ErrorOperand(Start, "Expected '[' token!");
1437 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1441 if (!isParsingInlineAsm()) {
1442 if (getParser().parsePrimaryExpr(Val, End))
1443 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1445 return X86Operand::CreateMem(Val, Start, End, Size);
1448 StringRef Identifier = Tok.getString();
1449 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, End))
1451 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1452 /*Scale=*/1, Start, End, Size, Identifier);
1455 /// Parse the '.' operator.
1456 X86Operand *X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1457 const MCExpr *&NewDisp) {
1458 const AsmToken &Tok = Parser.getTok();
1459 int64_t OrigDispVal, DotDispVal;
1461 // FIXME: Handle non-constant expressions.
1462 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1463 OrigDispVal = OrigDisp->getValue();
1465 return ErrorOperand(Tok.getLoc(), "Non-constant offsets are not supported!");
1468 StringRef DotDispStr = Tok.getString().drop_front(1);
1470 // .Imm gets lexed as a real.
1471 if (Tok.is(AsmToken::Real)) {
1473 DotDispStr.getAsInteger(10, DotDisp);
1474 DotDispVal = DotDisp.getZExtValue();
1475 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1477 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1478 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1480 return ErrorOperand(Tok.getLoc(), "Unable to lookup field reference!");
1481 DotDispVal = DotDisp;
1483 return ErrorOperand(Tok.getLoc(), "Unexpected token type!");
1485 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1486 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1487 unsigned Len = DotDispStr.size();
1488 unsigned Val = OrigDispVal + DotDispVal;
1489 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1493 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1497 /// Parse the 'offset' operator. This operator is used to specify the
1498 /// location rather then the content of a variable.
1499 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1500 const AsmToken &Tok = Parser.getTok();
1501 SMLoc OffsetOfLoc = Tok.getLoc();
1502 Parser.Lex(); // Eat offset.
1505 SMLoc Start = Tok.getLoc(), End;
1506 StringRef Identifier = Tok.getString();
1507 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, End))
1510 // Don't emit the offset operator.
1511 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1513 // The offset operator will have an 'r' constraint, thus we need to create
1514 // register operand to ensure proper matching. Just pick a GPR based on
1515 // the size of a pointer.
1516 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1517 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1518 OffsetOfLoc, Identifier);
1521 enum IntelOperatorKind {
1527 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1528 /// returns the number of elements in an array. It returns the value 1 for
1529 /// non-array variables. The SIZE operator returns the size of a C or C++
1530 /// variable. A variable's size is the product of its LENGTH and TYPE. The
1531 /// TYPE operator returns the size of a C or C++ type or variable. If the
1532 /// variable is an array, TYPE returns the size of a single element.
1533 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1534 const AsmToken &Tok = Parser.getTok();
1535 SMLoc TypeLoc = Tok.getLoc();
1536 Parser.Lex(); // Eat operator.
1538 const MCExpr *Val = 0;
1539 AsmToken StartTok = Tok;
1540 SMLoc Start = Tok.getLoc(), End;
1541 StringRef Identifier = Tok.getString();
1542 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, End))
1545 unsigned Length = 0, Size = 0, Type = 0;
1546 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Val)) {
1547 const MCSymbol &Sym = SymRef->getSymbol();
1548 // FIXME: The SemaLookup will fail if the name is anything other then an
1550 // FIXME: Pass a valid SMLoc.
1552 if (!SemaCallback->LookupInlineAsmIdentifier(Sym.getName(), NULL, Length,
1553 Size, Type, IsVarDecl))
1554 // FIXME: We don't warn on variables with namespace alias qualifiers
1555 // because support still needs to be added in the frontend.
1556 if (Identifier.equals(StartTok.getString()))
1557 return ErrorOperand(Start, "Unable to lookup expr!");
1561 default: llvm_unreachable("Unexpected operand kind!");
1562 case IOK_LENGTH: CVal = Length; break;
1563 case IOK_SIZE: CVal = Size; break;
1564 case IOK_TYPE: CVal = Type; break;
1567 // Rewrite the type operator and the C or C++ type or variable in terms of an
1568 // immediate. E.g. TYPE foo -> $$4
1569 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1570 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1572 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1573 return X86Operand::CreateImm(Imm, Start, End);
1576 X86Operand *X86AsmParser::ParseIntelOperand() {
1577 const AsmToken &Tok = Parser.getTok();
1578 SMLoc Start = Tok.getLoc(), End;
1580 // Offset, length, type and size operators.
1581 if (isParsingInlineAsm()) {
1582 StringRef AsmTokStr = Tok.getString();
1583 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1584 return ParseIntelOffsetOfOperator();
1585 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1586 return ParseIntelOperator(IOK_LENGTH);
1587 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1588 return ParseIntelOperator(IOK_SIZE);
1589 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1590 return ParseIntelOperator(IOK_TYPE);
1594 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1595 getLexer().is(AsmToken::LParen)) {
1596 AsmToken StartTok = Tok;
1597 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1598 /*AddImmPrefix=*/false);
1599 if (X86Operand *Err = ParseIntelExpression(SM, End))
1602 int64_t Imm = SM.getImm();
1603 if (isParsingInlineAsm()) {
1604 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1605 if (StartTok.getString().size() == Len)
1606 // Just add a prefix if this wasn't a complex immediate expression.
1607 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1609 // Otherwise, rewrite the complex expression as a single immediate.
1610 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1613 if (getLexer().isNot(AsmToken::LBrac)) {
1614 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1615 return X86Operand::CreateImm(ImmExpr, Start, End);
1618 // Only positive immediates are valid.
1620 return ErrorOperand(Start, "expected a positive immediate displacement "
1621 "before bracketed expr.");
1623 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1624 return ParseIntelMemOperand(/*SegReg=*/0, Imm, Start);
1629 if (!ParseRegister(RegNo, Start, End)) {
1630 // If this is a segment register followed by a ':', then this is the start
1631 // of a memory reference, otherwise this is a normal register reference.
1632 if (getLexer().isNot(AsmToken::Colon))
1633 return X86Operand::CreateReg(RegNo, Start, End);
1635 getParser().Lex(); // Eat the colon.
1636 return ParseIntelMemOperand(/*SegReg=*/RegNo, /*Disp=*/0, Start);
1640 return ParseIntelMemOperand(/*SegReg=*/0, /*Disp=*/0, Start);
1643 X86Operand *X86AsmParser::ParseATTOperand() {
1644 switch (getLexer().getKind()) {
1646 // Parse a memory operand with no segment register.
1647 return ParseMemOperand(0, Parser.getTok().getLoc());
1648 case AsmToken::Percent: {
1649 // Read the register.
1652 if (ParseRegister(RegNo, Start, End)) return 0;
1653 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1654 Error(Start, "%eiz and %riz can only be used as index registers",
1655 SMRange(Start, End));
1659 // If this is a segment register followed by a ':', then this is the start
1660 // of a memory reference, otherwise this is a normal register reference.
1661 if (getLexer().isNot(AsmToken::Colon))
1662 return X86Operand::CreateReg(RegNo, Start, End);
1664 getParser().Lex(); // Eat the colon.
1665 return ParseMemOperand(RegNo, Start);
1667 case AsmToken::Dollar: {
1668 // $42 -> immediate.
1669 SMLoc Start = Parser.getTok().getLoc(), End;
1672 if (getParser().parseExpression(Val, End))
1674 return X86Operand::CreateImm(Val, Start, End);
1679 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1680 /// has already been parsed if present.
1681 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1683 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1684 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1685 // only way to do this without lookahead is to eat the '(' and see what is
1687 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1688 if (getLexer().isNot(AsmToken::LParen)) {
1690 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1692 // After parsing the base expression we could either have a parenthesized
1693 // memory address or not. If not, return now. If so, eat the (.
1694 if (getLexer().isNot(AsmToken::LParen)) {
1695 // Unless we have a segment register, treat this as an immediate.
1697 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1698 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1704 // Okay, we have a '('. We don't know if this is an expression or not, but
1705 // so we have to eat the ( to see beyond it.
1706 SMLoc LParenLoc = Parser.getTok().getLoc();
1707 Parser.Lex(); // Eat the '('.
1709 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1710 // Nothing to do here, fall into the code below with the '(' part of the
1711 // memory operand consumed.
1715 // It must be an parenthesized expression, parse it now.
1716 if (getParser().parseParenExpression(Disp, ExprEnd))
1719 // After parsing the base expression we could either have a parenthesized
1720 // memory address or not. If not, return now. If so, eat the (.
1721 if (getLexer().isNot(AsmToken::LParen)) {
1722 // Unless we have a segment register, treat this as an immediate.
1724 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1725 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1733 // If we reached here, then we just ate the ( of the memory operand. Process
1734 // the rest of the memory operand.
1735 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1738 if (getLexer().is(AsmToken::Percent)) {
1739 SMLoc StartLoc, EndLoc;
1740 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1741 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1742 Error(StartLoc, "eiz and riz can only be used as index registers",
1743 SMRange(StartLoc, EndLoc));
1748 if (getLexer().is(AsmToken::Comma)) {
1749 Parser.Lex(); // Eat the comma.
1750 IndexLoc = Parser.getTok().getLoc();
1752 // Following the comma we should have either an index register, or a scale
1753 // value. We don't support the later form, but we want to parse it
1756 // Not that even though it would be completely consistent to support syntax
1757 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1758 if (getLexer().is(AsmToken::Percent)) {
1760 if (ParseRegister(IndexReg, L, L)) return 0;
1762 if (getLexer().isNot(AsmToken::RParen)) {
1763 // Parse the scale amount:
1764 // ::= ',' [scale-expression]
1765 if (getLexer().isNot(AsmToken::Comma)) {
1766 Error(Parser.getTok().getLoc(),
1767 "expected comma in scale expression");
1770 Parser.Lex(); // Eat the comma.
1772 if (getLexer().isNot(AsmToken::RParen)) {
1773 SMLoc Loc = Parser.getTok().getLoc();
1776 if (getParser().parseAbsoluteExpression(ScaleVal)){
1777 Error(Loc, "expected scale expression");
1781 // Validate the scale amount.
1782 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1783 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1786 Scale = (unsigned)ScaleVal;
1789 } else if (getLexer().isNot(AsmToken::RParen)) {
1790 // A scale amount without an index is ignored.
1792 SMLoc Loc = Parser.getTok().getLoc();
1795 if (getParser().parseAbsoluteExpression(Value))
1799 Warning(Loc, "scale factor without index register is ignored");
1804 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1805 if (getLexer().isNot(AsmToken::RParen)) {
1806 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1809 SMLoc MemEnd = Parser.getTok().getEndLoc();
1810 Parser.Lex(); // Eat the ')'.
1812 // If we have both a base register and an index register make sure they are
1813 // both 64-bit or 32-bit registers.
1814 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1815 if (BaseReg != 0 && IndexReg != 0) {
1816 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1817 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1818 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1819 IndexReg != X86::RIZ) {
1820 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1823 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1824 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1825 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1826 IndexReg != X86::EIZ){
1827 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1832 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1837 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1838 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1840 StringRef PatchedName = Name;
1842 // FIXME: Hack to recognize setneb as setne.
1843 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1844 PatchedName != "setb" && PatchedName != "setnb")
1845 PatchedName = PatchedName.substr(0, Name.size()-1);
1847 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1848 const MCExpr *ExtraImmOp = 0;
1849 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1850 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1851 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1852 bool IsVCMP = PatchedName[0] == 'v';
1853 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1854 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1855 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1859 .Case("unord", 0x03)
1864 /* AVX only from here */
1865 .Case("eq_uq", 0x08)
1868 .Case("false", 0x0B)
1869 .Case("neq_oq", 0x0C)
1873 .Case("eq_os", 0x10)
1874 .Case("lt_oq", 0x11)
1875 .Case("le_oq", 0x12)
1876 .Case("unord_s", 0x13)
1877 .Case("neq_us", 0x14)
1878 .Case("nlt_uq", 0x15)
1879 .Case("nle_uq", 0x16)
1880 .Case("ord_s", 0x17)
1881 .Case("eq_us", 0x18)
1882 .Case("nge_uq", 0x19)
1883 .Case("ngt_uq", 0x1A)
1884 .Case("false_os", 0x1B)
1885 .Case("neq_os", 0x1C)
1886 .Case("ge_oq", 0x1D)
1887 .Case("gt_oq", 0x1E)
1888 .Case("true_us", 0x1F)
1890 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1891 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1892 getParser().getContext());
1893 if (PatchedName.endswith("ss")) {
1894 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1895 } else if (PatchedName.endswith("sd")) {
1896 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1897 } else if (PatchedName.endswith("ps")) {
1898 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1900 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1901 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1906 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1908 if (ExtraImmOp && !isParsingIntelSyntax())
1909 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1911 // Determine whether this is an instruction prefix.
1913 Name == "lock" || Name == "rep" ||
1914 Name == "repe" || Name == "repz" ||
1915 Name == "repne" || Name == "repnz" ||
1916 Name == "rex64" || Name == "data16";
1919 // This does the actual operand parsing. Don't parse any more if we have a
1920 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1921 // just want to parse the "lock" as the first instruction and the "incl" as
1923 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1925 // Parse '*' modifier.
1926 if (getLexer().is(AsmToken::Star)) {
1927 SMLoc Loc = Parser.getTok().getLoc();
1928 Operands.push_back(X86Operand::CreateToken("*", Loc));
1929 Parser.Lex(); // Eat the star.
1932 // Read the first operand.
1933 if (X86Operand *Op = ParseOperand())
1934 Operands.push_back(Op);
1936 Parser.eatToEndOfStatement();
1940 while (getLexer().is(AsmToken::Comma)) {
1941 Parser.Lex(); // Eat the comma.
1943 // Parse and remember the operand.
1944 if (X86Operand *Op = ParseOperand())
1945 Operands.push_back(Op);
1947 Parser.eatToEndOfStatement();
1952 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1953 SMLoc Loc = getLexer().getLoc();
1954 Parser.eatToEndOfStatement();
1955 return Error(Loc, "unexpected token in argument list");
1959 if (getLexer().is(AsmToken::EndOfStatement))
1960 Parser.Lex(); // Consume the EndOfStatement
1961 else if (isPrefix && getLexer().is(AsmToken::Slash))
1962 Parser.Lex(); // Consume the prefix separator Slash
1964 if (ExtraImmOp && isParsingIntelSyntax())
1965 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1967 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1968 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1969 // documented form in various unofficial manuals, so a lot of code uses it.
1970 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1971 Operands.size() == 3) {
1972 X86Operand &Op = *(X86Operand*)Operands.back();
1973 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1974 isa<MCConstantExpr>(Op.Mem.Disp) &&
1975 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1976 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1977 SMLoc Loc = Op.getEndLoc();
1978 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1982 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1983 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1984 Operands.size() == 3) {
1985 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1986 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1987 isa<MCConstantExpr>(Op.Mem.Disp) &&
1988 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1989 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1990 SMLoc Loc = Op.getEndLoc();
1991 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1995 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1996 if (Name.startswith("ins") && Operands.size() == 3 &&
1997 (Name == "insb" || Name == "insw" || Name == "insl")) {
1998 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1999 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2000 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
2001 Operands.pop_back();
2002 Operands.pop_back();
2008 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
2009 if (Name.startswith("outs") && Operands.size() == 3 &&
2010 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
2011 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2012 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2013 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
2014 Operands.pop_back();
2015 Operands.pop_back();
2021 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2022 if (Name.startswith("movs") && Operands.size() == 3 &&
2023 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2024 (is64BitMode() && Name == "movsq"))) {
2025 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2026 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2027 if (isSrcOp(Op) && isDstOp(Op2)) {
2028 Operands.pop_back();
2029 Operands.pop_back();
2034 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2035 if (Name.startswith("lods") && Operands.size() == 3 &&
2036 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2037 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2038 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2039 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2040 if (isSrcOp(*Op1) && Op2->isReg()) {
2042 unsigned reg = Op2->getReg();
2043 bool isLods = Name == "lods";
2044 if (reg == X86::AL && (isLods || Name == "lodsb"))
2046 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2048 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2050 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2055 Operands.pop_back();
2056 Operands.pop_back();
2060 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2064 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2065 if (Name.startswith("stos") && Operands.size() == 3 &&
2066 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2067 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2068 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2069 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2070 if (isDstOp(*Op2) && Op1->isReg()) {
2072 unsigned reg = Op1->getReg();
2073 bool isStos = Name == "stos";
2074 if (reg == X86::AL && (isStos || Name == "stosb"))
2076 else if (reg == X86::AX && (isStos || Name == "stosw"))
2078 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2080 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2085 Operands.pop_back();
2086 Operands.pop_back();
2090 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2095 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2097 if ((Name.startswith("shr") || Name.startswith("sar") ||
2098 Name.startswith("shl") || Name.startswith("sal") ||
2099 Name.startswith("rcl") || Name.startswith("rcr") ||
2100 Name.startswith("rol") || Name.startswith("ror")) &&
2101 Operands.size() == 3) {
2102 if (isParsingIntelSyntax()) {
2104 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2105 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2106 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2108 Operands.pop_back();
2111 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2112 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2113 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2115 Operands.erase(Operands.begin() + 1);
2120 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2121 // instalias with an immediate operand yet.
2122 if (Name == "int" && Operands.size() == 2) {
2123 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2124 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2125 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2127 Operands.erase(Operands.begin() + 1);
2128 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2135 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2138 TmpInst.setOpcode(Opcode);
2140 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2141 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2142 TmpInst.addOperand(Inst.getOperand(0));
2147 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2148 bool isCmp = false) {
2149 if (!Inst.getOperand(0).isImm() ||
2150 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2153 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2156 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2157 bool isCmp = false) {
2158 if (!Inst.getOperand(0).isImm() ||
2159 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2162 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2165 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2166 bool isCmp = false) {
2167 if (!Inst.getOperand(0).isImm() ||
2168 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2171 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2175 processInstruction(MCInst &Inst,
2176 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2177 switch (Inst.getOpcode()) {
2178 default: return false;
2179 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2180 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2181 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2182 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2183 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2184 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2185 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2186 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2187 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2188 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2189 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2190 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2191 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2192 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2193 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2194 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2195 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2196 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2197 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2198 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2199 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2200 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2201 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2202 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2206 static const char *getSubtargetFeatureName(unsigned Val);
2208 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2209 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2210 MCStreamer &Out, unsigned &ErrorInfo,
2211 bool MatchingInlineAsm) {
2212 assert(!Operands.empty() && "Unexpect empty operand list!");
2213 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2214 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2215 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
2217 // First, handle aliases that expand to multiple instructions.
2218 // FIXME: This should be replaced with a real .td file alias mechanism.
2219 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2221 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2222 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2223 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2224 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2226 Inst.setOpcode(X86::WAIT);
2228 if (!MatchingInlineAsm)
2229 Out.EmitInstruction(Inst);
2232 StringSwitch<const char*>(Op->getToken())
2233 .Case("finit", "fninit")
2234 .Case("fsave", "fnsave")
2235 .Case("fstcw", "fnstcw")
2236 .Case("fstcww", "fnstcw")
2237 .Case("fstenv", "fnstenv")
2238 .Case("fstsw", "fnstsw")
2239 .Case("fstsww", "fnstsw")
2240 .Case("fclex", "fnclex")
2242 assert(Repl && "Unknown wait-prefixed instruction");
2244 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2247 bool WasOriginallyInvalidOperand = false;
2250 // First, try a direct match.
2251 switch (MatchInstructionImpl(Operands, Inst,
2252 ErrorInfo, MatchingInlineAsm,
2253 isParsingIntelSyntax())) {
2256 // Some instructions need post-processing to, for example, tweak which
2257 // encoding is selected. Loop on it while changes happen so the
2258 // individual transformations can chain off each other.
2259 if (!MatchingInlineAsm)
2260 while (processInstruction(Inst, Operands))
2264 if (!MatchingInlineAsm)
2265 Out.EmitInstruction(Inst);
2266 Opcode = Inst.getOpcode();
2268 case Match_MissingFeature: {
2269 assert(ErrorInfo && "Unknown missing feature!");
2270 // Special case the error message for the very common case where only
2271 // a single subtarget feature is missing.
2272 std::string Msg = "instruction requires:";
2274 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2275 if (ErrorInfo & Mask) {
2277 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2281 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2283 case Match_InvalidOperand:
2284 WasOriginallyInvalidOperand = true;
2286 case Match_MnemonicFail:
2290 // FIXME: Ideally, we would only attempt suffix matches for things which are
2291 // valid prefixes, and we could just infer the right unambiguous
2292 // type. However, that requires substantially more matcher support than the
2295 // Change the operand to point to a temporary token.
2296 StringRef Base = Op->getToken();
2297 SmallString<16> Tmp;
2300 Op->setTokenValue(Tmp.str());
2302 // If this instruction starts with an 'f', then it is a floating point stack
2303 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2304 // 80-bit floating point, which use the suffixes s,l,t respectively.
2306 // Otherwise, we assume that this may be an integer instruction, which comes
2307 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2308 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2310 // Check for the various suffix matches.
2311 Tmp[Base.size()] = Suffixes[0];
2312 unsigned ErrorInfoIgnore;
2313 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2314 unsigned Match1, Match2, Match3, Match4;
2316 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2317 isParsingIntelSyntax());
2318 // If this returned as a missing feature failure, remember that.
2319 if (Match1 == Match_MissingFeature)
2320 ErrorInfoMissingFeature = ErrorInfoIgnore;
2321 Tmp[Base.size()] = Suffixes[1];
2322 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2323 isParsingIntelSyntax());
2324 // If this returned as a missing feature failure, remember that.
2325 if (Match2 == Match_MissingFeature)
2326 ErrorInfoMissingFeature = ErrorInfoIgnore;
2327 Tmp[Base.size()] = Suffixes[2];
2328 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2329 isParsingIntelSyntax());
2330 // If this returned as a missing feature failure, remember that.
2331 if (Match3 == Match_MissingFeature)
2332 ErrorInfoMissingFeature = ErrorInfoIgnore;
2333 Tmp[Base.size()] = Suffixes[3];
2334 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2335 isParsingIntelSyntax());
2336 // If this returned as a missing feature failure, remember that.
2337 if (Match4 == Match_MissingFeature)
2338 ErrorInfoMissingFeature = ErrorInfoIgnore;
2340 // Restore the old token.
2341 Op->setTokenValue(Base);
2343 // If exactly one matched, then we treat that as a successful match (and the
2344 // instruction will already have been filled in correctly, since the failing
2345 // matches won't have modified it).
2346 unsigned NumSuccessfulMatches =
2347 (Match1 == Match_Success) + (Match2 == Match_Success) +
2348 (Match3 == Match_Success) + (Match4 == Match_Success);
2349 if (NumSuccessfulMatches == 1) {
2351 if (!MatchingInlineAsm)
2352 Out.EmitInstruction(Inst);
2353 Opcode = Inst.getOpcode();
2357 // Otherwise, the match failed, try to produce a decent error message.
2359 // If we had multiple suffix matches, then identify this as an ambiguous
2361 if (NumSuccessfulMatches > 1) {
2363 unsigned NumMatches = 0;
2364 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2365 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2366 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2367 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2369 SmallString<126> Msg;
2370 raw_svector_ostream OS(Msg);
2371 OS << "ambiguous instructions require an explicit suffix (could be ";
2372 for (unsigned i = 0; i != NumMatches; ++i) {
2375 if (i + 1 == NumMatches)
2377 OS << "'" << Base << MatchChars[i] << "'";
2380 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2384 // Okay, we know that none of the variants matched successfully.
2386 // If all of the instructions reported an invalid mnemonic, then the original
2387 // mnemonic was invalid.
2388 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2389 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2390 if (!WasOriginallyInvalidOperand) {
2391 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2393 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2394 Ranges, MatchingInlineAsm);
2397 // Recover location info for the operand if we know which was the problem.
2398 if (ErrorInfo != ~0U) {
2399 if (ErrorInfo >= Operands.size())
2400 return Error(IDLoc, "too few operands for instruction",
2401 EmptyRanges, MatchingInlineAsm);
2403 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2404 if (Operand->getStartLoc().isValid()) {
2405 SMRange OperandRange = Operand->getLocRange();
2406 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2407 OperandRange, MatchingInlineAsm);
2411 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2415 // If one instruction matched with a missing feature, report this as a
2417 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2418 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2419 std::string Msg = "instruction requires:";
2421 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2422 if (ErrorInfoMissingFeature & Mask) {
2424 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2428 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2431 // If one instruction matched with an invalid operand, report this as an
2433 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2434 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2435 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2440 // If all of these were an outright failure, report it in a useless way.
2441 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2442 EmptyRanges, MatchingInlineAsm);
2447 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2448 StringRef IDVal = DirectiveID.getIdentifier();
2449 if (IDVal == ".word")
2450 return ParseDirectiveWord(2, DirectiveID.getLoc());
2451 else if (IDVal.startswith(".code"))
2452 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2453 else if (IDVal.startswith(".att_syntax")) {
2454 getParser().setAssemblerDialect(0);
2456 } else if (IDVal.startswith(".intel_syntax")) {
2457 getParser().setAssemblerDialect(1);
2458 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2459 if(Parser.getTok().getString() == "noprefix") {
2460 // FIXME : Handle noprefix
2470 /// ParseDirectiveWord
2471 /// ::= .word [ expression (, expression)* ]
2472 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2473 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2475 const MCExpr *Value;
2476 if (getParser().parseExpression(Value))
2479 getParser().getStreamer().EmitValue(Value, Size);
2481 if (getLexer().is(AsmToken::EndOfStatement))
2484 // FIXME: Improve diagnostic.
2485 if (getLexer().isNot(AsmToken::Comma))
2486 return Error(L, "unexpected token in directive");
2495 /// ParseDirectiveCode
2496 /// ::= .code32 | .code64
2497 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2498 if (IDVal == ".code32") {
2500 if (is64BitMode()) {
2502 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2504 } else if (IDVal == ".code64") {
2506 if (!is64BitMode()) {
2508 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2511 return Error(L, "unexpected directive " + IDVal);
2517 // Force static initialization.
2518 extern "C" void LLVMInitializeX86AsmParser() {
2519 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2520 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2523 #define GET_REGISTER_MATCHER
2524 #define GET_MATCHER_IMPLEMENTATION
2525 #define GET_SUBTARGET_FEATURE_NAME
2526 #include "X86GenAsmMatcher.inc"