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 "llvm/Target/TargetAsmParser.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCStreamer.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCParser/MCAsmLexer.h"
18 #include "llvm/MC/MCParser/MCAsmParser.h"
19 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
20 #include "llvm/Support/SourceMgr.h"
21 #include "llvm/Target/TargetRegistry.h"
22 #include "llvm/Target/TargetAsmParser.h"
28 class X86ATTAsmParser : public TargetAsmParser {
32 MCAsmParser &getParser() const { return Parser; }
34 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
36 void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
38 bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
40 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
42 X86Operand *ParseOperand();
43 X86Operand *ParseMemOperand();
45 bool ParseDirectiveWord(unsigned Size, SMLoc L);
47 /// @name Auto-generated Match Functions
50 bool MatchInstruction(const SmallVectorImpl<MCParsedAsmOperand*> &Operands,
56 X86ATTAsmParser(const Target &T, MCAsmParser &_Parser)
57 : TargetAsmParser(T), Parser(_Parser) {}
59 virtual bool ParseInstruction(const StringRef &Name, SMLoc NameLoc,
60 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
62 virtual bool ParseDirective(AsmToken DirectiveID);
65 } // end anonymous namespace
67 /// @name Auto-generated Match Functions
70 static unsigned MatchRegisterName(StringRef Name);
76 /// X86Operand - Instances of this class represent a parsed X86 machine
78 struct X86Operand : public MCParsedAsmOperand {
86 SMLoc StartLoc, EndLoc;
111 X86Operand(KindTy K, SMLoc Start, SMLoc End)
112 : Kind(K), StartLoc(Start), EndLoc(End) {}
114 /// getStartLoc - Get the location of the first token of this operand.
115 SMLoc getStartLoc() const { return StartLoc; }
116 /// getEndLoc - Get the location of the last token of this operand.
117 SMLoc getEndLoc() const { return EndLoc; }
119 StringRef getToken() const {
120 assert(Kind == Token && "Invalid access!");
121 return StringRef(Tok.Data, Tok.Length);
124 unsigned getReg() const {
125 assert(Kind == Register && "Invalid access!");
129 const MCExpr *getImm() const {
130 assert(Kind == Immediate && "Invalid access!");
134 const MCExpr *getMemDisp() const {
135 assert(Kind == Memory && "Invalid access!");
138 unsigned getMemSegReg() const {
139 assert(Kind == Memory && "Invalid access!");
142 unsigned getMemBaseReg() const {
143 assert(Kind == Memory && "Invalid access!");
146 unsigned getMemIndexReg() const {
147 assert(Kind == Memory && "Invalid access!");
150 unsigned getMemScale() const {
151 assert(Kind == Memory && "Invalid access!");
155 bool isToken() const {return Kind == Token; }
157 bool isImm() const { return Kind == Immediate; }
159 bool isImmSExt8() const {
160 // Accept immediates which fit in 8 bits when sign extended, and
161 // non-absolute immediates.
165 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
166 int64_t Value = CE->getValue();
167 return Value == (int64_t) (int8_t) Value;
173 bool isMem() const { return Kind == Memory; }
175 bool isAbsMem() const {
176 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
177 !getMemIndexReg() && getMemScale() == 1;
180 bool isNoSegMem() const {
181 return Kind == Memory && !getMemSegReg();
184 bool isReg() const { return Kind == Register; }
186 void addRegOperands(MCInst &Inst, unsigned N) const {
187 assert(N == 1 && "Invalid number of operands!");
188 Inst.addOperand(MCOperand::CreateReg(getReg()));
191 void addImmOperands(MCInst &Inst, unsigned N) const {
192 assert(N == 1 && "Invalid number of operands!");
193 Inst.addOperand(MCOperand::CreateExpr(getImm()));
196 void addImmSExt8Operands(MCInst &Inst, unsigned N) const {
197 // FIXME: Support user customization of the render method.
198 assert(N == 1 && "Invalid number of operands!");
199 Inst.addOperand(MCOperand::CreateExpr(getImm()));
202 void addMemOperands(MCInst &Inst, unsigned N) const {
203 assert((N == 5) && "Invalid number of operands!");
204 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
205 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
206 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
207 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
208 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
211 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
212 assert((N == 1) && "Invalid number of operands!");
213 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
216 void addNoSegMemOperands(MCInst &Inst, unsigned N) const {
217 assert((N == 4) && "Invalid number of operands!");
218 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
219 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
220 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
221 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
224 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
225 X86Operand *Res = new X86Operand(Token, Loc, Loc);
226 Res->Tok.Data = Str.data();
227 Res->Tok.Length = Str.size();
231 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
232 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
233 Res->Reg.RegNo = RegNo;
237 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
238 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
243 /// Create an absolute memory operand.
244 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
246 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
248 Res->Mem.Disp = Disp;
249 Res->Mem.BaseReg = 0;
250 Res->Mem.IndexReg = 0;
255 /// Create a generalized memory operand.
256 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
257 unsigned BaseReg, unsigned IndexReg,
258 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
259 // We should never just have a displacement, that should be parsed as an
260 // absolute memory operand.
261 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
263 // The scale should always be one of {1,2,4,8}.
264 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
266 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
267 Res->Mem.SegReg = SegReg;
268 Res->Mem.Disp = Disp;
269 Res->Mem.BaseReg = BaseReg;
270 Res->Mem.IndexReg = IndexReg;
271 Res->Mem.Scale = Scale;
276 } // end anonymous namespace.
279 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
280 SMLoc &StartLoc, SMLoc &EndLoc) {
282 const AsmToken &TokPercent = Parser.getTok();
283 assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
284 StartLoc = TokPercent.getLoc();
285 Parser.Lex(); // Eat percent token.
287 const AsmToken &Tok = Parser.getTok();
288 if (Tok.isNot(AsmToken::Identifier))
289 return Error(Tok.getLoc(), "invalid register name");
291 // FIXME: Validate register for the current architecture; we have to do
292 // validation later, so maybe there is no need for this here.
293 RegNo = MatchRegisterName(Tok.getString());
296 return Error(Tok.getLoc(), "invalid register name");
298 EndLoc = Tok.getLoc();
299 Parser.Lex(); // Eat identifier token.
303 X86Operand *X86ATTAsmParser::ParseOperand() {
304 switch (getLexer().getKind()) {
306 return ParseMemOperand();
307 case AsmToken::Percent: {
308 // FIXME: if a segment register, this could either be just the seg reg, or
309 // the start of a memory operand.
312 if (ParseRegister(RegNo, Start, End)) return 0;
313 return X86Operand::CreateReg(RegNo, Start, End);
315 case AsmToken::Dollar: {
317 SMLoc Start = Parser.getTok().getLoc(), End;
320 if (getParser().ParseExpression(Val, End))
322 return X86Operand::CreateImm(Val, Start, End);
327 /// ParseMemOperand: segment: disp(basereg, indexreg, scale)
328 X86Operand *X86ATTAsmParser::ParseMemOperand() {
329 SMLoc MemStart = Parser.getTok().getLoc();
331 // FIXME: If SegReg ':' (e.g. %gs:), eat and remember.
334 // We have to disambiguate a parenthesized expression "(4+5)" from the start
335 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
336 // only way to do this without lookahead is to eat the '(' and see what is
338 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
339 if (getLexer().isNot(AsmToken::LParen)) {
341 if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
343 // After parsing the base expression we could either have a parenthesized
344 // memory address or not. If not, return now. If so, eat the (.
345 if (getLexer().isNot(AsmToken::LParen)) {
346 // Unless we have a segment register, treat this as an immediate.
348 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
349 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
355 // Okay, we have a '('. We don't know if this is an expression or not, but
356 // so we have to eat the ( to see beyond it.
357 SMLoc LParenLoc = Parser.getTok().getLoc();
358 Parser.Lex(); // Eat the '('.
360 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
361 // Nothing to do here, fall into the code below with the '(' part of the
362 // memory operand consumed.
366 // It must be an parenthesized expression, parse it now.
367 if (getParser().ParseParenExpression(Disp, ExprEnd))
370 // After parsing the base expression we could either have a parenthesized
371 // memory address or not. If not, return now. If so, eat the (.
372 if (getLexer().isNot(AsmToken::LParen)) {
373 // Unless we have a segment register, treat this as an immediate.
375 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
376 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
384 // If we reached here, then we just ate the ( of the memory operand. Process
385 // the rest of the memory operand.
386 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
388 if (getLexer().is(AsmToken::Percent)) {
390 if (ParseRegister(BaseReg, L, L)) return 0;
393 if (getLexer().is(AsmToken::Comma)) {
394 Parser.Lex(); // Eat the comma.
396 // Following the comma we should have either an index register, or a scale
397 // value. We don't support the later form, but we want to parse it
400 // Not that even though it would be completely consistent to support syntax
401 // like "1(%eax,,1)", the assembler doesn't.
402 if (getLexer().is(AsmToken::Percent)) {
404 if (ParseRegister(IndexReg, L, L)) return 0;
406 if (getLexer().isNot(AsmToken::RParen)) {
407 // Parse the scale amount:
408 // ::= ',' [scale-expression]
409 if (getLexer().isNot(AsmToken::Comma)) {
410 Error(Parser.getTok().getLoc(),
411 "expected comma in scale expression");
414 Parser.Lex(); // Eat the comma.
416 if (getLexer().isNot(AsmToken::RParen)) {
417 SMLoc Loc = Parser.getTok().getLoc();
420 if (getParser().ParseAbsoluteExpression(ScaleVal))
423 // Validate the scale amount.
424 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
425 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
428 Scale = (unsigned)ScaleVal;
431 } else if (getLexer().isNot(AsmToken::RParen)) {
432 // Otherwise we have the unsupported form of a scale amount without an
434 SMLoc Loc = Parser.getTok().getLoc();
437 if (getParser().ParseAbsoluteExpression(Value))
440 Error(Loc, "cannot have scale factor without index register");
445 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
446 if (getLexer().isNot(AsmToken::RParen)) {
447 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
450 SMLoc MemEnd = Parser.getTok().getLoc();
451 Parser.Lex(); // Eat the ')'.
453 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
457 bool X86ATTAsmParser::
458 ParseInstruction(const StringRef &Name, SMLoc NameLoc,
459 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
460 // FIXME: Hack to recognize "sal..." for now. We need a way to represent
461 // alternative syntaxes in the .td file, without requiring instruction
463 if (Name.startswith("sal")) {
464 std::string Tmp = "shl" + Name.substr(3).str();
465 Operands.push_back(X86Operand::CreateToken(Tmp, NameLoc));
467 // FIXME: This is a hack. We eventually want to add a general pattern
468 // mechanism to be used in the table gen file for these assembly names that
469 // use the same opcodes. Also we should only allow the "alternate names"
470 // for rep and repne with the instructions they can only appear with.
471 StringRef PatchedName = Name;
472 if (Name == "repe" || Name == "repz")
474 else if (Name == "repnz")
475 PatchedName = "repne";
476 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
479 if (getLexer().isNot(AsmToken::EndOfStatement)) {
481 // Parse '*' modifier.
482 if (getLexer().is(AsmToken::Star)) {
483 SMLoc Loc = Parser.getTok().getLoc();
484 Operands.push_back(X86Operand::CreateToken("*", Loc));
485 Parser.Lex(); // Eat the star.
488 // Read the first operand.
489 if (X86Operand *Op = ParseOperand())
490 Operands.push_back(Op);
494 while (getLexer().is(AsmToken::Comma)) {
495 Parser.Lex(); // Eat the comma.
497 // Parse and remember the operand.
498 if (X86Operand *Op = ParseOperand())
499 Operands.push_back(Op);
508 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
509 StringRef IDVal = DirectiveID.getIdentifier();
510 if (IDVal == ".word")
511 return ParseDirectiveWord(2, DirectiveID.getLoc());
515 /// ParseDirectiveWord
516 /// ::= .word [ expression (, expression)* ]
517 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
518 if (getLexer().isNot(AsmToken::EndOfStatement)) {
521 if (getParser().ParseExpression(Value))
524 getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
526 if (getLexer().is(AsmToken::EndOfStatement))
529 // FIXME: Improve diagnostic.
530 if (getLexer().isNot(AsmToken::Comma))
531 return Error(L, "unexpected token in directive");
540 extern "C" void LLVMInitializeX86AsmLexer();
542 // Force static initialization.
543 extern "C" void LLVMInitializeX86AsmParser() {
544 RegisterAsmParser<X86ATTAsmParser> X(TheX86_32Target);
545 RegisterAsmParser<X86ATTAsmParser> Y(TheX86_64Target);
546 LLVMInitializeX86AsmLexer();
549 #include "X86GenAsmMatcher.inc"