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;
209 InlineAsmIdentifierInfo Info;
211 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
212 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
213 Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac),
214 AddImmPrefix(addimmprefix) { Info.clear(); }
216 unsigned getBaseReg() { return BaseReg; }
217 unsigned getIndexReg() { return IndexReg; }
218 unsigned getScale() { return Scale; }
219 const MCExpr *getSym() { return Sym; }
220 StringRef getSymName() { return SymName; }
221 int64_t getImm() { return Imm + IC.execute(); }
222 bool isValidEndState() { return State == IES_RBRAC; }
223 bool getStopOnLBrac() { return StopOnLBrac; }
224 bool getAddImmPrefix() { return AddImmPrefix; }
225 bool hadError() { return State == IES_ERROR; }
227 InlineAsmIdentifierInfo &getIdentifierInfo() {
232 IntelExprState CurrState = State;
241 IC.pushOperator(IC_PLUS);
242 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
243 // If we already have a BaseReg, then assume this is the IndexReg with
248 assert (!IndexReg && "BaseReg/IndexReg already set!");
255 PrevState = CurrState;
258 IntelExprState CurrState = State;
273 // Only push the minus operator if it is not a unary operator.
274 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
275 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
276 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
277 IC.pushOperator(IC_MINUS);
278 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
279 // If we already have a BaseReg, then assume this is the IndexReg with
284 assert (!IndexReg && "BaseReg/IndexReg already set!");
291 PrevState = CurrState;
293 void onRegister(unsigned Reg) {
294 IntelExprState CurrState = State;
301 State = IES_REGISTER;
303 IC.pushOperand(IC_REGISTER);
306 // Index Register - Scale * Register
307 if (PrevState == IES_INTEGER) {
308 assert (!IndexReg && "IndexReg already set!");
309 State = IES_REGISTER;
311 // Get the scale and replace the 'Scale * Register' with '0'.
312 Scale = IC.popOperand();
313 IC.pushOperand(IC_IMM);
320 PrevState = CurrState;
322 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
332 SymName = SymRefName;
333 IC.pushOperand(IC_IMM);
337 void onInteger(int64_t TmpInt) {
338 IntelExprState CurrState = State;
349 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
350 // Index Register - Register * Scale
351 assert (!IndexReg && "IndexReg already set!");
354 // Get the scale and replace the 'Register * Scale' with '0'.
356 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
357 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
358 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
359 CurrState == IES_MINUS) {
360 // Unary minus. No need to pop the minus operand because it was never
362 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
364 IC.pushOperand(IC_IMM, TmpInt);
368 PrevState = CurrState;
379 State = IES_MULTIPLY;
380 IC.pushOperator(IC_MULTIPLY);
393 IC.pushOperator(IC_DIVIDE);
405 IC.pushOperator(IC_PLUS);
410 IntelExprState CurrState = State;
419 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
420 // If we already have a BaseReg, then assume this is the IndexReg with
425 assert (!IndexReg && "BaseReg/IndexReg already set!");
432 PrevState = CurrState;
435 IntelExprState CurrState = State;
445 // FIXME: We don't handle this type of unary minus, yet.
446 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
447 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
448 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
449 CurrState == IES_MINUS) {
454 IC.pushOperator(IC_LPAREN);
457 PrevState = CurrState;
469 IC.pushOperator(IC_RPAREN);
475 MCAsmParser &getParser() const { return Parser; }
477 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
479 bool Error(SMLoc L, const Twine &Msg,
480 ArrayRef<SMRange> Ranges = ArrayRef<SMRange>(),
481 bool MatchingInlineAsm = false) {
482 if (MatchingInlineAsm) return true;
483 return Parser.Error(L, Msg, Ranges);
486 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
491 X86Operand *ParseOperand();
492 X86Operand *ParseATTOperand();
493 X86Operand *ParseIntelOperand();
494 X86Operand *ParseIntelOffsetOfOperator();
495 X86Operand *ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
496 X86Operand *ParseIntelOperator(unsigned OpKind);
497 X86Operand *ParseIntelMemOperand(unsigned SegReg, int64_t ImmDisp,
499 X86Operand *ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
500 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
501 int64_t ImmDisp, unsigned Size);
502 X86Operand *ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
503 InlineAsmIdentifierInfo &Info, SMLoc &End);
505 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
507 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
508 unsigned BaseReg, unsigned IndexReg,
509 unsigned Scale, SMLoc Start, SMLoc End,
510 unsigned Size, StringRef Identifier,
511 InlineAsmIdentifierInfo &Info);
513 bool ParseDirectiveWord(unsigned Size, SMLoc L);
514 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
516 bool processInstruction(MCInst &Inst,
517 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
519 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
520 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
521 MCStreamer &Out, unsigned &ErrorInfo,
522 bool MatchingInlineAsm);
524 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
525 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
526 bool isSrcOp(X86Operand &Op);
528 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
529 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
530 bool isDstOp(X86Operand &Op);
532 bool is64BitMode() const {
533 // FIXME: Can tablegen auto-generate this?
534 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
537 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
538 setAvailableFeatures(FB);
541 bool isParsingIntelSyntax() {
542 return getParser().getAssemblerDialect();
545 /// @name Auto-generated Matcher Functions
548 #define GET_ASSEMBLER_HEADER
549 #include "X86GenAsmMatcher.inc"
554 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
555 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
557 // Initialize the set of available features.
558 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
560 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
562 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
564 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
566 virtual bool ParseDirective(AsmToken DirectiveID);
568 } // end anonymous namespace
570 /// @name Auto-generated Match Functions
573 static unsigned MatchRegisterName(StringRef Name);
577 static bool isImmSExti16i8Value(uint64_t Value) {
578 return (( Value <= 0x000000000000007FULL)||
579 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
580 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
583 static bool isImmSExti32i8Value(uint64_t Value) {
584 return (( Value <= 0x000000000000007FULL)||
585 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
586 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
589 static bool isImmZExtu32u8Value(uint64_t Value) {
590 return (Value <= 0x00000000000000FFULL);
593 static bool isImmSExti64i8Value(uint64_t Value) {
594 return (( Value <= 0x000000000000007FULL)||
595 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
598 static bool isImmSExti64i32Value(uint64_t Value) {
599 return (( Value <= 0x000000007FFFFFFFULL)||
600 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
604 /// X86Operand - Instances of this class represent a parsed X86 machine
606 struct X86Operand : public MCParsedAsmOperand {
614 SMLoc StartLoc, EndLoc;
648 X86Operand(KindTy K, SMLoc Start, SMLoc End)
649 : Kind(K), StartLoc(Start), EndLoc(End) {}
651 StringRef getSymName() { return SymName; }
653 /// getStartLoc - Get the location of the first token of this operand.
654 SMLoc getStartLoc() const { return StartLoc; }
655 /// getEndLoc - Get the location of the last token of this operand.
656 SMLoc getEndLoc() const { return EndLoc; }
657 /// getLocRange - Get the range between the first and last token of this
659 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
660 /// getOffsetOfLoc - Get the location of the offset operator.
661 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
663 virtual void print(raw_ostream &OS) const {}
665 StringRef getToken() const {
666 assert(Kind == Token && "Invalid access!");
667 return StringRef(Tok.Data, Tok.Length);
669 void setTokenValue(StringRef Value) {
670 assert(Kind == Token && "Invalid access!");
671 Tok.Data = Value.data();
672 Tok.Length = Value.size();
675 unsigned getReg() const {
676 assert(Kind == Register && "Invalid access!");
680 const MCExpr *getImm() const {
681 assert(Kind == Immediate && "Invalid access!");
685 const MCExpr *getMemDisp() const {
686 assert(Kind == Memory && "Invalid access!");
689 unsigned getMemSegReg() const {
690 assert(Kind == Memory && "Invalid access!");
693 unsigned getMemBaseReg() const {
694 assert(Kind == Memory && "Invalid access!");
697 unsigned getMemIndexReg() const {
698 assert(Kind == Memory && "Invalid access!");
701 unsigned getMemScale() const {
702 assert(Kind == Memory && "Invalid access!");
706 bool isToken() const {return Kind == Token; }
708 bool isImm() const { return Kind == Immediate; }
710 bool isImmSExti16i8() const {
714 // If this isn't a constant expr, just assume it fits and let relaxation
716 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
720 // Otherwise, check the value is in a range that makes sense for this
722 return isImmSExti16i8Value(CE->getValue());
724 bool isImmSExti32i8() const {
728 // If this isn't a constant expr, just assume it fits and let relaxation
730 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
734 // Otherwise, check the value is in a range that makes sense for this
736 return isImmSExti32i8Value(CE->getValue());
738 bool isImmZExtu32u8() const {
742 // If this isn't a constant expr, just assume it fits and let relaxation
744 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
748 // Otherwise, check the value is in a range that makes sense for this
750 return isImmZExtu32u8Value(CE->getValue());
752 bool isImmSExti64i8() const {
756 // If this isn't a constant expr, just assume it fits and let relaxation
758 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
762 // Otherwise, check the value is in a range that makes sense for this
764 return isImmSExti64i8Value(CE->getValue());
766 bool isImmSExti64i32() const {
770 // If this isn't a constant expr, just assume it fits and let relaxation
772 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
776 // Otherwise, check the value is in a range that makes sense for this
778 return isImmSExti64i32Value(CE->getValue());
781 bool isOffsetOf() const {
782 return OffsetOfLoc.getPointer();
785 bool needAddressOf() const {
789 bool isMem() const { return Kind == Memory; }
790 bool isMem8() const {
791 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
793 bool isMem16() const {
794 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
796 bool isMem32() const {
797 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
799 bool isMem64() const {
800 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
802 bool isMem80() const {
803 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
805 bool isMem128() const {
806 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
808 bool isMem256() const {
809 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
812 bool isMemVX32() const {
813 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
814 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
816 bool isMemVY32() const {
817 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
818 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
820 bool isMemVX64() const {
821 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
822 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
824 bool isMemVY64() const {
825 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
826 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
829 bool isAbsMem() const {
830 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
831 !getMemIndexReg() && getMemScale() == 1;
834 bool isReg() const { return Kind == Register; }
836 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
837 // Add as immediates when possible.
838 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
839 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
841 Inst.addOperand(MCOperand::CreateExpr(Expr));
844 void addRegOperands(MCInst &Inst, unsigned N) const {
845 assert(N == 1 && "Invalid number of operands!");
846 Inst.addOperand(MCOperand::CreateReg(getReg()));
849 void addImmOperands(MCInst &Inst, unsigned N) const {
850 assert(N == 1 && "Invalid number of operands!");
851 addExpr(Inst, getImm());
854 void addMem8Operands(MCInst &Inst, unsigned N) const {
855 addMemOperands(Inst, N);
857 void addMem16Operands(MCInst &Inst, unsigned N) const {
858 addMemOperands(Inst, N);
860 void addMem32Operands(MCInst &Inst, unsigned N) const {
861 addMemOperands(Inst, N);
863 void addMem64Operands(MCInst &Inst, unsigned N) const {
864 addMemOperands(Inst, N);
866 void addMem80Operands(MCInst &Inst, unsigned N) const {
867 addMemOperands(Inst, N);
869 void addMem128Operands(MCInst &Inst, unsigned N) const {
870 addMemOperands(Inst, N);
872 void addMem256Operands(MCInst &Inst, unsigned N) const {
873 addMemOperands(Inst, N);
875 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
876 addMemOperands(Inst, N);
878 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
879 addMemOperands(Inst, N);
881 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
882 addMemOperands(Inst, N);
884 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
885 addMemOperands(Inst, N);
888 void addMemOperands(MCInst &Inst, unsigned N) const {
889 assert((N == 5) && "Invalid number of operands!");
890 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
891 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
892 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
893 addExpr(Inst, getMemDisp());
894 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
897 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
898 assert((N == 1) && "Invalid number of operands!");
899 // Add as immediates when possible.
900 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
901 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
903 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
906 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
907 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
908 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
909 Res->Tok.Data = Str.data();
910 Res->Tok.Length = Str.size();
914 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
915 bool AddressOf = false,
916 SMLoc OffsetOfLoc = SMLoc(),
917 StringRef SymName = StringRef()) {
918 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
919 Res->Reg.RegNo = RegNo;
920 Res->AddressOf = AddressOf;
921 Res->OffsetOfLoc = OffsetOfLoc;
922 Res->SymName = SymName;
926 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
927 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
932 /// Create an absolute memory operand.
933 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
935 StringRef SymName = StringRef()) {
936 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
938 Res->Mem.Disp = Disp;
939 Res->Mem.BaseReg = 0;
940 Res->Mem.IndexReg = 0;
942 Res->Mem.Size = Size;
943 Res->SymName = SymName;
944 Res->AddressOf = false;
948 /// Create a generalized memory operand.
949 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
950 unsigned BaseReg, unsigned IndexReg,
951 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
953 StringRef SymName = StringRef()) {
954 // We should never just have a displacement, that should be parsed as an
955 // absolute memory operand.
956 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
958 // The scale should always be one of {1,2,4,8}.
959 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
961 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
962 Res->Mem.SegReg = SegReg;
963 Res->Mem.Disp = Disp;
964 Res->Mem.BaseReg = BaseReg;
965 Res->Mem.IndexReg = IndexReg;
966 Res->Mem.Scale = Scale;
967 Res->Mem.Size = Size;
968 Res->SymName = SymName;
969 Res->AddressOf = false;
974 } // end anonymous namespace.
976 bool X86AsmParser::isSrcOp(X86Operand &Op) {
977 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
979 return (Op.isMem() &&
980 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
981 isa<MCConstantExpr>(Op.Mem.Disp) &&
982 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
983 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
986 bool X86AsmParser::isDstOp(X86Operand &Op) {
987 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
990 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
991 isa<MCConstantExpr>(Op.Mem.Disp) &&
992 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
993 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
996 bool X86AsmParser::ParseRegister(unsigned &RegNo,
997 SMLoc &StartLoc, SMLoc &EndLoc) {
999 const AsmToken &PercentTok = Parser.getTok();
1000 StartLoc = PercentTok.getLoc();
1002 // If we encounter a %, ignore it. This code handles registers with and
1003 // without the prefix, unprefixed registers can occur in cfi directives.
1004 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1005 Parser.Lex(); // Eat percent token.
1007 const AsmToken &Tok = Parser.getTok();
1008 EndLoc = Tok.getEndLoc();
1010 if (Tok.isNot(AsmToken::Identifier)) {
1011 if (isParsingIntelSyntax()) return true;
1012 return Error(StartLoc, "invalid register name",
1013 SMRange(StartLoc, EndLoc));
1016 RegNo = MatchRegisterName(Tok.getString());
1018 // If the match failed, try the register name as lowercase.
1020 RegNo = MatchRegisterName(Tok.getString().lower());
1022 if (!is64BitMode()) {
1023 // FIXME: This should be done using Requires<In32BitMode> and
1024 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1026 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1028 if (RegNo == X86::RIZ ||
1029 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1030 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1031 X86II::isX86_64ExtendedReg(RegNo))
1032 return Error(StartLoc, "register %"
1033 + Tok.getString() + " is only available in 64-bit mode",
1034 SMRange(StartLoc, EndLoc));
1037 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1038 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1040 Parser.Lex(); // Eat 'st'
1042 // Check to see if we have '(4)' after %st.
1043 if (getLexer().isNot(AsmToken::LParen))
1048 const AsmToken &IntTok = Parser.getTok();
1049 if (IntTok.isNot(AsmToken::Integer))
1050 return Error(IntTok.getLoc(), "expected stack index");
1051 switch (IntTok.getIntVal()) {
1052 case 0: RegNo = X86::ST0; break;
1053 case 1: RegNo = X86::ST1; break;
1054 case 2: RegNo = X86::ST2; break;
1055 case 3: RegNo = X86::ST3; break;
1056 case 4: RegNo = X86::ST4; break;
1057 case 5: RegNo = X86::ST5; break;
1058 case 6: RegNo = X86::ST6; break;
1059 case 7: RegNo = X86::ST7; break;
1060 default: return Error(IntTok.getLoc(), "invalid stack index");
1063 if (getParser().Lex().isNot(AsmToken::RParen))
1064 return Error(Parser.getTok().getLoc(), "expected ')'");
1066 EndLoc = Parser.getTok().getEndLoc();
1067 Parser.Lex(); // Eat ')'
1071 EndLoc = Parser.getTok().getEndLoc();
1073 // If this is "db[0-7]", match it as an alias
1075 if (RegNo == 0 && Tok.getString().size() == 3 &&
1076 Tok.getString().startswith("db")) {
1077 switch (Tok.getString()[2]) {
1078 case '0': RegNo = X86::DR0; break;
1079 case '1': RegNo = X86::DR1; break;
1080 case '2': RegNo = X86::DR2; break;
1081 case '3': RegNo = X86::DR3; break;
1082 case '4': RegNo = X86::DR4; break;
1083 case '5': RegNo = X86::DR5; break;
1084 case '6': RegNo = X86::DR6; break;
1085 case '7': RegNo = X86::DR7; break;
1089 EndLoc = Parser.getTok().getEndLoc();
1090 Parser.Lex(); // Eat it.
1096 if (isParsingIntelSyntax()) return true;
1097 return Error(StartLoc, "invalid register name",
1098 SMRange(StartLoc, EndLoc));
1101 Parser.Lex(); // Eat identifier token.
1105 X86Operand *X86AsmParser::ParseOperand() {
1106 if (isParsingIntelSyntax())
1107 return ParseIntelOperand();
1108 return ParseATTOperand();
1111 /// getIntelMemOperandSize - Return intel memory operand size.
1112 static unsigned getIntelMemOperandSize(StringRef OpStr) {
1113 unsigned Size = StringSwitch<unsigned>(OpStr)
1114 .Cases("BYTE", "byte", 8)
1115 .Cases("WORD", "word", 16)
1116 .Cases("DWORD", "dword", 32)
1117 .Cases("QWORD", "qword", 64)
1118 .Cases("XWORD", "xword", 80)
1119 .Cases("XMMWORD", "xmmword", 128)
1120 .Cases("YMMWORD", "ymmword", 256)
1126 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1127 unsigned BaseReg, unsigned IndexReg,
1128 unsigned Scale, SMLoc Start, SMLoc End,
1129 unsigned Size, StringRef Identifier,
1130 InlineAsmIdentifierInfo &Info){
1133 if (const MCSymbolRefExpr *SymRef = dyn_cast<MCSymbolRefExpr>(Disp)) {
1134 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1135 // reference. We need an 'r' constraint here, so we need to create register
1136 // operand to ensure proper matching. Just pick a GPR based on the size of
1138 if (!Info.IsVarDecl) {
1139 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1140 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1141 SMLoc(), Identifier);
1144 Size = Info.Type * 8; // Size is in terms of bits in this context.
1146 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1151 // When parsing inline assembly we set the base register to a non-zero value
1152 // if we don't know the actual value at this time. This is necessary to
1153 // get the matching correct in some cases.
1154 BaseReg = BaseReg ? BaseReg : 1;
1155 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1156 End, Size, Identifier);
1160 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1161 StringRef SymName, int64_t ImmDisp,
1162 int64_t FinalImmDisp, SMLoc &BracLoc,
1163 SMLoc &StartInBrac, SMLoc &End) {
1164 // Remove the '[' and ']' from the IR string.
1165 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1166 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1168 // If ImmDisp is non-zero, then we parsed a displacement before the
1169 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1170 // If ImmDisp doesn't match the displacement computed by the state machine
1171 // then we have an additional displacement in the bracketed expression.
1172 if (ImmDisp != FinalImmDisp) {
1174 // We have an immediate displacement before the bracketed expression.
1175 // Adjust this to match the final immediate displacement.
1177 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1178 E = AsmRewrites->end(); I != E; ++I) {
1179 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1181 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1182 assert (!Found && "ImmDisp already rewritten.");
1183 (*I).Kind = AOK_Imm;
1184 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1185 (*I).Val = FinalImmDisp;
1190 assert (Found && "Unable to rewrite ImmDisp.");
1192 // We have a symbolic and an immediate displacement, but no displacement
1193 // before the bracketed expression. Put the immediate displacement
1194 // before the bracketed expression.
1195 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1198 // Remove all the ImmPrefix rewrites within the brackets.
1199 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1200 E = AsmRewrites->end(); I != E; ++I) {
1201 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1203 if ((*I).Kind == AOK_ImmPrefix)
1204 (*I).Kind = AOK_Delete;
1206 const char *SymLocPtr = SymName.data();
1207 // Skip everything before the symbol.
1208 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1209 assert(Len > 0 && "Expected a non-negative length.");
1210 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1212 // Skip everything after the symbol.
1213 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1214 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1215 assert(Len > 0 && "Expected a non-negative length.");
1216 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1221 X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1222 const AsmToken &Tok = Parser.getTok();
1226 bool UpdateLocLex = true;
1228 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1229 // identifier. Don't try an parse it as a register.
1230 if (Tok.getString().startswith("."))
1233 // If we're parsing an immediate expression, we don't expect a '['.
1234 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1237 switch (getLexer().getKind()) {
1239 if (SM.isValidEndState()) {
1243 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1245 case AsmToken::EndOfStatement: {
1249 case AsmToken::Identifier: {
1250 // This could be a register or a symbolic displacement.
1253 SMLoc IdentLoc = Tok.getLoc();
1254 StringRef Identifier = Tok.getString();
1255 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1256 SM.onRegister(TmpReg);
1257 UpdateLocLex = false;
1260 if (!isParsingInlineAsm()) {
1261 if (getParser().parsePrimaryExpr(Val, End))
1262 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1264 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1265 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info, 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 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1357 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1358 End, Size, SM.getSymName(), Info);
1361 // Inline assembly may use variable names with namespace alias qualifiers.
1362 X86Operand *X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1363 StringRef &Identifier,
1364 InlineAsmIdentifierInfo &Info,
1366 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1369 StringRef LineBuf(Identifier.data());
1370 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info);
1371 unsigned BufLen = LineBuf.size();
1372 assert (BufLen && "Expected a non-zero length identifier.");
1374 // Advance the token stream based on what the frontend parsed.
1375 const AsmToken &Tok = Parser.getTok();
1376 AsmToken IdentEnd = Tok;
1377 while (BufLen > 0) {
1379 BufLen -= Tok.getString().size();
1380 getLexer().Lex(); // Consume the token.
1383 return ErrorOperand(IdentEnd.getLoc(),
1384 "Frontend parser mismatch with asm lexer!");
1385 End = IdentEnd.getEndLoc();
1387 // Create the symbol reference.
1388 Identifier = LineBuf;
1389 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1390 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1391 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1395 /// ParseIntelMemOperand - Parse intel style memory operand.
1396 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg,
1399 const AsmToken &Tok = Parser.getTok();
1402 unsigned Size = getIntelMemOperandSize(Tok.getString());
1404 Parser.Lex(); // Eat operand size (e.g., byte, word).
1405 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1406 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1407 Parser.Lex(); // Eat ptr.
1410 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1411 if (getLexer().is(AsmToken::Integer)) {
1412 if (isParsingInlineAsm())
1413 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1415 int64_t ImmDisp = Tok.getIntVal();
1416 Parser.Lex(); // Eat the integer.
1417 if (getLexer().isNot(AsmToken::LBrac))
1418 return ErrorOperand(Start, "Expected '[' token!");
1419 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1422 if (getLexer().is(AsmToken::LBrac))
1423 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1425 if (!ParseRegister(SegReg, Start, End)) {
1426 // Handel SegReg : [ ... ]
1427 if (getLexer().isNot(AsmToken::Colon))
1428 return ErrorOperand(Start, "Expected ':' token!");
1429 Parser.Lex(); // Eat :
1430 if (getLexer().isNot(AsmToken::LBrac))
1431 return ErrorOperand(Start, "Expected '[' token!");
1432 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1436 if (!isParsingInlineAsm()) {
1437 if (getParser().parsePrimaryExpr(Val, End))
1438 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1440 return X86Operand::CreateMem(Val, Start, End, Size);
1443 InlineAsmIdentifierInfo Info;
1444 StringRef Identifier = Tok.getString();
1445 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info, End))
1447 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1448 /*Scale=*/1, Start, End, Size, Identifier, Info);
1451 /// Parse the '.' operator.
1452 X86Operand *X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1453 const MCExpr *&NewDisp) {
1454 const AsmToken &Tok = Parser.getTok();
1455 int64_t OrigDispVal, DotDispVal;
1457 // FIXME: Handle non-constant expressions.
1458 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1459 OrigDispVal = OrigDisp->getValue();
1461 return ErrorOperand(Tok.getLoc(), "Non-constant offsets are not supported!");
1464 StringRef DotDispStr = Tok.getString().drop_front(1);
1466 // .Imm gets lexed as a real.
1467 if (Tok.is(AsmToken::Real)) {
1469 DotDispStr.getAsInteger(10, DotDisp);
1470 DotDispVal = DotDisp.getZExtValue();
1471 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1473 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1474 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1476 return ErrorOperand(Tok.getLoc(), "Unable to lookup field reference!");
1477 DotDispVal = DotDisp;
1479 return ErrorOperand(Tok.getLoc(), "Unexpected token type!");
1481 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1482 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1483 unsigned Len = DotDispStr.size();
1484 unsigned Val = OrigDispVal + DotDispVal;
1485 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1489 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1493 /// Parse the 'offset' operator. This operator is used to specify the
1494 /// location rather then the content of a variable.
1495 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1496 const AsmToken &Tok = Parser.getTok();
1497 SMLoc OffsetOfLoc = Tok.getLoc();
1498 Parser.Lex(); // Eat offset.
1501 InlineAsmIdentifierInfo Info;
1502 SMLoc Start = Tok.getLoc(), End;
1503 StringRef Identifier = Tok.getString();
1504 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info, End))
1507 // Don't emit the offset operator.
1508 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1510 // The offset operator will have an 'r' constraint, thus we need to create
1511 // register operand to ensure proper matching. Just pick a GPR based on
1512 // the size of a pointer.
1513 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1514 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1515 OffsetOfLoc, Identifier);
1518 enum IntelOperatorKind {
1524 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1525 /// returns the number of elements in an array. It returns the value 1 for
1526 /// non-array variables. The SIZE operator returns the size of a C or C++
1527 /// variable. A variable's size is the product of its LENGTH and TYPE. The
1528 /// TYPE operator returns the size of a C or C++ type or variable. If the
1529 /// variable is an array, TYPE returns the size of a single element.
1530 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1531 const AsmToken &Tok = Parser.getTok();
1532 SMLoc TypeLoc = Tok.getLoc();
1533 Parser.Lex(); // Eat operator.
1535 const MCExpr *Val = 0;
1536 InlineAsmIdentifierInfo Info;
1537 SMLoc Start = Tok.getLoc(), End;
1538 StringRef Identifier = Tok.getString();
1539 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info, End))
1544 default: llvm_unreachable("Unexpected operand kind!");
1545 case IOK_LENGTH: CVal = Info.Length; break;
1546 case IOK_SIZE: CVal = Info.Size; break;
1547 case IOK_TYPE: CVal = Info.Type; break;
1550 // Rewrite the type operator and the C or C++ type or variable in terms of an
1551 // immediate. E.g. TYPE foo -> $$4
1552 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1553 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1555 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1556 return X86Operand::CreateImm(Imm, Start, End);
1559 X86Operand *X86AsmParser::ParseIntelOperand() {
1560 const AsmToken &Tok = Parser.getTok();
1561 SMLoc Start = Tok.getLoc(), End;
1563 // Offset, length, type and size operators.
1564 if (isParsingInlineAsm()) {
1565 StringRef AsmTokStr = Tok.getString();
1566 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1567 return ParseIntelOffsetOfOperator();
1568 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1569 return ParseIntelOperator(IOK_LENGTH);
1570 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1571 return ParseIntelOperator(IOK_SIZE);
1572 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1573 return ParseIntelOperator(IOK_TYPE);
1577 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1578 getLexer().is(AsmToken::LParen)) {
1579 AsmToken StartTok = Tok;
1580 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1581 /*AddImmPrefix=*/false);
1582 if (X86Operand *Err = ParseIntelExpression(SM, End))
1585 int64_t Imm = SM.getImm();
1586 if (isParsingInlineAsm()) {
1587 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1588 if (StartTok.getString().size() == Len)
1589 // Just add a prefix if this wasn't a complex immediate expression.
1590 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1592 // Otherwise, rewrite the complex expression as a single immediate.
1593 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1596 if (getLexer().isNot(AsmToken::LBrac)) {
1597 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1598 return X86Operand::CreateImm(ImmExpr, Start, End);
1601 // Only positive immediates are valid.
1603 return ErrorOperand(Start, "expected a positive immediate displacement "
1604 "before bracketed expr.");
1606 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1607 return ParseIntelMemOperand(/*SegReg=*/0, Imm, Start);
1612 if (!ParseRegister(RegNo, Start, End)) {
1613 // If this is a segment register followed by a ':', then this is the start
1614 // of a memory reference, otherwise this is a normal register reference.
1615 if (getLexer().isNot(AsmToken::Colon))
1616 return X86Operand::CreateReg(RegNo, Start, End);
1618 getParser().Lex(); // Eat the colon.
1619 return ParseIntelMemOperand(/*SegReg=*/RegNo, /*Disp=*/0, Start);
1623 return ParseIntelMemOperand(/*SegReg=*/0, /*Disp=*/0, Start);
1626 X86Operand *X86AsmParser::ParseATTOperand() {
1627 switch (getLexer().getKind()) {
1629 // Parse a memory operand with no segment register.
1630 return ParseMemOperand(0, Parser.getTok().getLoc());
1631 case AsmToken::Percent: {
1632 // Read the register.
1635 if (ParseRegister(RegNo, Start, End)) return 0;
1636 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1637 Error(Start, "%eiz and %riz can only be used as index registers",
1638 SMRange(Start, End));
1642 // If this is a segment register followed by a ':', then this is the start
1643 // of a memory reference, otherwise this is a normal register reference.
1644 if (getLexer().isNot(AsmToken::Colon))
1645 return X86Operand::CreateReg(RegNo, Start, End);
1647 getParser().Lex(); // Eat the colon.
1648 return ParseMemOperand(RegNo, Start);
1650 case AsmToken::Dollar: {
1651 // $42 -> immediate.
1652 SMLoc Start = Parser.getTok().getLoc(), End;
1655 if (getParser().parseExpression(Val, End))
1657 return X86Operand::CreateImm(Val, Start, End);
1662 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1663 /// has already been parsed if present.
1664 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1666 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1667 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1668 // only way to do this without lookahead is to eat the '(' and see what is
1670 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1671 if (getLexer().isNot(AsmToken::LParen)) {
1673 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1675 // After parsing the base expression we could either have a parenthesized
1676 // memory address or not. If not, return now. If so, eat the (.
1677 if (getLexer().isNot(AsmToken::LParen)) {
1678 // Unless we have a segment register, treat this as an immediate.
1680 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1681 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1687 // Okay, we have a '('. We don't know if this is an expression or not, but
1688 // so we have to eat the ( to see beyond it.
1689 SMLoc LParenLoc = Parser.getTok().getLoc();
1690 Parser.Lex(); // Eat the '('.
1692 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1693 // Nothing to do here, fall into the code below with the '(' part of the
1694 // memory operand consumed.
1698 // It must be an parenthesized expression, parse it now.
1699 if (getParser().parseParenExpression(Disp, ExprEnd))
1702 // After parsing the base expression we could either have a parenthesized
1703 // memory address or not. If not, return now. If so, eat the (.
1704 if (getLexer().isNot(AsmToken::LParen)) {
1705 // Unless we have a segment register, treat this as an immediate.
1707 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1708 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1716 // If we reached here, then we just ate the ( of the memory operand. Process
1717 // the rest of the memory operand.
1718 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1721 if (getLexer().is(AsmToken::Percent)) {
1722 SMLoc StartLoc, EndLoc;
1723 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1724 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1725 Error(StartLoc, "eiz and riz can only be used as index registers",
1726 SMRange(StartLoc, EndLoc));
1731 if (getLexer().is(AsmToken::Comma)) {
1732 Parser.Lex(); // Eat the comma.
1733 IndexLoc = Parser.getTok().getLoc();
1735 // Following the comma we should have either an index register, or a scale
1736 // value. We don't support the later form, but we want to parse it
1739 // Not that even though it would be completely consistent to support syntax
1740 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1741 if (getLexer().is(AsmToken::Percent)) {
1743 if (ParseRegister(IndexReg, L, L)) return 0;
1745 if (getLexer().isNot(AsmToken::RParen)) {
1746 // Parse the scale amount:
1747 // ::= ',' [scale-expression]
1748 if (getLexer().isNot(AsmToken::Comma)) {
1749 Error(Parser.getTok().getLoc(),
1750 "expected comma in scale expression");
1753 Parser.Lex(); // Eat the comma.
1755 if (getLexer().isNot(AsmToken::RParen)) {
1756 SMLoc Loc = Parser.getTok().getLoc();
1759 if (getParser().parseAbsoluteExpression(ScaleVal)){
1760 Error(Loc, "expected scale expression");
1764 // Validate the scale amount.
1765 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1766 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1769 Scale = (unsigned)ScaleVal;
1772 } else if (getLexer().isNot(AsmToken::RParen)) {
1773 // A scale amount without an index is ignored.
1775 SMLoc Loc = Parser.getTok().getLoc();
1778 if (getParser().parseAbsoluteExpression(Value))
1782 Warning(Loc, "scale factor without index register is ignored");
1787 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1788 if (getLexer().isNot(AsmToken::RParen)) {
1789 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1792 SMLoc MemEnd = Parser.getTok().getEndLoc();
1793 Parser.Lex(); // Eat the ')'.
1795 // If we have both a base register and an index register make sure they are
1796 // both 64-bit or 32-bit registers.
1797 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1798 if (BaseReg != 0 && IndexReg != 0) {
1799 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1800 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1801 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1802 IndexReg != X86::RIZ) {
1803 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1806 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1807 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1808 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1809 IndexReg != X86::EIZ){
1810 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1815 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1820 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1821 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1823 StringRef PatchedName = Name;
1825 // FIXME: Hack to recognize setneb as setne.
1826 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1827 PatchedName != "setb" && PatchedName != "setnb")
1828 PatchedName = PatchedName.substr(0, Name.size()-1);
1830 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1831 const MCExpr *ExtraImmOp = 0;
1832 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1833 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1834 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1835 bool IsVCMP = PatchedName[0] == 'v';
1836 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1837 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1838 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1842 .Case("unord", 0x03)
1847 /* AVX only from here */
1848 .Case("eq_uq", 0x08)
1851 .Case("false", 0x0B)
1852 .Case("neq_oq", 0x0C)
1856 .Case("eq_os", 0x10)
1857 .Case("lt_oq", 0x11)
1858 .Case("le_oq", 0x12)
1859 .Case("unord_s", 0x13)
1860 .Case("neq_us", 0x14)
1861 .Case("nlt_uq", 0x15)
1862 .Case("nle_uq", 0x16)
1863 .Case("ord_s", 0x17)
1864 .Case("eq_us", 0x18)
1865 .Case("nge_uq", 0x19)
1866 .Case("ngt_uq", 0x1A)
1867 .Case("false_os", 0x1B)
1868 .Case("neq_os", 0x1C)
1869 .Case("ge_oq", 0x1D)
1870 .Case("gt_oq", 0x1E)
1871 .Case("true_us", 0x1F)
1873 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1874 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1875 getParser().getContext());
1876 if (PatchedName.endswith("ss")) {
1877 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1878 } else if (PatchedName.endswith("sd")) {
1879 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1880 } else if (PatchedName.endswith("ps")) {
1881 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1883 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1884 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1889 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1891 if (ExtraImmOp && !isParsingIntelSyntax())
1892 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1894 // Determine whether this is an instruction prefix.
1896 Name == "lock" || Name == "rep" ||
1897 Name == "repe" || Name == "repz" ||
1898 Name == "repne" || Name == "repnz" ||
1899 Name == "rex64" || Name == "data16";
1902 // This does the actual operand parsing. Don't parse any more if we have a
1903 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1904 // just want to parse the "lock" as the first instruction and the "incl" as
1906 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1908 // Parse '*' modifier.
1909 if (getLexer().is(AsmToken::Star)) {
1910 SMLoc Loc = Parser.getTok().getLoc();
1911 Operands.push_back(X86Operand::CreateToken("*", Loc));
1912 Parser.Lex(); // Eat the star.
1915 // Read the first operand.
1916 if (X86Operand *Op = ParseOperand())
1917 Operands.push_back(Op);
1919 Parser.eatToEndOfStatement();
1923 while (getLexer().is(AsmToken::Comma)) {
1924 Parser.Lex(); // Eat the comma.
1926 // Parse and remember the operand.
1927 if (X86Operand *Op = ParseOperand())
1928 Operands.push_back(Op);
1930 Parser.eatToEndOfStatement();
1935 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1936 SMLoc Loc = getLexer().getLoc();
1937 Parser.eatToEndOfStatement();
1938 return Error(Loc, "unexpected token in argument list");
1942 if (getLexer().is(AsmToken::EndOfStatement))
1943 Parser.Lex(); // Consume the EndOfStatement
1944 else if (isPrefix && getLexer().is(AsmToken::Slash))
1945 Parser.Lex(); // Consume the prefix separator Slash
1947 if (ExtraImmOp && isParsingIntelSyntax())
1948 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1950 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1951 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1952 // documented form in various unofficial manuals, so a lot of code uses it.
1953 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1954 Operands.size() == 3) {
1955 X86Operand &Op = *(X86Operand*)Operands.back();
1956 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1957 isa<MCConstantExpr>(Op.Mem.Disp) &&
1958 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1959 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1960 SMLoc Loc = Op.getEndLoc();
1961 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1965 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1966 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1967 Operands.size() == 3) {
1968 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1969 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1970 isa<MCConstantExpr>(Op.Mem.Disp) &&
1971 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1972 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1973 SMLoc Loc = Op.getEndLoc();
1974 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1978 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1979 if (Name.startswith("ins") && Operands.size() == 3 &&
1980 (Name == "insb" || Name == "insw" || Name == "insl")) {
1981 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1982 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1983 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1984 Operands.pop_back();
1985 Operands.pop_back();
1991 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
1992 if (Name.startswith("outs") && Operands.size() == 3 &&
1993 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
1994 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1995 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1996 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
1997 Operands.pop_back();
1998 Operands.pop_back();
2004 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2005 if (Name.startswith("movs") && Operands.size() == 3 &&
2006 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2007 (is64BitMode() && Name == "movsq"))) {
2008 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2009 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2010 if (isSrcOp(Op) && isDstOp(Op2)) {
2011 Operands.pop_back();
2012 Operands.pop_back();
2017 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2018 if (Name.startswith("lods") && Operands.size() == 3 &&
2019 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2020 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2021 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2022 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2023 if (isSrcOp(*Op1) && Op2->isReg()) {
2025 unsigned reg = Op2->getReg();
2026 bool isLods = Name == "lods";
2027 if (reg == X86::AL && (isLods || Name == "lodsb"))
2029 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2031 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2033 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2038 Operands.pop_back();
2039 Operands.pop_back();
2043 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2047 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2048 if (Name.startswith("stos") && Operands.size() == 3 &&
2049 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2050 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2051 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2052 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2053 if (isDstOp(*Op2) && Op1->isReg()) {
2055 unsigned reg = Op1->getReg();
2056 bool isStos = Name == "stos";
2057 if (reg == X86::AL && (isStos || Name == "stosb"))
2059 else if (reg == X86::AX && (isStos || Name == "stosw"))
2061 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2063 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2068 Operands.pop_back();
2069 Operands.pop_back();
2073 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2078 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2080 if ((Name.startswith("shr") || Name.startswith("sar") ||
2081 Name.startswith("shl") || Name.startswith("sal") ||
2082 Name.startswith("rcl") || Name.startswith("rcr") ||
2083 Name.startswith("rol") || Name.startswith("ror")) &&
2084 Operands.size() == 3) {
2085 if (isParsingIntelSyntax()) {
2087 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2088 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2089 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2091 Operands.pop_back();
2094 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2095 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2096 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2098 Operands.erase(Operands.begin() + 1);
2103 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2104 // instalias with an immediate operand yet.
2105 if (Name == "int" && Operands.size() == 2) {
2106 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2107 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2108 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2110 Operands.erase(Operands.begin() + 1);
2111 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2118 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2121 TmpInst.setOpcode(Opcode);
2123 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2124 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2125 TmpInst.addOperand(Inst.getOperand(0));
2130 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2131 bool isCmp = false) {
2132 if (!Inst.getOperand(0).isImm() ||
2133 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2136 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2139 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2140 bool isCmp = false) {
2141 if (!Inst.getOperand(0).isImm() ||
2142 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2145 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2148 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2149 bool isCmp = false) {
2150 if (!Inst.getOperand(0).isImm() ||
2151 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2154 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2158 processInstruction(MCInst &Inst,
2159 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2160 switch (Inst.getOpcode()) {
2161 default: return false;
2162 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2163 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2164 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2165 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2166 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2167 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2168 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2169 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2170 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2171 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2172 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2173 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2174 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2175 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2176 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2177 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2178 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2179 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2180 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2181 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2182 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2183 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2184 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2185 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2189 static const char *getSubtargetFeatureName(unsigned Val);
2191 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2192 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2193 MCStreamer &Out, unsigned &ErrorInfo,
2194 bool MatchingInlineAsm) {
2195 assert(!Operands.empty() && "Unexpect empty operand list!");
2196 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2197 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2198 ArrayRef<SMRange> EmptyRanges = ArrayRef<SMRange>();
2200 // First, handle aliases that expand to multiple instructions.
2201 // FIXME: This should be replaced with a real .td file alias mechanism.
2202 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2204 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2205 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2206 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2207 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2209 Inst.setOpcode(X86::WAIT);
2211 if (!MatchingInlineAsm)
2212 Out.EmitInstruction(Inst);
2215 StringSwitch<const char*>(Op->getToken())
2216 .Case("finit", "fninit")
2217 .Case("fsave", "fnsave")
2218 .Case("fstcw", "fnstcw")
2219 .Case("fstcww", "fnstcw")
2220 .Case("fstenv", "fnstenv")
2221 .Case("fstsw", "fnstsw")
2222 .Case("fstsww", "fnstsw")
2223 .Case("fclex", "fnclex")
2225 assert(Repl && "Unknown wait-prefixed instruction");
2227 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2230 bool WasOriginallyInvalidOperand = false;
2233 // First, try a direct match.
2234 switch (MatchInstructionImpl(Operands, Inst,
2235 ErrorInfo, MatchingInlineAsm,
2236 isParsingIntelSyntax())) {
2239 // Some instructions need post-processing to, for example, tweak which
2240 // encoding is selected. Loop on it while changes happen so the
2241 // individual transformations can chain off each other.
2242 if (!MatchingInlineAsm)
2243 while (processInstruction(Inst, Operands))
2247 if (!MatchingInlineAsm)
2248 Out.EmitInstruction(Inst);
2249 Opcode = Inst.getOpcode();
2251 case Match_MissingFeature: {
2252 assert(ErrorInfo && "Unknown missing feature!");
2253 // Special case the error message for the very common case where only
2254 // a single subtarget feature is missing.
2255 std::string Msg = "instruction requires:";
2257 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2258 if (ErrorInfo & Mask) {
2260 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2264 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2266 case Match_InvalidOperand:
2267 WasOriginallyInvalidOperand = true;
2269 case Match_MnemonicFail:
2273 // FIXME: Ideally, we would only attempt suffix matches for things which are
2274 // valid prefixes, and we could just infer the right unambiguous
2275 // type. However, that requires substantially more matcher support than the
2278 // Change the operand to point to a temporary token.
2279 StringRef Base = Op->getToken();
2280 SmallString<16> Tmp;
2283 Op->setTokenValue(Tmp.str());
2285 // If this instruction starts with an 'f', then it is a floating point stack
2286 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2287 // 80-bit floating point, which use the suffixes s,l,t respectively.
2289 // Otherwise, we assume that this may be an integer instruction, which comes
2290 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2291 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2293 // Check for the various suffix matches.
2294 Tmp[Base.size()] = Suffixes[0];
2295 unsigned ErrorInfoIgnore;
2296 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2297 unsigned Match1, Match2, Match3, Match4;
2299 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2300 isParsingIntelSyntax());
2301 // If this returned as a missing feature failure, remember that.
2302 if (Match1 == Match_MissingFeature)
2303 ErrorInfoMissingFeature = ErrorInfoIgnore;
2304 Tmp[Base.size()] = Suffixes[1];
2305 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2306 isParsingIntelSyntax());
2307 // If this returned as a missing feature failure, remember that.
2308 if (Match2 == Match_MissingFeature)
2309 ErrorInfoMissingFeature = ErrorInfoIgnore;
2310 Tmp[Base.size()] = Suffixes[2];
2311 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2312 isParsingIntelSyntax());
2313 // If this returned as a missing feature failure, remember that.
2314 if (Match3 == Match_MissingFeature)
2315 ErrorInfoMissingFeature = ErrorInfoIgnore;
2316 Tmp[Base.size()] = Suffixes[3];
2317 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2318 isParsingIntelSyntax());
2319 // If this returned as a missing feature failure, remember that.
2320 if (Match4 == Match_MissingFeature)
2321 ErrorInfoMissingFeature = ErrorInfoIgnore;
2323 // Restore the old token.
2324 Op->setTokenValue(Base);
2326 // If exactly one matched, then we treat that as a successful match (and the
2327 // instruction will already have been filled in correctly, since the failing
2328 // matches won't have modified it).
2329 unsigned NumSuccessfulMatches =
2330 (Match1 == Match_Success) + (Match2 == Match_Success) +
2331 (Match3 == Match_Success) + (Match4 == Match_Success);
2332 if (NumSuccessfulMatches == 1) {
2334 if (!MatchingInlineAsm)
2335 Out.EmitInstruction(Inst);
2336 Opcode = Inst.getOpcode();
2340 // Otherwise, the match failed, try to produce a decent error message.
2342 // If we had multiple suffix matches, then identify this as an ambiguous
2344 if (NumSuccessfulMatches > 1) {
2346 unsigned NumMatches = 0;
2347 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2348 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2349 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2350 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2352 SmallString<126> Msg;
2353 raw_svector_ostream OS(Msg);
2354 OS << "ambiguous instructions require an explicit suffix (could be ";
2355 for (unsigned i = 0; i != NumMatches; ++i) {
2358 if (i + 1 == NumMatches)
2360 OS << "'" << Base << MatchChars[i] << "'";
2363 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2367 // Okay, we know that none of the variants matched successfully.
2369 // If all of the instructions reported an invalid mnemonic, then the original
2370 // mnemonic was invalid.
2371 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2372 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2373 if (!WasOriginallyInvalidOperand) {
2374 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2376 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2377 Ranges, MatchingInlineAsm);
2380 // Recover location info for the operand if we know which was the problem.
2381 if (ErrorInfo != ~0U) {
2382 if (ErrorInfo >= Operands.size())
2383 return Error(IDLoc, "too few operands for instruction",
2384 EmptyRanges, MatchingInlineAsm);
2386 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2387 if (Operand->getStartLoc().isValid()) {
2388 SMRange OperandRange = Operand->getLocRange();
2389 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2390 OperandRange, MatchingInlineAsm);
2394 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2398 // If one instruction matched with a missing feature, report this as a
2400 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2401 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2402 std::string Msg = "instruction requires:";
2404 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2405 if (ErrorInfoMissingFeature & Mask) {
2407 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2411 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2414 // If one instruction matched with an invalid operand, report this as an
2416 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2417 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2418 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2423 // If all of these were an outright failure, report it in a useless way.
2424 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2425 EmptyRanges, MatchingInlineAsm);
2430 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2431 StringRef IDVal = DirectiveID.getIdentifier();
2432 if (IDVal == ".word")
2433 return ParseDirectiveWord(2, DirectiveID.getLoc());
2434 else if (IDVal.startswith(".code"))
2435 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2436 else if (IDVal.startswith(".att_syntax")) {
2437 getParser().setAssemblerDialect(0);
2439 } else if (IDVal.startswith(".intel_syntax")) {
2440 getParser().setAssemblerDialect(1);
2441 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2442 if(Parser.getTok().getString() == "noprefix") {
2443 // FIXME : Handle noprefix
2453 /// ParseDirectiveWord
2454 /// ::= .word [ expression (, expression)* ]
2455 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2456 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2458 const MCExpr *Value;
2459 if (getParser().parseExpression(Value))
2462 getParser().getStreamer().EmitValue(Value, Size);
2464 if (getLexer().is(AsmToken::EndOfStatement))
2467 // FIXME: Improve diagnostic.
2468 if (getLexer().isNot(AsmToken::Comma))
2469 return Error(L, "unexpected token in directive");
2478 /// ParseDirectiveCode
2479 /// ::= .code32 | .code64
2480 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2481 if (IDVal == ".code32") {
2483 if (is64BitMode()) {
2485 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2487 } else if (IDVal == ".code64") {
2489 if (!is64BitMode()) {
2491 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2494 return Error(L, "unexpected directive " + IDVal);
2500 // Force static initialization.
2501 extern "C" void LLVMInitializeX86AsmParser() {
2502 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2503 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2506 #define GET_REGISTER_MATCHER
2507 #define GET_MATCHER_IMPLEMENTATION
2508 #define GET_SUBTARGET_FEATURE_NAME
2509 #include "X86GenAsmMatcher.inc"