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() {
223 return State == IES_RBRAC || State == IES_INTEGER;
225 bool getStopOnLBrac() { return StopOnLBrac; }
226 bool getAddImmPrefix() { return AddImmPrefix; }
227 bool hadError() { return State == IES_ERROR; }
229 InlineAsmIdentifierInfo &getIdentifierInfo() {
234 IntelExprState CurrState = State;
243 IC.pushOperator(IC_PLUS);
244 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
245 // If we already have a BaseReg, then assume this is the IndexReg with
250 assert (!IndexReg && "BaseReg/IndexReg already set!");
257 PrevState = CurrState;
260 IntelExprState CurrState = State;
275 // Only push the minus operator if it is not a unary operator.
276 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
277 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
278 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
279 IC.pushOperator(IC_MINUS);
280 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
281 // If we already have a BaseReg, then assume this is the IndexReg with
286 assert (!IndexReg && "BaseReg/IndexReg already set!");
293 PrevState = CurrState;
295 void onRegister(unsigned Reg) {
296 IntelExprState CurrState = State;
303 State = IES_REGISTER;
305 IC.pushOperand(IC_REGISTER);
308 // Index Register - Scale * Register
309 if (PrevState == IES_INTEGER) {
310 assert (!IndexReg && "IndexReg already set!");
311 State = IES_REGISTER;
313 // Get the scale and replace the 'Scale * Register' with '0'.
314 Scale = IC.popOperand();
315 IC.pushOperand(IC_IMM);
322 PrevState = CurrState;
324 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
334 SymName = SymRefName;
335 IC.pushOperand(IC_IMM);
339 void onInteger(int64_t TmpInt) {
340 IntelExprState CurrState = State;
351 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
352 // Index Register - Register * Scale
353 assert (!IndexReg && "IndexReg already set!");
356 // Get the scale and replace the 'Register * Scale' with '0'.
358 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
359 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
360 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
361 CurrState == IES_MINUS) {
362 // Unary minus. No need to pop the minus operand because it was never
364 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
366 IC.pushOperand(IC_IMM, TmpInt);
370 PrevState = CurrState;
381 State = IES_MULTIPLY;
382 IC.pushOperator(IC_MULTIPLY);
395 IC.pushOperator(IC_DIVIDE);
407 IC.pushOperator(IC_PLUS);
412 IntelExprState CurrState = State;
421 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
422 // If we already have a BaseReg, then assume this is the IndexReg with
427 assert (!IndexReg && "BaseReg/IndexReg already set!");
434 PrevState = CurrState;
437 IntelExprState CurrState = State;
447 // FIXME: We don't handle this type of unary minus, yet.
448 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
449 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
450 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
451 CurrState == IES_MINUS) {
456 IC.pushOperator(IC_LPAREN);
459 PrevState = CurrState;
471 IC.pushOperator(IC_RPAREN);
477 MCAsmParser &getParser() const { return Parser; }
479 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
481 bool Error(SMLoc L, const Twine &Msg,
482 ArrayRef<SMRange> Ranges = None,
483 bool MatchingInlineAsm = false) {
484 if (MatchingInlineAsm) return true;
485 return Parser.Error(L, Msg, Ranges);
488 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
493 X86Operand *ParseOperand();
494 X86Operand *ParseATTOperand();
495 X86Operand *ParseIntelOperand();
496 X86Operand *ParseIntelOffsetOfOperator();
497 X86Operand *ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
498 X86Operand *ParseIntelOperator(unsigned OpKind);
499 X86Operand *ParseIntelMemOperand(unsigned SegReg, int64_t ImmDisp,
501 X86Operand *ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
502 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
503 int64_t ImmDisp, unsigned Size);
504 X86Operand *ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
505 InlineAsmIdentifierInfo &Info,
506 bool IsUnevaluatedOperand, SMLoc &End);
508 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
510 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
511 unsigned BaseReg, unsigned IndexReg,
512 unsigned Scale, SMLoc Start, SMLoc End,
513 unsigned Size, StringRef Identifier,
514 InlineAsmIdentifierInfo &Info);
516 bool ParseDirectiveWord(unsigned Size, SMLoc L);
517 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
519 bool processInstruction(MCInst &Inst,
520 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
522 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
523 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
524 MCStreamer &Out, unsigned &ErrorInfo,
525 bool MatchingInlineAsm);
527 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
528 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
529 bool isSrcOp(X86Operand &Op);
531 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
532 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
533 bool isDstOp(X86Operand &Op);
535 bool is64BitMode() const {
536 // FIXME: Can tablegen auto-generate this?
537 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
540 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
541 setAvailableFeatures(FB);
544 bool isParsingIntelSyntax() {
545 return getParser().getAssemblerDialect();
548 /// @name Auto-generated Matcher Functions
551 #define GET_ASSEMBLER_HEADER
552 #include "X86GenAsmMatcher.inc"
557 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser)
558 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
560 // Initialize the set of available features.
561 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
563 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
565 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
567 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
569 virtual bool ParseDirective(AsmToken DirectiveID);
571 } // end anonymous namespace
573 /// @name Auto-generated Match Functions
576 static unsigned MatchRegisterName(StringRef Name);
580 static bool isImmSExti16i8Value(uint64_t Value) {
581 return (( Value <= 0x000000000000007FULL)||
582 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
583 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
586 static bool isImmSExti32i8Value(uint64_t Value) {
587 return (( Value <= 0x000000000000007FULL)||
588 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
589 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
592 static bool isImmZExtu32u8Value(uint64_t Value) {
593 return (Value <= 0x00000000000000FFULL);
596 static bool isImmSExti64i8Value(uint64_t Value) {
597 return (( Value <= 0x000000000000007FULL)||
598 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
601 static bool isImmSExti64i32Value(uint64_t Value) {
602 return (( Value <= 0x000000007FFFFFFFULL)||
603 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
607 /// X86Operand - Instances of this class represent a parsed X86 machine
609 struct X86Operand : public MCParsedAsmOperand {
617 SMLoc StartLoc, EndLoc;
652 X86Operand(KindTy K, SMLoc Start, SMLoc End)
653 : Kind(K), StartLoc(Start), EndLoc(End) {}
655 StringRef getSymName() { return SymName; }
656 void *getOpDecl() { return OpDecl; }
658 /// getStartLoc - Get the location of the first token of this operand.
659 SMLoc getStartLoc() const { return StartLoc; }
660 /// getEndLoc - Get the location of the last token of this operand.
661 SMLoc getEndLoc() const { return EndLoc; }
662 /// getLocRange - Get the range between the first and last token of this
664 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
665 /// getOffsetOfLoc - Get the location of the offset operator.
666 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
668 virtual void print(raw_ostream &OS) const {}
670 StringRef getToken() const {
671 assert(Kind == Token && "Invalid access!");
672 return StringRef(Tok.Data, Tok.Length);
674 void setTokenValue(StringRef Value) {
675 assert(Kind == Token && "Invalid access!");
676 Tok.Data = Value.data();
677 Tok.Length = Value.size();
680 unsigned getReg() const {
681 assert(Kind == Register && "Invalid access!");
685 const MCExpr *getImm() const {
686 assert(Kind == Immediate && "Invalid access!");
690 const MCExpr *getMemDisp() const {
691 assert(Kind == Memory && "Invalid access!");
694 unsigned getMemSegReg() const {
695 assert(Kind == Memory && "Invalid access!");
698 unsigned getMemBaseReg() const {
699 assert(Kind == Memory && "Invalid access!");
702 unsigned getMemIndexReg() const {
703 assert(Kind == Memory && "Invalid access!");
706 unsigned getMemScale() const {
707 assert(Kind == Memory && "Invalid access!");
711 bool isToken() const {return Kind == Token; }
713 bool isImm() const { return Kind == Immediate; }
715 bool isImmSExti16i8() const {
719 // If this isn't a constant expr, just assume it fits and let relaxation
721 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
725 // Otherwise, check the value is in a range that makes sense for this
727 return isImmSExti16i8Value(CE->getValue());
729 bool isImmSExti32i8() const {
733 // If this isn't a constant expr, just assume it fits and let relaxation
735 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
739 // Otherwise, check the value is in a range that makes sense for this
741 return isImmSExti32i8Value(CE->getValue());
743 bool isImmZExtu32u8() const {
747 // If this isn't a constant expr, just assume it fits and let relaxation
749 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
753 // Otherwise, check the value is in a range that makes sense for this
755 return isImmZExtu32u8Value(CE->getValue());
757 bool isImmSExti64i8() const {
761 // If this isn't a constant expr, just assume it fits and let relaxation
763 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
767 // Otherwise, check the value is in a range that makes sense for this
769 return isImmSExti64i8Value(CE->getValue());
771 bool isImmSExti64i32() const {
775 // If this isn't a constant expr, just assume it fits and let relaxation
777 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
781 // Otherwise, check the value is in a range that makes sense for this
783 return isImmSExti64i32Value(CE->getValue());
786 bool isOffsetOf() const {
787 return OffsetOfLoc.getPointer();
790 bool needAddressOf() const {
794 bool isMem() const { return Kind == Memory; }
795 bool isMem8() const {
796 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
798 bool isMem16() const {
799 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
801 bool isMem32() const {
802 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
804 bool isMem64() const {
805 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
807 bool isMem80() const {
808 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
810 bool isMem128() const {
811 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
813 bool isMem256() const {
814 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
817 bool isMemVX32() const {
818 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
819 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
821 bool isMemVY32() const {
822 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
823 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
825 bool isMemVX64() const {
826 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
827 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
829 bool isMemVY64() const {
830 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
831 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
834 bool isAbsMem() const {
835 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
836 !getMemIndexReg() && getMemScale() == 1;
839 bool isReg() const { return Kind == Register; }
841 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
842 // Add as immediates when possible.
843 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
844 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
846 Inst.addOperand(MCOperand::CreateExpr(Expr));
849 void addRegOperands(MCInst &Inst, unsigned N) const {
850 assert(N == 1 && "Invalid number of operands!");
851 Inst.addOperand(MCOperand::CreateReg(getReg()));
854 void addImmOperands(MCInst &Inst, unsigned N) const {
855 assert(N == 1 && "Invalid number of operands!");
856 addExpr(Inst, getImm());
859 void addMem8Operands(MCInst &Inst, unsigned N) const {
860 addMemOperands(Inst, N);
862 void addMem16Operands(MCInst &Inst, unsigned N) const {
863 addMemOperands(Inst, N);
865 void addMem32Operands(MCInst &Inst, unsigned N) const {
866 addMemOperands(Inst, N);
868 void addMem64Operands(MCInst &Inst, unsigned N) const {
869 addMemOperands(Inst, N);
871 void addMem80Operands(MCInst &Inst, unsigned N) const {
872 addMemOperands(Inst, N);
874 void addMem128Operands(MCInst &Inst, unsigned N) const {
875 addMemOperands(Inst, N);
877 void addMem256Operands(MCInst &Inst, unsigned N) const {
878 addMemOperands(Inst, N);
880 void addMemVX32Operands(MCInst &Inst, unsigned N) const {
881 addMemOperands(Inst, N);
883 void addMemVY32Operands(MCInst &Inst, unsigned N) const {
884 addMemOperands(Inst, N);
886 void addMemVX64Operands(MCInst &Inst, unsigned N) const {
887 addMemOperands(Inst, N);
889 void addMemVY64Operands(MCInst &Inst, unsigned N) const {
890 addMemOperands(Inst, N);
893 void addMemOperands(MCInst &Inst, unsigned N) const {
894 assert((N == 5) && "Invalid number of operands!");
895 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
896 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
897 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
898 addExpr(Inst, getMemDisp());
899 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
902 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
903 assert((N == 1) && "Invalid number of operands!");
904 // Add as immediates when possible.
905 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
906 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
908 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
911 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
912 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
913 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
914 Res->Tok.Data = Str.data();
915 Res->Tok.Length = Str.size();
919 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
920 bool AddressOf = false,
921 SMLoc OffsetOfLoc = SMLoc(),
922 StringRef SymName = StringRef(),
924 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
925 Res->Reg.RegNo = RegNo;
926 Res->AddressOf = AddressOf;
927 Res->OffsetOfLoc = OffsetOfLoc;
928 Res->SymName = SymName;
929 Res->OpDecl = OpDecl;
933 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
934 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
939 /// Create an absolute memory operand.
940 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
941 unsigned Size = 0, StringRef SymName = StringRef(),
943 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
945 Res->Mem.Disp = Disp;
946 Res->Mem.BaseReg = 0;
947 Res->Mem.IndexReg = 0;
949 Res->Mem.Size = Size;
950 Res->SymName = SymName;
951 Res->OpDecl = OpDecl;
952 Res->AddressOf = false;
956 /// Create a generalized memory operand.
957 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
958 unsigned BaseReg, unsigned IndexReg,
959 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
961 StringRef SymName = StringRef(),
963 // We should never just have a displacement, that should be parsed as an
964 // absolute memory operand.
965 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
967 // The scale should always be one of {1,2,4,8}.
968 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
970 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
971 Res->Mem.SegReg = SegReg;
972 Res->Mem.Disp = Disp;
973 Res->Mem.BaseReg = BaseReg;
974 Res->Mem.IndexReg = IndexReg;
975 Res->Mem.Scale = Scale;
976 Res->Mem.Size = Size;
977 Res->SymName = SymName;
978 Res->OpDecl = OpDecl;
979 Res->AddressOf = false;
984 } // end anonymous namespace.
986 bool X86AsmParser::isSrcOp(X86Operand &Op) {
987 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
989 return (Op.isMem() &&
990 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
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::isDstOp(X86Operand &Op) {
997 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
1000 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
1001 isa<MCConstantExpr>(Op.Mem.Disp) &&
1002 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1003 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
1006 bool X86AsmParser::ParseRegister(unsigned &RegNo,
1007 SMLoc &StartLoc, SMLoc &EndLoc) {
1009 const AsmToken &PercentTok = Parser.getTok();
1010 StartLoc = PercentTok.getLoc();
1012 // If we encounter a %, ignore it. This code handles registers with and
1013 // without the prefix, unprefixed registers can occur in cfi directives.
1014 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1015 Parser.Lex(); // Eat percent token.
1017 const AsmToken &Tok = Parser.getTok();
1018 EndLoc = Tok.getEndLoc();
1020 if (Tok.isNot(AsmToken::Identifier)) {
1021 if (isParsingIntelSyntax()) return true;
1022 return Error(StartLoc, "invalid register name",
1023 SMRange(StartLoc, EndLoc));
1026 RegNo = MatchRegisterName(Tok.getString());
1028 // If the match failed, try the register name as lowercase.
1030 RegNo = MatchRegisterName(Tok.getString().lower());
1032 if (!is64BitMode()) {
1033 // FIXME: This should be done using Requires<In32BitMode> and
1034 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1036 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1038 if (RegNo == X86::RIZ ||
1039 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1040 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1041 X86II::isX86_64ExtendedReg(RegNo))
1042 return Error(StartLoc, "register %"
1043 + Tok.getString() + " is only available in 64-bit mode",
1044 SMRange(StartLoc, EndLoc));
1047 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1048 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1050 Parser.Lex(); // Eat 'st'
1052 // Check to see if we have '(4)' after %st.
1053 if (getLexer().isNot(AsmToken::LParen))
1058 const AsmToken &IntTok = Parser.getTok();
1059 if (IntTok.isNot(AsmToken::Integer))
1060 return Error(IntTok.getLoc(), "expected stack index");
1061 switch (IntTok.getIntVal()) {
1062 case 0: RegNo = X86::ST0; break;
1063 case 1: RegNo = X86::ST1; break;
1064 case 2: RegNo = X86::ST2; break;
1065 case 3: RegNo = X86::ST3; break;
1066 case 4: RegNo = X86::ST4; break;
1067 case 5: RegNo = X86::ST5; break;
1068 case 6: RegNo = X86::ST6; break;
1069 case 7: RegNo = X86::ST7; break;
1070 default: return Error(IntTok.getLoc(), "invalid stack index");
1073 if (getParser().Lex().isNot(AsmToken::RParen))
1074 return Error(Parser.getTok().getLoc(), "expected ')'");
1076 EndLoc = Parser.getTok().getEndLoc();
1077 Parser.Lex(); // Eat ')'
1081 EndLoc = Parser.getTok().getEndLoc();
1083 // If this is "db[0-7]", match it as an alias
1085 if (RegNo == 0 && Tok.getString().size() == 3 &&
1086 Tok.getString().startswith("db")) {
1087 switch (Tok.getString()[2]) {
1088 case '0': RegNo = X86::DR0; break;
1089 case '1': RegNo = X86::DR1; break;
1090 case '2': RegNo = X86::DR2; break;
1091 case '3': RegNo = X86::DR3; break;
1092 case '4': RegNo = X86::DR4; break;
1093 case '5': RegNo = X86::DR5; break;
1094 case '6': RegNo = X86::DR6; break;
1095 case '7': RegNo = X86::DR7; break;
1099 EndLoc = Parser.getTok().getEndLoc();
1100 Parser.Lex(); // Eat it.
1106 if (isParsingIntelSyntax()) return true;
1107 return Error(StartLoc, "invalid register name",
1108 SMRange(StartLoc, EndLoc));
1111 Parser.Lex(); // Eat identifier token.
1115 X86Operand *X86AsmParser::ParseOperand() {
1116 if (isParsingIntelSyntax())
1117 return ParseIntelOperand();
1118 return ParseATTOperand();
1121 /// getIntelMemOperandSize - Return intel memory operand size.
1122 static unsigned getIntelMemOperandSize(StringRef OpStr) {
1123 unsigned Size = StringSwitch<unsigned>(OpStr)
1124 .Cases("BYTE", "byte", 8)
1125 .Cases("WORD", "word", 16)
1126 .Cases("DWORD", "dword", 32)
1127 .Cases("QWORD", "qword", 64)
1128 .Cases("XWORD", "xword", 80)
1129 .Cases("XMMWORD", "xmmword", 128)
1130 .Cases("YMMWORD", "ymmword", 256)
1136 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1137 unsigned BaseReg, unsigned IndexReg,
1138 unsigned Scale, SMLoc Start, SMLoc End,
1139 unsigned Size, StringRef Identifier,
1140 InlineAsmIdentifierInfo &Info){
1141 if (isa<MCSymbolRefExpr>(Disp)) {
1142 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1143 // reference. We need an 'r' constraint here, so we need to create register
1144 // operand to ensure proper matching. Just pick a GPR based on the size of
1146 if (!Info.IsVarDecl) {
1147 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1148 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1149 SMLoc(), Identifier, Info.OpDecl);
1152 Size = Info.Type * 8; // Size is in terms of bits in this context.
1154 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1159 // When parsing inline assembly we set the base register to a non-zero value
1160 // if we don't know the actual value at this time. This is necessary to
1161 // get the matching correct in some cases.
1162 BaseReg = BaseReg ? BaseReg : 1;
1163 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1164 End, Size, Identifier, Info.OpDecl);
1168 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1169 StringRef SymName, int64_t ImmDisp,
1170 int64_t FinalImmDisp, SMLoc &BracLoc,
1171 SMLoc &StartInBrac, SMLoc &End) {
1172 // Remove the '[' and ']' from the IR string.
1173 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1174 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1176 // If ImmDisp is non-zero, then we parsed a displacement before the
1177 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1178 // If ImmDisp doesn't match the displacement computed by the state machine
1179 // then we have an additional displacement in the bracketed expression.
1180 if (ImmDisp != FinalImmDisp) {
1182 // We have an immediate displacement before the bracketed expression.
1183 // Adjust this to match the final immediate displacement.
1185 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1186 E = AsmRewrites->end(); I != E; ++I) {
1187 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1189 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1190 assert (!Found && "ImmDisp already rewritten.");
1191 (*I).Kind = AOK_Imm;
1192 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1193 (*I).Val = FinalImmDisp;
1198 assert (Found && "Unable to rewrite ImmDisp.");
1201 // We have a symbolic and an immediate displacement, but no displacement
1202 // before the bracketed expression. Put the immediate displacement
1203 // before the bracketed expression.
1204 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1207 // Remove all the ImmPrefix rewrites within the brackets.
1208 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1209 E = AsmRewrites->end(); I != E; ++I) {
1210 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1212 if ((*I).Kind == AOK_ImmPrefix)
1213 (*I).Kind = AOK_Delete;
1215 const char *SymLocPtr = SymName.data();
1216 // Skip everything before the symbol.
1217 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1218 assert(Len > 0 && "Expected a non-negative length.");
1219 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1221 // Skip everything after the symbol.
1222 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1223 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1224 assert(Len > 0 && "Expected a non-negative length.");
1225 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1230 X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1231 const AsmToken &Tok = Parser.getTok();
1235 bool UpdateLocLex = true;
1237 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1238 // identifier. Don't try an parse it as a register.
1239 if (Tok.getString().startswith("."))
1242 // If we're parsing an immediate expression, we don't expect a '['.
1243 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1246 switch (getLexer().getKind()) {
1248 if (SM.isValidEndState()) {
1252 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1254 case AsmToken::EndOfStatement: {
1258 case AsmToken::Identifier: {
1259 // This could be a register or a symbolic displacement.
1262 SMLoc IdentLoc = Tok.getLoc();
1263 StringRef Identifier = Tok.getString();
1264 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1265 SM.onRegister(TmpReg);
1266 UpdateLocLex = false;
1269 if (!isParsingInlineAsm()) {
1270 if (getParser().parsePrimaryExpr(Val, End))
1271 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1273 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1274 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1275 /*Unevaluated*/ false, End))
1278 SM.onIdentifierExpr(Val, Identifier);
1279 UpdateLocLex = false;
1282 return ErrorOperand(Tok.getLoc(), "Unexpected identifier!");
1284 case AsmToken::Integer:
1285 if (isParsingInlineAsm() && SM.getAddImmPrefix())
1286 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1288 SM.onInteger(Tok.getIntVal());
1290 case AsmToken::Plus: SM.onPlus(); break;
1291 case AsmToken::Minus: SM.onMinus(); break;
1292 case AsmToken::Star: SM.onStar(); break;
1293 case AsmToken::Slash: SM.onDivide(); break;
1294 case AsmToken::LBrac: SM.onLBrac(); break;
1295 case AsmToken::RBrac: SM.onRBrac(); break;
1296 case AsmToken::LParen: SM.onLParen(); break;
1297 case AsmToken::RParen: SM.onRParen(); break;
1300 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1302 if (!Done && UpdateLocLex) {
1304 Parser.Lex(); // Consume the token.
1310 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1313 const AsmToken &Tok = Parser.getTok();
1314 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1315 if (getLexer().isNot(AsmToken::LBrac))
1316 return ErrorOperand(BracLoc, "Expected '[' token!");
1317 Parser.Lex(); // Eat '['
1319 SMLoc StartInBrac = Tok.getLoc();
1320 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1321 // may have already parsed an immediate displacement before the bracketed
1323 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1324 if (X86Operand *Err = ParseIntelExpression(SM, End))
1328 if (const MCExpr *Sym = SM.getSym()) {
1329 // A symbolic displacement.
1331 if (isParsingInlineAsm())
1332 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1333 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1336 // An immediate displacement only.
1337 Disp = MCConstantExpr::Create(SM.getImm(), getContext());
1340 // Parse the dot operator (e.g., [ebx].foo.bar).
1341 if (Tok.getString().startswith(".")) {
1342 const MCExpr *NewDisp;
1343 if (X86Operand *Err = ParseIntelDotOperator(Disp, NewDisp))
1346 End = Tok.getEndLoc();
1347 Parser.Lex(); // Eat the field.
1351 int BaseReg = SM.getBaseReg();
1352 int IndexReg = SM.getIndexReg();
1353 int Scale = SM.getScale();
1354 if (!isParsingInlineAsm()) {
1356 if (!BaseReg && !IndexReg) {
1358 return X86Operand::CreateMem(Disp, Start, End, Size);
1360 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1362 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1366 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1367 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1368 End, Size, SM.getSymName(), Info);
1371 // Inline assembly may use variable names with namespace alias qualifiers.
1372 X86Operand *X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1373 StringRef &Identifier,
1374 InlineAsmIdentifierInfo &Info,
1375 bool IsUnevaluatedOperand,
1377 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1380 StringRef LineBuf(Identifier.data());
1381 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
1383 const AsmToken &Tok = Parser.getTok();
1385 // Advance the token stream until the end of the current token is
1386 // after the end of what the frontend claimed.
1387 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
1389 End = Tok.getEndLoc();
1392 assert(End.getPointer() <= EndPtr && "frontend claimed part of a token?");
1393 if (End.getPointer() == EndPtr) break;
1396 // Create the symbol reference.
1397 Identifier = LineBuf;
1398 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1399 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1400 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1404 /// ParseIntelMemOperand - Parse intel style memory operand.
1405 X86Operand *X86AsmParser::ParseIntelMemOperand(unsigned SegReg,
1408 const AsmToken &Tok = Parser.getTok();
1411 unsigned Size = getIntelMemOperandSize(Tok.getString());
1413 Parser.Lex(); // Eat operand size (e.g., byte, word).
1414 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1415 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1416 Parser.Lex(); // Eat ptr.
1419 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1420 if (getLexer().is(AsmToken::Integer)) {
1421 if (isParsingInlineAsm())
1422 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1424 int64_t ImmDisp = Tok.getIntVal();
1425 Parser.Lex(); // Eat the integer.
1426 if (getLexer().isNot(AsmToken::LBrac))
1427 return ErrorOperand(Start, "Expected '[' token!");
1428 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1431 if (getLexer().is(AsmToken::LBrac))
1432 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1434 if (!ParseRegister(SegReg, Start, End)) {
1435 // Handel SegReg : [ ... ]
1436 if (getLexer().isNot(AsmToken::Colon))
1437 return ErrorOperand(Start, "Expected ':' token!");
1438 Parser.Lex(); // Eat :
1439 if (getLexer().isNot(AsmToken::LBrac))
1440 return ErrorOperand(Start, "Expected '[' token!");
1441 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1445 if (!isParsingInlineAsm()) {
1446 if (getParser().parsePrimaryExpr(Val, End))
1447 return ErrorOperand(Tok.getLoc(), "Unexpected token!");
1449 return X86Operand::CreateMem(Val, Start, End, Size);
1452 InlineAsmIdentifierInfo Info;
1453 StringRef Identifier = Tok.getString();
1454 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1455 /*Unevaluated*/ false, End))
1457 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1458 /*Scale=*/1, Start, End, Size, Identifier, Info);
1461 /// Parse the '.' operator.
1462 X86Operand *X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1463 const MCExpr *&NewDisp) {
1464 const AsmToken &Tok = Parser.getTok();
1465 int64_t OrigDispVal, DotDispVal;
1467 // FIXME: Handle non-constant expressions.
1468 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1469 OrigDispVal = OrigDisp->getValue();
1471 return ErrorOperand(Tok.getLoc(), "Non-constant offsets are not supported!");
1474 StringRef DotDispStr = Tok.getString().drop_front(1);
1476 // .Imm gets lexed as a real.
1477 if (Tok.is(AsmToken::Real)) {
1479 DotDispStr.getAsInteger(10, DotDisp);
1480 DotDispVal = DotDisp.getZExtValue();
1481 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1483 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1484 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1486 return ErrorOperand(Tok.getLoc(), "Unable to lookup field reference!");
1487 DotDispVal = DotDisp;
1489 return ErrorOperand(Tok.getLoc(), "Unexpected token type!");
1491 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1492 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1493 unsigned Len = DotDispStr.size();
1494 unsigned Val = OrigDispVal + DotDispVal;
1495 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1499 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1503 /// Parse the 'offset' operator. This operator is used to specify the
1504 /// location rather then the content of a variable.
1505 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1506 const AsmToken &Tok = Parser.getTok();
1507 SMLoc OffsetOfLoc = Tok.getLoc();
1508 Parser.Lex(); // Eat offset.
1511 InlineAsmIdentifierInfo Info;
1512 SMLoc Start = Tok.getLoc(), End;
1513 StringRef Identifier = Tok.getString();
1514 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1515 /*Unevaluated*/ false, End))
1518 // Don't emit the offset operator.
1519 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1521 // The offset operator will have an 'r' constraint, thus we need to create
1522 // register operand to ensure proper matching. Just pick a GPR based on
1523 // the size of a pointer.
1524 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1525 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1526 OffsetOfLoc, Identifier, Info.OpDecl);
1529 enum IntelOperatorKind {
1535 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1536 /// returns the number of elements in an array. It returns the value 1 for
1537 /// non-array variables. The SIZE operator returns the size of a C or C++
1538 /// variable. A variable's size is the product of its LENGTH and TYPE. The
1539 /// TYPE operator returns the size of a C or C++ type or variable. If the
1540 /// variable is an array, TYPE returns the size of a single element.
1541 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1542 const AsmToken &Tok = Parser.getTok();
1543 SMLoc TypeLoc = Tok.getLoc();
1544 Parser.Lex(); // Eat operator.
1546 const MCExpr *Val = 0;
1547 InlineAsmIdentifierInfo Info;
1548 SMLoc Start = Tok.getLoc(), End;
1549 StringRef Identifier = Tok.getString();
1550 if (X86Operand *Err = ParseIntelIdentifier(Val, Identifier, Info,
1551 /*Unevaluated*/ true, End))
1556 default: llvm_unreachable("Unexpected operand kind!");
1557 case IOK_LENGTH: CVal = Info.Length; break;
1558 case IOK_SIZE: CVal = Info.Size; break;
1559 case IOK_TYPE: CVal = Info.Type; break;
1562 // Rewrite the type operator and the C or C++ type or variable in terms of an
1563 // immediate. E.g. TYPE foo -> $$4
1564 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1565 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1567 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1568 return X86Operand::CreateImm(Imm, Start, End);
1571 X86Operand *X86AsmParser::ParseIntelOperand() {
1572 const AsmToken &Tok = Parser.getTok();
1573 SMLoc Start = Tok.getLoc(), End;
1575 // Offset, length, type and size operators.
1576 if (isParsingInlineAsm()) {
1577 StringRef AsmTokStr = Tok.getString();
1578 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1579 return ParseIntelOffsetOfOperator();
1580 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1581 return ParseIntelOperator(IOK_LENGTH);
1582 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1583 return ParseIntelOperator(IOK_SIZE);
1584 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1585 return ParseIntelOperator(IOK_TYPE);
1589 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1590 getLexer().is(AsmToken::LParen)) {
1591 AsmToken StartTok = Tok;
1592 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1593 /*AddImmPrefix=*/false);
1594 if (X86Operand *Err = ParseIntelExpression(SM, End))
1597 int64_t Imm = SM.getImm();
1598 if (isParsingInlineAsm()) {
1599 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1600 if (StartTok.getString().size() == Len)
1601 // Just add a prefix if this wasn't a complex immediate expression.
1602 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1604 // Otherwise, rewrite the complex expression as a single immediate.
1605 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1608 if (getLexer().isNot(AsmToken::LBrac)) {
1609 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1610 return X86Operand::CreateImm(ImmExpr, Start, End);
1613 // Only positive immediates are valid.
1615 return ErrorOperand(Start, "expected a positive immediate displacement "
1616 "before bracketed expr.");
1618 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1619 return ParseIntelMemOperand(/*SegReg=*/0, Imm, Start);
1624 if (!ParseRegister(RegNo, Start, End)) {
1625 // If this is a segment register followed by a ':', then this is the start
1626 // of a memory reference, otherwise this is a normal register reference.
1627 if (getLexer().isNot(AsmToken::Colon))
1628 return X86Operand::CreateReg(RegNo, Start, End);
1630 getParser().Lex(); // Eat the colon.
1631 return ParseIntelMemOperand(/*SegReg=*/RegNo, /*Disp=*/0, Start);
1635 return ParseIntelMemOperand(/*SegReg=*/0, /*Disp=*/0, Start);
1638 X86Operand *X86AsmParser::ParseATTOperand() {
1639 switch (getLexer().getKind()) {
1641 // Parse a memory operand with no segment register.
1642 return ParseMemOperand(0, Parser.getTok().getLoc());
1643 case AsmToken::Percent: {
1644 // Read the register.
1647 if (ParseRegister(RegNo, Start, End)) return 0;
1648 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1649 Error(Start, "%eiz and %riz can only be used as index registers",
1650 SMRange(Start, End));
1654 // If this is a segment register followed by a ':', then this is the start
1655 // of a memory reference, otherwise this is a normal register reference.
1656 if (getLexer().isNot(AsmToken::Colon))
1657 return X86Operand::CreateReg(RegNo, Start, End);
1659 getParser().Lex(); // Eat the colon.
1660 return ParseMemOperand(RegNo, Start);
1662 case AsmToken::Dollar: {
1663 // $42 -> immediate.
1664 SMLoc Start = Parser.getTok().getLoc(), End;
1667 if (getParser().parseExpression(Val, End))
1669 return X86Operand::CreateImm(Val, Start, End);
1674 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1675 /// has already been parsed if present.
1676 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1678 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1679 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1680 // only way to do this without lookahead is to eat the '(' and see what is
1682 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1683 if (getLexer().isNot(AsmToken::LParen)) {
1685 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1687 // After parsing the base expression we could either have a parenthesized
1688 // memory address or not. If not, return now. If so, eat the (.
1689 if (getLexer().isNot(AsmToken::LParen)) {
1690 // Unless we have a segment register, treat this as an immediate.
1692 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1693 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1699 // Okay, we have a '('. We don't know if this is an expression or not, but
1700 // so we have to eat the ( to see beyond it.
1701 SMLoc LParenLoc = Parser.getTok().getLoc();
1702 Parser.Lex(); // Eat the '('.
1704 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1705 // Nothing to do here, fall into the code below with the '(' part of the
1706 // memory operand consumed.
1710 // It must be an parenthesized expression, parse it now.
1711 if (getParser().parseParenExpression(Disp, ExprEnd))
1714 // After parsing the base expression we could either have a parenthesized
1715 // memory address or not. If not, return now. If so, eat the (.
1716 if (getLexer().isNot(AsmToken::LParen)) {
1717 // Unless we have a segment register, treat this as an immediate.
1719 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1720 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1728 // If we reached here, then we just ate the ( of the memory operand. Process
1729 // the rest of the memory operand.
1730 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1733 if (getLexer().is(AsmToken::Percent)) {
1734 SMLoc StartLoc, EndLoc;
1735 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1736 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1737 Error(StartLoc, "eiz and riz can only be used as index registers",
1738 SMRange(StartLoc, EndLoc));
1743 if (getLexer().is(AsmToken::Comma)) {
1744 Parser.Lex(); // Eat the comma.
1745 IndexLoc = Parser.getTok().getLoc();
1747 // Following the comma we should have either an index register, or a scale
1748 // value. We don't support the later form, but we want to parse it
1751 // Not that even though it would be completely consistent to support syntax
1752 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1753 if (getLexer().is(AsmToken::Percent)) {
1755 if (ParseRegister(IndexReg, L, L)) return 0;
1757 if (getLexer().isNot(AsmToken::RParen)) {
1758 // Parse the scale amount:
1759 // ::= ',' [scale-expression]
1760 if (getLexer().isNot(AsmToken::Comma)) {
1761 Error(Parser.getTok().getLoc(),
1762 "expected comma in scale expression");
1765 Parser.Lex(); // Eat the comma.
1767 if (getLexer().isNot(AsmToken::RParen)) {
1768 SMLoc Loc = Parser.getTok().getLoc();
1771 if (getParser().parseAbsoluteExpression(ScaleVal)){
1772 Error(Loc, "expected scale expression");
1776 // Validate the scale amount.
1777 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1778 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1781 Scale = (unsigned)ScaleVal;
1784 } else if (getLexer().isNot(AsmToken::RParen)) {
1785 // A scale amount without an index is ignored.
1787 SMLoc Loc = Parser.getTok().getLoc();
1790 if (getParser().parseAbsoluteExpression(Value))
1794 Warning(Loc, "scale factor without index register is ignored");
1799 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1800 if (getLexer().isNot(AsmToken::RParen)) {
1801 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1804 SMLoc MemEnd = Parser.getTok().getEndLoc();
1805 Parser.Lex(); // Eat the ')'.
1807 // If we have both a base register and an index register make sure they are
1808 // both 64-bit or 32-bit registers.
1809 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1810 if (BaseReg != 0 && IndexReg != 0) {
1811 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1812 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1813 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1814 IndexReg != X86::RIZ) {
1815 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1818 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1819 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1820 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1821 IndexReg != X86::EIZ){
1822 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1827 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1832 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1833 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1835 StringRef PatchedName = Name;
1837 // FIXME: Hack to recognize setneb as setne.
1838 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1839 PatchedName != "setb" && PatchedName != "setnb")
1840 PatchedName = PatchedName.substr(0, Name.size()-1);
1842 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1843 const MCExpr *ExtraImmOp = 0;
1844 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1845 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1846 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1847 bool IsVCMP = PatchedName[0] == 'v';
1848 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1849 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1850 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1854 .Case("unord", 0x03)
1859 /* AVX only from here */
1860 .Case("eq_uq", 0x08)
1863 .Case("false", 0x0B)
1864 .Case("neq_oq", 0x0C)
1868 .Case("eq_os", 0x10)
1869 .Case("lt_oq", 0x11)
1870 .Case("le_oq", 0x12)
1871 .Case("unord_s", 0x13)
1872 .Case("neq_us", 0x14)
1873 .Case("nlt_uq", 0x15)
1874 .Case("nle_uq", 0x16)
1875 .Case("ord_s", 0x17)
1876 .Case("eq_us", 0x18)
1877 .Case("nge_uq", 0x19)
1878 .Case("ngt_uq", 0x1A)
1879 .Case("false_os", 0x1B)
1880 .Case("neq_os", 0x1C)
1881 .Case("ge_oq", 0x1D)
1882 .Case("gt_oq", 0x1E)
1883 .Case("true_us", 0x1F)
1885 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1886 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1887 getParser().getContext());
1888 if (PatchedName.endswith("ss")) {
1889 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1890 } else if (PatchedName.endswith("sd")) {
1891 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1892 } else if (PatchedName.endswith("ps")) {
1893 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1895 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1896 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1901 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1903 if (ExtraImmOp && !isParsingIntelSyntax())
1904 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1906 // Determine whether this is an instruction prefix.
1908 Name == "lock" || Name == "rep" ||
1909 Name == "repe" || Name == "repz" ||
1910 Name == "repne" || Name == "repnz" ||
1911 Name == "rex64" || Name == "data16";
1914 // This does the actual operand parsing. Don't parse any more if we have a
1915 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1916 // just want to parse the "lock" as the first instruction and the "incl" as
1918 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1920 // Parse '*' modifier.
1921 if (getLexer().is(AsmToken::Star)) {
1922 SMLoc Loc = Parser.getTok().getLoc();
1923 Operands.push_back(X86Operand::CreateToken("*", Loc));
1924 Parser.Lex(); // Eat the star.
1927 // Read the first operand.
1928 if (X86Operand *Op = ParseOperand())
1929 Operands.push_back(Op);
1931 Parser.eatToEndOfStatement();
1935 while (getLexer().is(AsmToken::Comma)) {
1936 Parser.Lex(); // Eat the comma.
1938 // Parse and remember the operand.
1939 if (X86Operand *Op = ParseOperand())
1940 Operands.push_back(Op);
1942 Parser.eatToEndOfStatement();
1947 if (getLexer().isNot(AsmToken::EndOfStatement)) {
1948 SMLoc Loc = getLexer().getLoc();
1949 Parser.eatToEndOfStatement();
1950 return Error(Loc, "unexpected token in argument list");
1954 if (getLexer().is(AsmToken::EndOfStatement))
1955 Parser.Lex(); // Consume the EndOfStatement
1956 else if (isPrefix && getLexer().is(AsmToken::Slash))
1957 Parser.Lex(); // Consume the prefix separator Slash
1959 if (ExtraImmOp && isParsingIntelSyntax())
1960 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1962 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
1963 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
1964 // documented form in various unofficial manuals, so a lot of code uses it.
1965 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
1966 Operands.size() == 3) {
1967 X86Operand &Op = *(X86Operand*)Operands.back();
1968 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1969 isa<MCConstantExpr>(Op.Mem.Disp) &&
1970 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1971 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1972 SMLoc Loc = Op.getEndLoc();
1973 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1977 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
1978 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
1979 Operands.size() == 3) {
1980 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1981 if (Op.isMem() && Op.Mem.SegReg == 0 &&
1982 isa<MCConstantExpr>(Op.Mem.Disp) &&
1983 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1984 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
1985 SMLoc Loc = Op.getEndLoc();
1986 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
1990 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
1991 if (Name.startswith("ins") && Operands.size() == 3 &&
1992 (Name == "insb" || Name == "insw" || Name == "insl")) {
1993 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
1994 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
1995 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
1996 Operands.pop_back();
1997 Operands.pop_back();
2003 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
2004 if (Name.startswith("outs") && Operands.size() == 3 &&
2005 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
2006 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2007 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2008 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
2009 Operands.pop_back();
2010 Operands.pop_back();
2016 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2017 if (Name.startswith("movs") && Operands.size() == 3 &&
2018 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2019 (is64BitMode() && Name == "movsq"))) {
2020 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2021 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2022 if (isSrcOp(Op) && isDstOp(Op2)) {
2023 Operands.pop_back();
2024 Operands.pop_back();
2029 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2030 if (Name.startswith("lods") && Operands.size() == 3 &&
2031 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2032 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2033 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2034 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2035 if (isSrcOp(*Op1) && Op2->isReg()) {
2037 unsigned reg = Op2->getReg();
2038 bool isLods = Name == "lods";
2039 if (reg == X86::AL && (isLods || Name == "lodsb"))
2041 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2043 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2045 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2050 Operands.pop_back();
2051 Operands.pop_back();
2055 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2059 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2060 if (Name.startswith("stos") && Operands.size() == 3 &&
2061 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2062 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2063 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2064 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2065 if (isDstOp(*Op2) && Op1->isReg()) {
2067 unsigned reg = Op1->getReg();
2068 bool isStos = Name == "stos";
2069 if (reg == X86::AL && (isStos || Name == "stosb"))
2071 else if (reg == X86::AX && (isStos || Name == "stosw"))
2073 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2075 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2080 Operands.pop_back();
2081 Operands.pop_back();
2085 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2090 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2092 if ((Name.startswith("shr") || Name.startswith("sar") ||
2093 Name.startswith("shl") || Name.startswith("sal") ||
2094 Name.startswith("rcl") || Name.startswith("rcr") ||
2095 Name.startswith("rol") || Name.startswith("ror")) &&
2096 Operands.size() == 3) {
2097 if (isParsingIntelSyntax()) {
2099 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2100 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2101 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2103 Operands.pop_back();
2106 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2107 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2108 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2110 Operands.erase(Operands.begin() + 1);
2115 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2116 // instalias with an immediate operand yet.
2117 if (Name == "int" && Operands.size() == 2) {
2118 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2119 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2120 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2122 Operands.erase(Operands.begin() + 1);
2123 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2130 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2133 TmpInst.setOpcode(Opcode);
2135 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2136 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2137 TmpInst.addOperand(Inst.getOperand(0));
2142 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2143 bool isCmp = false) {
2144 if (!Inst.getOperand(0).isImm() ||
2145 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2148 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2151 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2152 bool isCmp = false) {
2153 if (!Inst.getOperand(0).isImm() ||
2154 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2157 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2160 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2161 bool isCmp = false) {
2162 if (!Inst.getOperand(0).isImm() ||
2163 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2166 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2170 processInstruction(MCInst &Inst,
2171 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2172 switch (Inst.getOpcode()) {
2173 default: return false;
2174 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2175 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2176 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2177 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2178 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2179 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2180 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2181 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2182 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2183 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2184 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2185 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2186 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2187 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2188 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2189 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2190 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2191 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2192 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2193 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2194 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2195 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2196 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2197 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2201 static const char *getSubtargetFeatureName(unsigned Val);
2203 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2204 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2205 MCStreamer &Out, unsigned &ErrorInfo,
2206 bool MatchingInlineAsm) {
2207 assert(!Operands.empty() && "Unexpect empty operand list!");
2208 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2209 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2210 ArrayRef<SMRange> EmptyRanges = None;
2212 // First, handle aliases that expand to multiple instructions.
2213 // FIXME: This should be replaced with a real .td file alias mechanism.
2214 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2216 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2217 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2218 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2219 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2221 Inst.setOpcode(X86::WAIT);
2223 if (!MatchingInlineAsm)
2224 Out.EmitInstruction(Inst);
2227 StringSwitch<const char*>(Op->getToken())
2228 .Case("finit", "fninit")
2229 .Case("fsave", "fnsave")
2230 .Case("fstcw", "fnstcw")
2231 .Case("fstcww", "fnstcw")
2232 .Case("fstenv", "fnstenv")
2233 .Case("fstsw", "fnstsw")
2234 .Case("fstsww", "fnstsw")
2235 .Case("fclex", "fnclex")
2237 assert(Repl && "Unknown wait-prefixed instruction");
2239 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2242 bool WasOriginallyInvalidOperand = false;
2245 // First, try a direct match.
2246 switch (MatchInstructionImpl(Operands, Inst,
2247 ErrorInfo, MatchingInlineAsm,
2248 isParsingIntelSyntax())) {
2251 // Some instructions need post-processing to, for example, tweak which
2252 // encoding is selected. Loop on it while changes happen so the
2253 // individual transformations can chain off each other.
2254 if (!MatchingInlineAsm)
2255 while (processInstruction(Inst, Operands))
2259 if (!MatchingInlineAsm)
2260 Out.EmitInstruction(Inst);
2261 Opcode = Inst.getOpcode();
2263 case Match_MissingFeature: {
2264 assert(ErrorInfo && "Unknown missing feature!");
2265 // Special case the error message for the very common case where only
2266 // a single subtarget feature is missing.
2267 std::string Msg = "instruction requires:";
2269 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2270 if (ErrorInfo & Mask) {
2272 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2276 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2278 case Match_InvalidOperand:
2279 WasOriginallyInvalidOperand = true;
2281 case Match_MnemonicFail:
2285 // FIXME: Ideally, we would only attempt suffix matches for things which are
2286 // valid prefixes, and we could just infer the right unambiguous
2287 // type. However, that requires substantially more matcher support than the
2290 // Change the operand to point to a temporary token.
2291 StringRef Base = Op->getToken();
2292 SmallString<16> Tmp;
2295 Op->setTokenValue(Tmp.str());
2297 // If this instruction starts with an 'f', then it is a floating point stack
2298 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2299 // 80-bit floating point, which use the suffixes s,l,t respectively.
2301 // Otherwise, we assume that this may be an integer instruction, which comes
2302 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2303 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2305 // Check for the various suffix matches.
2306 Tmp[Base.size()] = Suffixes[0];
2307 unsigned ErrorInfoIgnore;
2308 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2309 unsigned Match1, Match2, Match3, Match4;
2311 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2312 MatchingInlineAsm, isParsingIntelSyntax());
2313 // If this returned as a missing feature failure, remember that.
2314 if (Match1 == Match_MissingFeature)
2315 ErrorInfoMissingFeature = ErrorInfoIgnore;
2316 Tmp[Base.size()] = Suffixes[1];
2317 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2318 MatchingInlineAsm, isParsingIntelSyntax());
2319 // If this returned as a missing feature failure, remember that.
2320 if (Match2 == Match_MissingFeature)
2321 ErrorInfoMissingFeature = ErrorInfoIgnore;
2322 Tmp[Base.size()] = Suffixes[2];
2323 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2324 MatchingInlineAsm, isParsingIntelSyntax());
2325 // If this returned as a missing feature failure, remember that.
2326 if (Match3 == Match_MissingFeature)
2327 ErrorInfoMissingFeature = ErrorInfoIgnore;
2328 Tmp[Base.size()] = Suffixes[3];
2329 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2330 MatchingInlineAsm, isParsingIntelSyntax());
2331 // If this returned as a missing feature failure, remember that.
2332 if (Match4 == Match_MissingFeature)
2333 ErrorInfoMissingFeature = ErrorInfoIgnore;
2335 // Restore the old token.
2336 Op->setTokenValue(Base);
2338 // If exactly one matched, then we treat that as a successful match (and the
2339 // instruction will already have been filled in correctly, since the failing
2340 // matches won't have modified it).
2341 unsigned NumSuccessfulMatches =
2342 (Match1 == Match_Success) + (Match2 == Match_Success) +
2343 (Match3 == Match_Success) + (Match4 == Match_Success);
2344 if (NumSuccessfulMatches == 1) {
2346 if (!MatchingInlineAsm)
2347 Out.EmitInstruction(Inst);
2348 Opcode = Inst.getOpcode();
2352 // Otherwise, the match failed, try to produce a decent error message.
2354 // If we had multiple suffix matches, then identify this as an ambiguous
2356 if (NumSuccessfulMatches > 1) {
2358 unsigned NumMatches = 0;
2359 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2360 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2361 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2362 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2364 SmallString<126> Msg;
2365 raw_svector_ostream OS(Msg);
2366 OS << "ambiguous instructions require an explicit suffix (could be ";
2367 for (unsigned i = 0; i != NumMatches; ++i) {
2370 if (i + 1 == NumMatches)
2372 OS << "'" << Base << MatchChars[i] << "'";
2375 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2379 // Okay, we know that none of the variants matched successfully.
2381 // If all of the instructions reported an invalid mnemonic, then the original
2382 // mnemonic was invalid.
2383 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2384 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2385 if (!WasOriginallyInvalidOperand) {
2386 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2388 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2389 Ranges, MatchingInlineAsm);
2392 // Recover location info for the operand if we know which was the problem.
2393 if (ErrorInfo != ~0U) {
2394 if (ErrorInfo >= Operands.size())
2395 return Error(IDLoc, "too few operands for instruction",
2396 EmptyRanges, MatchingInlineAsm);
2398 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2399 if (Operand->getStartLoc().isValid()) {
2400 SMRange OperandRange = Operand->getLocRange();
2401 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2402 OperandRange, MatchingInlineAsm);
2406 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2410 // If one instruction matched with a missing feature, report this as a
2412 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2413 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2414 std::string Msg = "instruction requires:";
2416 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2417 if (ErrorInfoMissingFeature & Mask) {
2419 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2423 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2426 // If one instruction matched with an invalid operand, report this as an
2428 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2429 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2430 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2435 // If all of these were an outright failure, report it in a useless way.
2436 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2437 EmptyRanges, MatchingInlineAsm);
2442 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2443 StringRef IDVal = DirectiveID.getIdentifier();
2444 if (IDVal == ".word")
2445 return ParseDirectiveWord(2, DirectiveID.getLoc());
2446 else if (IDVal.startswith(".code"))
2447 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2448 else if (IDVal.startswith(".att_syntax")) {
2449 getParser().setAssemblerDialect(0);
2451 } else if (IDVal.startswith(".intel_syntax")) {
2452 getParser().setAssemblerDialect(1);
2453 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2454 if(Parser.getTok().getString() == "noprefix") {
2455 // FIXME : Handle noprefix
2465 /// ParseDirectiveWord
2466 /// ::= .word [ expression (, expression)* ]
2467 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2468 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2470 const MCExpr *Value;
2471 if (getParser().parseExpression(Value))
2474 getParser().getStreamer().EmitValue(Value, Size);
2476 if (getLexer().is(AsmToken::EndOfStatement))
2479 // FIXME: Improve diagnostic.
2480 if (getLexer().isNot(AsmToken::Comma))
2481 return Error(L, "unexpected token in directive");
2490 /// ParseDirectiveCode
2491 /// ::= .code32 | .code64
2492 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2493 if (IDVal == ".code32") {
2495 if (is64BitMode()) {
2497 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2499 } else if (IDVal == ".code64") {
2501 if (!is64BitMode()) {
2503 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2506 return Error(L, "unexpected directive " + IDVal);
2512 // Force static initialization.
2513 extern "C" void LLVMInitializeX86AsmParser() {
2514 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2515 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2518 #define GET_REGISTER_MATCHER
2519 #define GET_MATCHER_IMPLEMENTATION
2520 #define GET_SUBTARGET_FEATURE_NAME
2521 #include "X86GenAsmMatcher.inc"