1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "MCTargetDesc/X86BaseInfo.h" 11 #include "llvm/ADT/APFloat.h" 12 #include "llvm/ADT/STLExtras.h" 13 #include "llvm/ADT/SmallString.h" 14 #include "llvm/ADT/SmallVector.h" 15 #include "llvm/ADT/StringSwitch.h" 16 #include "llvm/ADT/Twine.h" 17 #include "llvm/MC/MCContext.h" 18 #include "llvm/MC/MCExpr.h" 19 #include "llvm/MC/MCInst.h" 20 #include "llvm/MC/MCParser/MCAsmLexer.h" 21 #include "llvm/MC/MCParser/MCAsmParser.h" 22 #include "llvm/MC/MCParser/MCParsedAsmOperand.h" 23 #include "llvm/MC/MCRegisterInfo.h" 24 #include "llvm/MC/MCStreamer.h" 25 #include "llvm/MC/MCSubtargetInfo.h" 26 #include "llvm/MC/MCSymbol.h" 27 #include "llvm/MC/MCTargetAsmParser.h" 28 #include "llvm/Support/SourceMgr.h" 29 #include "llvm/Support/TargetRegistry.h" 30 #include "llvm/Support/raw_ostream.h" 31 32 using namespace llvm; 33 34 namespace { 35 struct X86Operand; 36 37 static const char OpPrecedence[] = { 38 0, // IC_OR 39 1, // IC_AND 40 2, // IC_PLUS 41 2, // IC_MINUS 42 3, // IC_MULTIPLY 43 3, // IC_DIVIDE 44 4, // IC_RPAREN 45 5, // IC_LPAREN 46 0, // IC_IMM 47 0 // IC_REGISTER 48 }; 49 50 class X86AsmParser : public MCTargetAsmParser { 51 MCSubtargetInfo &STI; 52 MCAsmParser &Parser; 53 ParseInstructionInfo *InstInfo; 54 private: 55 SMLoc consumeToken() { 56 SMLoc Result = Parser.getTok().getLoc(); 57 Parser.Lex(); 58 return Result; 59 } 60 61 enum InfixCalculatorTok { 62 IC_OR = 0, 63 IC_AND, 64 IC_PLUS, 65 IC_MINUS, 66 IC_MULTIPLY, 67 IC_DIVIDE, 68 IC_RPAREN, 69 IC_LPAREN, 70 IC_IMM, 71 IC_REGISTER 72 }; 73 74 class InfixCalculator { 75 typedef std::pair< InfixCalculatorTok, int64_t > ICToken; 76 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack; 77 SmallVector<ICToken, 4> PostfixStack; 78 79 public: 80 int64_t popOperand() { 81 assert (!PostfixStack.empty() && "Poped an empty stack!"); 82 ICToken Op = PostfixStack.pop_back_val(); 83 assert ((Op.first == IC_IMM || Op.first == IC_REGISTER) 84 && "Expected and immediate or register!"); 85 return Op.second; 86 } 87 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) { 88 assert ((Op == IC_IMM || Op == IC_REGISTER) && 89 "Unexpected operand!"); 90 PostfixStack.push_back(std::make_pair(Op, Val)); 91 } 92 93 void popOperator() { InfixOperatorStack.pop_back(); } 94 void pushOperator(InfixCalculatorTok Op) { 95 // Push the new operator if the stack is empty. 96 if (InfixOperatorStack.empty()) { 97 InfixOperatorStack.push_back(Op); 98 return; 99 } 100 101 // Push the new operator if it has a higher precedence than the operator 102 // on the top of the stack or the operator on the top of the stack is a 103 // left parentheses. 104 unsigned Idx = InfixOperatorStack.size() - 1; 105 InfixCalculatorTok StackOp = InfixOperatorStack[Idx]; 106 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) { 107 InfixOperatorStack.push_back(Op); 108 return; 109 } 110 111 // The operator on the top of the stack has higher precedence than the 112 // new operator. 113 unsigned ParenCount = 0; 114 while (1) { 115 // Nothing to process. 116 if (InfixOperatorStack.empty()) 117 break; 118 119 Idx = InfixOperatorStack.size() - 1; 120 StackOp = InfixOperatorStack[Idx]; 121 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount)) 122 break; 123 124 // If we have an even parentheses count and we see a left parentheses, 125 // then stop processing. 126 if (!ParenCount && StackOp == IC_LPAREN) 127 break; 128 129 if (StackOp == IC_RPAREN) { 130 ++ParenCount; 131 InfixOperatorStack.pop_back(); 132 } else if (StackOp == IC_LPAREN) { 133 --ParenCount; 134 InfixOperatorStack.pop_back(); 135 } else { 136 InfixOperatorStack.pop_back(); 137 PostfixStack.push_back(std::make_pair(StackOp, 0)); 138 } 139 } 140 // Push the new operator. 141 InfixOperatorStack.push_back(Op); 142 } 143 int64_t execute() { 144 // Push any remaining operators onto the postfix stack. 145 while (!InfixOperatorStack.empty()) { 146 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val(); 147 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN) 148 PostfixStack.push_back(std::make_pair(StackOp, 0)); 149 } 150 151 if (PostfixStack.empty()) 152 return 0; 153 154 SmallVector<ICToken, 16> OperandStack; 155 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) { 156 ICToken Op = PostfixStack[i]; 157 if (Op.first == IC_IMM || Op.first == IC_REGISTER) { 158 OperandStack.push_back(Op); 159 } else { 160 assert (OperandStack.size() > 1 && "Too few operands."); 161 int64_t Val; 162 ICToken Op2 = OperandStack.pop_back_val(); 163 ICToken Op1 = OperandStack.pop_back_val(); 164 switch (Op.first) { 165 default: 166 report_fatal_error("Unexpected operator!"); 167 break; 168 case IC_PLUS: 169 Val = Op1.second + Op2.second; 170 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 171 break; 172 case IC_MINUS: 173 Val = Op1.second - Op2.second; 174 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 175 break; 176 case IC_MULTIPLY: 177 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 178 "Multiply operation with an immediate and a register!"); 179 Val = Op1.second * Op2.second; 180 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 181 break; 182 case IC_DIVIDE: 183 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 184 "Divide operation with an immediate and a register!"); 185 assert (Op2.second != 0 && "Division by zero!"); 186 Val = Op1.second / Op2.second; 187 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 188 break; 189 case IC_OR: 190 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 191 "Or operation with an immediate and a register!"); 192 Val = Op1.second | Op2.second; 193 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 194 break; 195 case IC_AND: 196 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 197 "And operation with an immediate and a register!"); 198 Val = Op1.second & Op2.second; 199 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 200 break; 201 } 202 } 203 } 204 assert (OperandStack.size() == 1 && "Expected a single result."); 205 return OperandStack.pop_back_val().second; 206 } 207 }; 208 209 enum IntelExprState { 210 IES_OR, 211 IES_AND, 212 IES_PLUS, 213 IES_MINUS, 214 IES_MULTIPLY, 215 IES_DIVIDE, 216 IES_LBRAC, 217 IES_RBRAC, 218 IES_LPAREN, 219 IES_RPAREN, 220 IES_REGISTER, 221 IES_INTEGER, 222 IES_IDENTIFIER, 223 IES_ERROR 224 }; 225 226 class IntelExprStateMachine { 227 IntelExprState State, PrevState; 228 unsigned BaseReg, IndexReg, TmpReg, Scale; 229 int64_t Imm; 230 const MCExpr *Sym; 231 StringRef SymName; 232 bool StopOnLBrac, AddImmPrefix; 233 InfixCalculator IC; 234 InlineAsmIdentifierInfo Info; 235 public: 236 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) : 237 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0), 238 Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac), 239 AddImmPrefix(addimmprefix) { Info.clear(); } 240 241 unsigned getBaseReg() { return BaseReg; } 242 unsigned getIndexReg() { return IndexReg; } 243 unsigned getScale() { return Scale; } 244 const MCExpr *getSym() { return Sym; } 245 StringRef getSymName() { return SymName; } 246 int64_t getImm() { return Imm + IC.execute(); } 247 bool isValidEndState() { 248 return State == IES_RBRAC || State == IES_INTEGER; 249 } 250 bool getStopOnLBrac() { return StopOnLBrac; } 251 bool getAddImmPrefix() { return AddImmPrefix; } 252 bool hadError() { return State == IES_ERROR; } 253 254 InlineAsmIdentifierInfo &getIdentifierInfo() { 255 return Info; 256 } 257 258 void onOr() { 259 IntelExprState CurrState = State; 260 switch (State) { 261 default: 262 State = IES_ERROR; 263 break; 264 case IES_INTEGER: 265 case IES_RPAREN: 266 case IES_REGISTER: 267 State = IES_OR; 268 IC.pushOperator(IC_OR); 269 break; 270 } 271 PrevState = CurrState; 272 } 273 void onAnd() { 274 IntelExprState CurrState = State; 275 switch (State) { 276 default: 277 State = IES_ERROR; 278 break; 279 case IES_INTEGER: 280 case IES_RPAREN: 281 case IES_REGISTER: 282 State = IES_AND; 283 IC.pushOperator(IC_AND); 284 break; 285 } 286 PrevState = CurrState; 287 } 288 void onPlus() { 289 IntelExprState CurrState = State; 290 switch (State) { 291 default: 292 State = IES_ERROR; 293 break; 294 case IES_INTEGER: 295 case IES_RPAREN: 296 case IES_REGISTER: 297 State = IES_PLUS; 298 IC.pushOperator(IC_PLUS); 299 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) { 300 // If we already have a BaseReg, then assume this is the IndexReg with 301 // a scale of 1. 302 if (!BaseReg) { 303 BaseReg = TmpReg; 304 } else { 305 assert (!IndexReg && "BaseReg/IndexReg already set!"); 306 IndexReg = TmpReg; 307 Scale = 1; 308 } 309 } 310 break; 311 } 312 PrevState = CurrState; 313 } 314 void onMinus() { 315 IntelExprState CurrState = State; 316 switch (State) { 317 default: 318 State = IES_ERROR; 319 break; 320 case IES_PLUS: 321 case IES_MULTIPLY: 322 case IES_DIVIDE: 323 case IES_LPAREN: 324 case IES_RPAREN: 325 case IES_LBRAC: 326 case IES_RBRAC: 327 case IES_INTEGER: 328 case IES_REGISTER: 329 State = IES_MINUS; 330 // Only push the minus operator if it is not a unary operator. 331 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS || 332 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE || 333 CurrState == IES_LPAREN || CurrState == IES_LBRAC)) 334 IC.pushOperator(IC_MINUS); 335 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) { 336 // If we already have a BaseReg, then assume this is the IndexReg with 337 // a scale of 1. 338 if (!BaseReg) { 339 BaseReg = TmpReg; 340 } else { 341 assert (!IndexReg && "BaseReg/IndexReg already set!"); 342 IndexReg = TmpReg; 343 Scale = 1; 344 } 345 } 346 break; 347 } 348 PrevState = CurrState; 349 } 350 void onRegister(unsigned Reg) { 351 IntelExprState CurrState = State; 352 switch (State) { 353 default: 354 State = IES_ERROR; 355 break; 356 case IES_PLUS: 357 case IES_LPAREN: 358 State = IES_REGISTER; 359 TmpReg = Reg; 360 IC.pushOperand(IC_REGISTER); 361 break; 362 case IES_MULTIPLY: 363 // Index Register - Scale * Register 364 if (PrevState == IES_INTEGER) { 365 assert (!IndexReg && "IndexReg already set!"); 366 State = IES_REGISTER; 367 IndexReg = Reg; 368 // Get the scale and replace the 'Scale * Register' with '0'. 369 Scale = IC.popOperand(); 370 IC.pushOperand(IC_IMM); 371 IC.popOperator(); 372 } else { 373 State = IES_ERROR; 374 } 375 break; 376 } 377 PrevState = CurrState; 378 } 379 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) { 380 PrevState = State; 381 switch (State) { 382 default: 383 State = IES_ERROR; 384 break; 385 case IES_PLUS: 386 case IES_MINUS: 387 State = IES_INTEGER; 388 Sym = SymRef; 389 SymName = SymRefName; 390 IC.pushOperand(IC_IMM); 391 break; 392 } 393 } 394 bool onInteger(int64_t TmpInt, StringRef &ErrMsg) { 395 IntelExprState CurrState = State; 396 switch (State) { 397 default: 398 State = IES_ERROR; 399 break; 400 case IES_PLUS: 401 case IES_MINUS: 402 case IES_OR: 403 case IES_AND: 404 case IES_DIVIDE: 405 case IES_MULTIPLY: 406 case IES_LPAREN: 407 State = IES_INTEGER; 408 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) { 409 // Index Register - Register * Scale 410 assert (!IndexReg && "IndexReg already set!"); 411 IndexReg = TmpReg; 412 Scale = TmpInt; 413 if(Scale != 1 && Scale != 2 && Scale != 4 && Scale != 8) { 414 ErrMsg = "scale factor in address must be 1, 2, 4 or 8"; 415 return true; 416 } 417 // Get the scale and replace the 'Register * Scale' with '0'. 418 IC.popOperator(); 419 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS || 420 PrevState == IES_OR || PrevState == IES_AND || 421 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE || 422 PrevState == IES_LPAREN || PrevState == IES_LBRAC) && 423 CurrState == IES_MINUS) { 424 // Unary minus. No need to pop the minus operand because it was never 425 // pushed. 426 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm. 427 } else { 428 IC.pushOperand(IC_IMM, TmpInt); 429 } 430 break; 431 } 432 PrevState = CurrState; 433 return false; 434 } 435 void onStar() { 436 PrevState = State; 437 switch (State) { 438 default: 439 State = IES_ERROR; 440 break; 441 case IES_INTEGER: 442 case IES_REGISTER: 443 case IES_RPAREN: 444 State = IES_MULTIPLY; 445 IC.pushOperator(IC_MULTIPLY); 446 break; 447 } 448 } 449 void onDivide() { 450 PrevState = State; 451 switch (State) { 452 default: 453 State = IES_ERROR; 454 break; 455 case IES_INTEGER: 456 case IES_RPAREN: 457 State = IES_DIVIDE; 458 IC.pushOperator(IC_DIVIDE); 459 break; 460 } 461 } 462 void onLBrac() { 463 PrevState = State; 464 switch (State) { 465 default: 466 State = IES_ERROR; 467 break; 468 case IES_RBRAC: 469 State = IES_PLUS; 470 IC.pushOperator(IC_PLUS); 471 break; 472 } 473 } 474 void onRBrac() { 475 IntelExprState CurrState = State; 476 switch (State) { 477 default: 478 State = IES_ERROR; 479 break; 480 case IES_INTEGER: 481 case IES_REGISTER: 482 case IES_RPAREN: 483 State = IES_RBRAC; 484 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) { 485 // If we already have a BaseReg, then assume this is the IndexReg with 486 // a scale of 1. 487 if (!BaseReg) { 488 BaseReg = TmpReg; 489 } else { 490 assert (!IndexReg && "BaseReg/IndexReg already set!"); 491 IndexReg = TmpReg; 492 Scale = 1; 493 } 494 } 495 break; 496 } 497 PrevState = CurrState; 498 } 499 void onLParen() { 500 IntelExprState CurrState = State; 501 switch (State) { 502 default: 503 State = IES_ERROR; 504 break; 505 case IES_PLUS: 506 case IES_MINUS: 507 case IES_OR: 508 case IES_AND: 509 case IES_MULTIPLY: 510 case IES_DIVIDE: 511 case IES_LPAREN: 512 // FIXME: We don't handle this type of unary minus, yet. 513 if ((PrevState == IES_PLUS || PrevState == IES_MINUS || 514 PrevState == IES_OR || PrevState == IES_AND || 515 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE || 516 PrevState == IES_LPAREN || PrevState == IES_LBRAC) && 517 CurrState == IES_MINUS) { 518 State = IES_ERROR; 519 break; 520 } 521 State = IES_LPAREN; 522 IC.pushOperator(IC_LPAREN); 523 break; 524 } 525 PrevState = CurrState; 526 } 527 void onRParen() { 528 PrevState = State; 529 switch (State) { 530 default: 531 State = IES_ERROR; 532 break; 533 case IES_INTEGER: 534 case IES_REGISTER: 535 case IES_RPAREN: 536 State = IES_RPAREN; 537 IC.pushOperator(IC_RPAREN); 538 break; 539 } 540 } 541 }; 542 543 MCAsmParser &getParser() const { return Parser; } 544 545 MCAsmLexer &getLexer() const { return Parser.getLexer(); } 546 547 bool Error(SMLoc L, const Twine &Msg, 548 ArrayRef<SMRange> Ranges = None, 549 bool MatchingInlineAsm = false) { 550 if (MatchingInlineAsm) return true; 551 return Parser.Error(L, Msg, Ranges); 552 } 553 554 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) { 555 Error(Loc, Msg); 556 return 0; 557 } 558 559 X86Operand *DefaultMemSIOperand(SMLoc Loc); 560 X86Operand *DefaultMemDIOperand(SMLoc Loc); 561 X86Operand *ParseOperand(); 562 X86Operand *ParseATTOperand(); 563 X86Operand *ParseIntelOperand(); 564 X86Operand *ParseIntelOffsetOfOperator(); 565 bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp); 566 X86Operand *ParseIntelOperator(unsigned OpKind); 567 X86Operand *ParseIntelSegmentOverride(unsigned SegReg, SMLoc Start, unsigned Size); 568 X86Operand *ParseIntelMemOperand(int64_t ImmDisp, SMLoc StartLoc, 569 unsigned Size); 570 bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End); 571 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start, 572 int64_t ImmDisp, unsigned Size); 573 bool ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier, 574 InlineAsmIdentifierInfo &Info, 575 bool IsUnevaluatedOperand, SMLoc &End); 576 577 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc); 578 579 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp, 580 unsigned BaseReg, unsigned IndexReg, 581 unsigned Scale, SMLoc Start, SMLoc End, 582 unsigned Size, StringRef Identifier, 583 InlineAsmIdentifierInfo &Info); 584 585 bool ParseDirectiveWord(unsigned Size, SMLoc L); 586 bool ParseDirectiveCode(StringRef IDVal, SMLoc L); 587 588 bool processInstruction(MCInst &Inst, 589 const SmallVectorImpl<MCParsedAsmOperand*> &Ops); 590 591 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, 592 SmallVectorImpl<MCParsedAsmOperand*> &Operands, 593 MCStreamer &Out, unsigned &ErrorInfo, 594 bool MatchingInlineAsm); 595 596 /// doSrcDstMatch - Returns true if operands are matching in their 597 /// word size (%si and %di, %esi and %edi, etc.). Order depends on 598 /// the parsing mode (Intel vs. AT&T). 599 bool doSrcDstMatch(X86Operand &Op1, X86Operand &Op2); 600 601 bool is64BitMode() const { 602 // FIXME: Can tablegen auto-generate this? 603 return (STI.getFeatureBits() & X86::Mode64Bit) != 0; 604 } 605 bool is32BitMode() const { 606 // FIXME: Can tablegen auto-generate this? 607 return (STI.getFeatureBits() & X86::Mode32Bit) != 0; 608 } 609 bool is16BitMode() const { 610 // FIXME: Can tablegen auto-generate this? 611 return (STI.getFeatureBits() & X86::Mode16Bit) != 0; 612 } 613 void SwitchMode(uint64_t mode) { 614 uint64_t oldMode = STI.getFeatureBits() & 615 (X86::Mode64Bit | X86::Mode32Bit | X86::Mode16Bit); 616 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(oldMode | mode)); 617 setAvailableFeatures(FB); 618 assert(mode == (STI.getFeatureBits() & 619 (X86::Mode64Bit | X86::Mode32Bit | X86::Mode16Bit))); 620 } 621 622 bool isParsingIntelSyntax() { 623 return getParser().getAssemblerDialect(); 624 } 625 626 /// @name Auto-generated Matcher Functions 627 /// { 628 629 #define GET_ASSEMBLER_HEADER 630 #include "X86GenAsmMatcher.inc" 631 632 /// } 633 634 public: 635 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser, 636 const MCInstrInfo &MII) 637 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) { 638 639 // Initialize the set of available features. 640 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits())); 641 } 642 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc); 643 644 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name, 645 SMLoc NameLoc, 646 SmallVectorImpl<MCParsedAsmOperand*> &Operands); 647 648 virtual bool ParseDirective(AsmToken DirectiveID); 649 }; 650 } // end anonymous namespace 651 652 /// @name Auto-generated Match Functions 653 /// { 654 655 static unsigned MatchRegisterName(StringRef Name); 656 657 /// } 658 659 static bool isImmSExti16i8Value(uint64_t Value) { 660 return (( Value <= 0x000000000000007FULL)|| 661 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)|| 662 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL)); 663 } 664 665 static bool isImmSExti32i8Value(uint64_t Value) { 666 return (( Value <= 0x000000000000007FULL)|| 667 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)|| 668 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL)); 669 } 670 671 static bool isImmZExtu32u8Value(uint64_t Value) { 672 return (Value <= 0x00000000000000FFULL); 673 } 674 675 static bool isImmSExti64i8Value(uint64_t Value) { 676 return (( Value <= 0x000000000000007FULL)|| 677 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL)); 678 } 679 680 static bool isImmSExti64i32Value(uint64_t Value) { 681 return (( Value <= 0x000000007FFFFFFFULL)|| 682 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL)); 683 } 684 namespace { 685 686 /// X86Operand - Instances of this class represent a parsed X86 machine 687 /// instruction. 688 struct X86Operand : public MCParsedAsmOperand { 689 enum KindTy { 690 Token, 691 Register, 692 Immediate, 693 Memory 694 } Kind; 695 696 SMLoc StartLoc, EndLoc; 697 SMLoc OffsetOfLoc; 698 StringRef SymName; 699 void *OpDecl; 700 bool AddressOf; 701 702 struct TokOp { 703 const char *Data; 704 unsigned Length; 705 }; 706 707 struct RegOp { 708 unsigned RegNo; 709 }; 710 711 struct ImmOp { 712 const MCExpr *Val; 713 }; 714 715 struct MemOp { 716 unsigned SegReg; 717 const MCExpr *Disp; 718 unsigned BaseReg; 719 unsigned IndexReg; 720 unsigned Scale; 721 unsigned Size; 722 }; 723 724 union { 725 struct TokOp Tok; 726 struct RegOp Reg; 727 struct ImmOp Imm; 728 struct MemOp Mem; 729 }; 730 731 X86Operand(KindTy K, SMLoc Start, SMLoc End) 732 : Kind(K), StartLoc(Start), EndLoc(End) {} 733 734 StringRef getSymName() { return SymName; } 735 void *getOpDecl() { return OpDecl; } 736 737 /// getStartLoc - Get the location of the first token of this operand. 738 SMLoc getStartLoc() const { return StartLoc; } 739 /// getEndLoc - Get the location of the last token of this operand. 740 SMLoc getEndLoc() const { return EndLoc; } 741 /// getLocRange - Get the range between the first and last token of this 742 /// operand. 743 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); } 744 /// getOffsetOfLoc - Get the location of the offset operator. 745 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; } 746 747 virtual void print(raw_ostream &OS) const {} 748 749 StringRef getToken() const { 750 assert(Kind == Token && "Invalid access!"); 751 return StringRef(Tok.Data, Tok.Length); 752 } 753 void setTokenValue(StringRef Value) { 754 assert(Kind == Token && "Invalid access!"); 755 Tok.Data = Value.data(); 756 Tok.Length = Value.size(); 757 } 758 759 unsigned getReg() const { 760 assert(Kind == Register && "Invalid access!"); 761 return Reg.RegNo; 762 } 763 764 const MCExpr *getImm() const { 765 assert(Kind == Immediate && "Invalid access!"); 766 return Imm.Val; 767 } 768 769 const MCExpr *getMemDisp() const { 770 assert(Kind == Memory && "Invalid access!"); 771 return Mem.Disp; 772 } 773 unsigned getMemSegReg() const { 774 assert(Kind == Memory && "Invalid access!"); 775 return Mem.SegReg; 776 } 777 unsigned getMemBaseReg() const { 778 assert(Kind == Memory && "Invalid access!"); 779 return Mem.BaseReg; 780 } 781 unsigned getMemIndexReg() const { 782 assert(Kind == Memory && "Invalid access!"); 783 return Mem.IndexReg; 784 } 785 unsigned getMemScale() const { 786 assert(Kind == Memory && "Invalid access!"); 787 return Mem.Scale; 788 } 789 790 bool isToken() const {return Kind == Token; } 791 792 bool isImm() const { return Kind == Immediate; } 793 794 bool isImmSExti16i8() const { 795 if (!isImm()) 796 return false; 797 798 // If this isn't a constant expr, just assume it fits and let relaxation 799 // handle it. 800 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()); 801 if (!CE) 802 return true; 803 804 // Otherwise, check the value is in a range that makes sense for this 805 // extension. 806 return isImmSExti16i8Value(CE->getValue()); 807 } 808 bool isImmSExti32i8() const { 809 if (!isImm()) 810 return false; 811 812 // If this isn't a constant expr, just assume it fits and let relaxation 813 // handle it. 814 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()); 815 if (!CE) 816 return true; 817 818 // Otherwise, check the value is in a range that makes sense for this 819 // extension. 820 return isImmSExti32i8Value(CE->getValue()); 821 } 822 bool isImmZExtu32u8() const { 823 if (!isImm()) 824 return false; 825 826 // If this isn't a constant expr, just assume it fits and let relaxation 827 // handle it. 828 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()); 829 if (!CE) 830 return true; 831 832 // Otherwise, check the value is in a range that makes sense for this 833 // extension. 834 return isImmZExtu32u8Value(CE->getValue()); 835 } 836 bool isImmSExti64i8() const { 837 if (!isImm()) 838 return false; 839 840 // If this isn't a constant expr, just assume it fits and let relaxation 841 // handle it. 842 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()); 843 if (!CE) 844 return true; 845 846 // Otherwise, check the value is in a range that makes sense for this 847 // extension. 848 return isImmSExti64i8Value(CE->getValue()); 849 } 850 bool isImmSExti64i32() const { 851 if (!isImm()) 852 return false; 853 854 // If this isn't a constant expr, just assume it fits and let relaxation 855 // handle it. 856 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()); 857 if (!CE) 858 return true; 859 860 // Otherwise, check the value is in a range that makes sense for this 861 // extension. 862 return isImmSExti64i32Value(CE->getValue()); 863 } 864 865 bool isOffsetOf() const { 866 return OffsetOfLoc.getPointer(); 867 } 868 869 bool needAddressOf() const { 870 return AddressOf; 871 } 872 873 bool isMem() const { return Kind == Memory; } 874 bool isMem8() const { 875 return Kind == Memory && (!Mem.Size || Mem.Size == 8); 876 } 877 bool isMem16() const { 878 return Kind == Memory && (!Mem.Size || Mem.Size == 16); 879 } 880 bool isMem32() const { 881 return Kind == Memory && (!Mem.Size || Mem.Size == 32); 882 } 883 bool isMem64() const { 884 return Kind == Memory && (!Mem.Size || Mem.Size == 64); 885 } 886 bool isMem80() const { 887 return Kind == Memory && (!Mem.Size || Mem.Size == 80); 888 } 889 bool isMem128() const { 890 return Kind == Memory && (!Mem.Size || Mem.Size == 128); 891 } 892 bool isMem256() const { 893 return Kind == Memory && (!Mem.Size || Mem.Size == 256); 894 } 895 bool isMem512() const { 896 return Kind == Memory && (!Mem.Size || Mem.Size == 512); 897 } 898 899 bool isMemVX32() const { 900 return Kind == Memory && (!Mem.Size || Mem.Size == 32) && 901 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15; 902 } 903 bool isMemVY32() const { 904 return Kind == Memory && (!Mem.Size || Mem.Size == 32) && 905 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15; 906 } 907 bool isMemVX64() const { 908 return Kind == Memory && (!Mem.Size || Mem.Size == 64) && 909 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15; 910 } 911 bool isMemVY64() const { 912 return Kind == Memory && (!Mem.Size || Mem.Size == 64) && 913 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15; 914 } 915 bool isMemVZ32() const { 916 return Kind == Memory && (!Mem.Size || Mem.Size == 32) && 917 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31; 918 } 919 bool isMemVZ64() const { 920 return Kind == Memory && (!Mem.Size || Mem.Size == 64) && 921 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31; 922 } 923 924 bool isAbsMem() const { 925 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() && 926 !getMemIndexReg() && getMemScale() == 1; 927 } 928 929 bool isSrcIdx() const { 930 return !getMemIndexReg() && getMemScale() == 1 && 931 (getMemBaseReg() == X86::RSI || getMemBaseReg() == X86::ESI || 932 getMemBaseReg() == X86::SI) && isa<MCConstantExpr>(getMemDisp()) && 933 cast<MCConstantExpr>(getMemDisp())->getValue() == 0; 934 } 935 bool isSrcIdx8() const { 936 return isMem8() && isSrcIdx(); 937 } 938 bool isSrcIdx16() const { 939 return isMem16() && isSrcIdx(); 940 } 941 bool isSrcIdx32() const { 942 return isMem32() && isSrcIdx(); 943 } 944 bool isSrcIdx64() const { 945 return isMem64() && isSrcIdx(); 946 } 947 948 bool isDstIdx() const { 949 return !getMemIndexReg() && getMemScale() == 1 && 950 (getMemSegReg() == 0 || getMemSegReg() == X86::ES) && 951 (getMemBaseReg() == X86::RDI || getMemBaseReg() == X86::EDI || 952 getMemBaseReg() == X86::DI) && isa<MCConstantExpr>(getMemDisp()) && 953 cast<MCConstantExpr>(getMemDisp())->getValue() == 0; 954 } 955 bool isDstIdx8() const { 956 return isMem8() && isDstIdx(); 957 } 958 bool isDstIdx16() const { 959 return isMem16() && isDstIdx(); 960 } 961 bool isDstIdx32() const { 962 return isMem32() && isDstIdx(); 963 } 964 bool isDstIdx64() const { 965 return isMem64() && isDstIdx(); 966 } 967 968 bool isMemOffs8() const { 969 return Kind == Memory && !getMemBaseReg() && 970 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 8); 971 } 972 bool isMemOffs16() const { 973 return Kind == Memory && !getMemBaseReg() && 974 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 16); 975 } 976 bool isMemOffs32() const { 977 return Kind == Memory && !getMemBaseReg() && 978 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 32); 979 } 980 bool isMemOffs64() const { 981 return Kind == Memory && !getMemBaseReg() && 982 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 64); 983 } 984 985 bool isReg() const { return Kind == Register; } 986 987 bool isGR32orGR64() const { 988 return Kind == Register && 989 (X86MCRegisterClasses[X86::GR32RegClassID].contains(getReg()) || 990 X86MCRegisterClasses[X86::GR64RegClassID].contains(getReg())); 991 } 992 993 void addExpr(MCInst &Inst, const MCExpr *Expr) const { 994 // Add as immediates when possible. 995 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr)) 996 Inst.addOperand(MCOperand::CreateImm(CE->getValue())); 997 else 998 Inst.addOperand(MCOperand::CreateExpr(Expr)); 999 } 1000 1001 void addRegOperands(MCInst &Inst, unsigned N) const { 1002 assert(N == 1 && "Invalid number of operands!"); 1003 Inst.addOperand(MCOperand::CreateReg(getReg())); 1004 } 1005 1006 static unsigned getGR32FromGR64(unsigned RegNo) { 1007 switch (RegNo) { 1008 default: llvm_unreachable("Unexpected register"); 1009 case X86::RAX: return X86::EAX; 1010 case X86::RCX: return X86::ECX; 1011 case X86::RDX: return X86::EDX; 1012 case X86::RBX: return X86::EBX; 1013 case X86::RBP: return X86::EBP; 1014 case X86::RSP: return X86::ESP; 1015 case X86::RSI: return X86::ESI; 1016 case X86::RDI: return X86::EDI; 1017 case X86::R8: return X86::R8D; 1018 case X86::R9: return X86::R9D; 1019 case X86::R10: return X86::R10D; 1020 case X86::R11: return X86::R11D; 1021 case X86::R12: return X86::R12D; 1022 case X86::R13: return X86::R13D; 1023 case X86::R14: return X86::R14D; 1024 case X86::R15: return X86::R15D; 1025 case X86::RIP: return X86::EIP; 1026 } 1027 } 1028 1029 void addGR32orGR64Operands(MCInst &Inst, unsigned N) const { 1030 assert(N == 1 && "Invalid number of operands!"); 1031 unsigned RegNo = getReg(); 1032 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo)) 1033 RegNo = getGR32FromGR64(RegNo); 1034 Inst.addOperand(MCOperand::CreateReg(RegNo)); 1035 } 1036 1037 void addImmOperands(MCInst &Inst, unsigned N) const { 1038 assert(N == 1 && "Invalid number of operands!"); 1039 addExpr(Inst, getImm()); 1040 } 1041 1042 void addMemOperands(MCInst &Inst, unsigned N) const { 1043 assert((N == 5) && "Invalid number of operands!"); 1044 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg())); 1045 Inst.addOperand(MCOperand::CreateImm(getMemScale())); 1046 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg())); 1047 addExpr(Inst, getMemDisp()); 1048 Inst.addOperand(MCOperand::CreateReg(getMemSegReg())); 1049 } 1050 1051 void addAbsMemOperands(MCInst &Inst, unsigned N) const { 1052 assert((N == 1) && "Invalid number of operands!"); 1053 // Add as immediates when possible. 1054 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp())) 1055 Inst.addOperand(MCOperand::CreateImm(CE->getValue())); 1056 else 1057 Inst.addOperand(MCOperand::CreateExpr(getMemDisp())); 1058 } 1059 1060 void addSrcIdxOperands(MCInst &Inst, unsigned N) const { 1061 assert((N == 2) && "Invalid number of operands!"); 1062 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg())); 1063 Inst.addOperand(MCOperand::CreateReg(getMemSegReg())); 1064 } 1065 void addDstIdxOperands(MCInst &Inst, unsigned N) const { 1066 assert((N == 1) && "Invalid number of operands!"); 1067 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg())); 1068 } 1069 1070 void addMemOffsOperands(MCInst &Inst, unsigned N) const { 1071 assert((N == 2) && "Invalid number of operands!"); 1072 // Add as immediates when possible. 1073 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp())) 1074 Inst.addOperand(MCOperand::CreateImm(CE->getValue())); 1075 else 1076 Inst.addOperand(MCOperand::CreateExpr(getMemDisp())); 1077 Inst.addOperand(MCOperand::CreateReg(getMemSegReg())); 1078 } 1079 1080 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) { 1081 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size()); 1082 X86Operand *Res = new X86Operand(Token, Loc, EndLoc); 1083 Res->Tok.Data = Str.data(); 1084 Res->Tok.Length = Str.size(); 1085 return Res; 1086 } 1087 1088 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc, 1089 bool AddressOf = false, 1090 SMLoc OffsetOfLoc = SMLoc(), 1091 StringRef SymName = StringRef(), 1092 void *OpDecl = 0) { 1093 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc); 1094 Res->Reg.RegNo = RegNo; 1095 Res->AddressOf = AddressOf; 1096 Res->OffsetOfLoc = OffsetOfLoc; 1097 Res->SymName = SymName; 1098 Res->OpDecl = OpDecl; 1099 return Res; 1100 } 1101 1102 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){ 1103 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc); 1104 Res->Imm.Val = Val; 1105 return Res; 1106 } 1107 1108 /// Create an absolute memory operand. 1109 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc, 1110 unsigned Size = 0, StringRef SymName = StringRef(), 1111 void *OpDecl = 0) { 1112 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc); 1113 Res->Mem.SegReg = 0; 1114 Res->Mem.Disp = Disp; 1115 Res->Mem.BaseReg = 0; 1116 Res->Mem.IndexReg = 0; 1117 Res->Mem.Scale = 1; 1118 Res->Mem.Size = Size; 1119 Res->SymName = SymName; 1120 Res->OpDecl = OpDecl; 1121 Res->AddressOf = false; 1122 return Res; 1123 } 1124 1125 /// Create a generalized memory operand. 1126 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp, 1127 unsigned BaseReg, unsigned IndexReg, 1128 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc, 1129 unsigned Size = 0, 1130 StringRef SymName = StringRef(), 1131 void *OpDecl = 0) { 1132 // We should never just have a displacement, that should be parsed as an 1133 // absolute memory operand. 1134 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!"); 1135 1136 // The scale should always be one of {1,2,4,8}. 1137 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) && 1138 "Invalid scale!"); 1139 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc); 1140 Res->Mem.SegReg = SegReg; 1141 Res->Mem.Disp = Disp; 1142 Res->Mem.BaseReg = BaseReg; 1143 Res->Mem.IndexReg = IndexReg; 1144 Res->Mem.Scale = Scale; 1145 Res->Mem.Size = Size; 1146 Res->SymName = SymName; 1147 Res->OpDecl = OpDecl; 1148 Res->AddressOf = false; 1149 return Res; 1150 } 1151 }; 1152 1153 } // end anonymous namespace. 1154 1155 static bool CheckBaseRegAndIndexReg(unsigned BaseReg, unsigned IndexReg, 1156 StringRef &ErrMsg) { 1157 // If we have both a base register and an index register make sure they are 1158 // both 64-bit or 32-bit registers. 1159 // To support VSIB, IndexReg can be 128-bit or 256-bit registers. 1160 if (BaseReg != 0 && IndexReg != 0) { 1161 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) && 1162 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) || 1163 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) && 1164 IndexReg != X86::RIZ) { 1165 ErrMsg = "base register is 64-bit, but index register is not"; 1166 return true; 1167 } 1168 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) && 1169 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) || 1170 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) && 1171 IndexReg != X86::EIZ){ 1172 ErrMsg = "base register is 32-bit, but index register is not"; 1173 return true; 1174 } 1175 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg)) { 1176 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) || 1177 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) { 1178 ErrMsg = "base register is 16-bit, but index register is not"; 1179 return true; 1180 } 1181 if (((BaseReg == X86::BX || BaseReg == X86::BP) && 1182 IndexReg != X86::SI && IndexReg != X86::DI) || 1183 ((BaseReg == X86::SI || BaseReg == X86::DI) && 1184 IndexReg != X86::BX && IndexReg != X86::BP)) { 1185 ErrMsg = "invalid 16-bit base/index register combination"; 1186 return true; 1187 } 1188 } 1189 } 1190 return false; 1191 } 1192 1193 bool X86AsmParser::doSrcDstMatch(X86Operand &Op1, X86Operand &Op2) 1194 { 1195 // Return true and let a normal complaint about bogus operands happen. 1196 if (!Op1.isMem() || !Op2.isMem()) 1197 return true; 1198 1199 // Actually these might be the other way round if Intel syntax is 1200 // being used. It doesn't matter. 1201 unsigned diReg = Op1.Mem.BaseReg; 1202 unsigned siReg = Op2.Mem.BaseReg; 1203 1204 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(siReg)) 1205 return X86MCRegisterClasses[X86::GR16RegClassID].contains(diReg); 1206 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(siReg)) 1207 return X86MCRegisterClasses[X86::GR32RegClassID].contains(diReg); 1208 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(siReg)) 1209 return X86MCRegisterClasses[X86::GR64RegClassID].contains(diReg); 1210 // Again, return true and let another error happen. 1211 return true; 1212 } 1213 1214 bool X86AsmParser::ParseRegister(unsigned &RegNo, 1215 SMLoc &StartLoc, SMLoc &EndLoc) { 1216 RegNo = 0; 1217 const AsmToken &PercentTok = Parser.getTok(); 1218 StartLoc = PercentTok.getLoc(); 1219 1220 // If we encounter a %, ignore it. This code handles registers with and 1221 // without the prefix, unprefixed registers can occur in cfi directives. 1222 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent)) 1223 Parser.Lex(); // Eat percent token. 1224 1225 const AsmToken &Tok = Parser.getTok(); 1226 EndLoc = Tok.getEndLoc(); 1227 1228 if (Tok.isNot(AsmToken::Identifier)) { 1229 if (isParsingIntelSyntax()) return true; 1230 return Error(StartLoc, "invalid register name", 1231 SMRange(StartLoc, EndLoc)); 1232 } 1233 1234 RegNo = MatchRegisterName(Tok.getString()); 1235 1236 // If the match failed, try the register name as lowercase. 1237 if (RegNo == 0) 1238 RegNo = MatchRegisterName(Tok.getString().lower()); 1239 1240 if (!is64BitMode()) { 1241 // FIXME: This should be done using Requires<Not64BitMode> and 1242 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also 1243 // checked. 1244 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a 1245 // REX prefix. 1246 if (RegNo == X86::RIZ || 1247 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) || 1248 X86II::isX86_64NonExtLowByteReg(RegNo) || 1249 X86II::isX86_64ExtendedReg(RegNo)) 1250 return Error(StartLoc, "register %" 1251 + Tok.getString() + " is only available in 64-bit mode", 1252 SMRange(StartLoc, EndLoc)); 1253 } 1254 1255 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens. 1256 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) { 1257 RegNo = X86::ST0; 1258 Parser.Lex(); // Eat 'st' 1259 1260 // Check to see if we have '(4)' after %st. 1261 if (getLexer().isNot(AsmToken::LParen)) 1262 return false; 1263 // Lex the paren. 1264 getParser().Lex(); 1265 1266 const AsmToken &IntTok = Parser.getTok(); 1267 if (IntTok.isNot(AsmToken::Integer)) 1268 return Error(IntTok.getLoc(), "expected stack index"); 1269 switch (IntTok.getIntVal()) { 1270 case 0: RegNo = X86::ST0; break; 1271 case 1: RegNo = X86::ST1; break; 1272 case 2: RegNo = X86::ST2; break; 1273 case 3: RegNo = X86::ST3; break; 1274 case 4: RegNo = X86::ST4; break; 1275 case 5: RegNo = X86::ST5; break; 1276 case 6: RegNo = X86::ST6; break; 1277 case 7: RegNo = X86::ST7; break; 1278 default: return Error(IntTok.getLoc(), "invalid stack index"); 1279 } 1280 1281 if (getParser().Lex().isNot(AsmToken::RParen)) 1282 return Error(Parser.getTok().getLoc(), "expected ')'"); 1283 1284 EndLoc = Parser.getTok().getEndLoc(); 1285 Parser.Lex(); // Eat ')' 1286 return false; 1287 } 1288 1289 EndLoc = Parser.getTok().getEndLoc(); 1290 1291 // If this is "db[0-7]", match it as an alias 1292 // for dr[0-7]. 1293 if (RegNo == 0 && Tok.getString().size() == 3 && 1294 Tok.getString().startswith("db")) { 1295 switch (Tok.getString()[2]) { 1296 case '0': RegNo = X86::DR0; break; 1297 case '1': RegNo = X86::DR1; break; 1298 case '2': RegNo = X86::DR2; break; 1299 case '3': RegNo = X86::DR3; break; 1300 case '4': RegNo = X86::DR4; break; 1301 case '5': RegNo = X86::DR5; break; 1302 case '6': RegNo = X86::DR6; break; 1303 case '7': RegNo = X86::DR7; break; 1304 } 1305 1306 if (RegNo != 0) { 1307 EndLoc = Parser.getTok().getEndLoc(); 1308 Parser.Lex(); // Eat it. 1309 return false; 1310 } 1311 } 1312 1313 if (RegNo == 0) { 1314 if (isParsingIntelSyntax()) return true; 1315 return Error(StartLoc, "invalid register name", 1316 SMRange(StartLoc, EndLoc)); 1317 } 1318 1319 Parser.Lex(); // Eat identifier token. 1320 return false; 1321 } 1322 1323 X86Operand *X86AsmParser::DefaultMemSIOperand(SMLoc Loc) { 1324 unsigned basereg = 1325 is64BitMode() ? X86::RSI : (is32BitMode() ? X86::ESI : X86::SI); 1326 const MCExpr *Disp = MCConstantExpr::Create(0, getContext()); 1327 return X86Operand::CreateMem(/*SegReg=*/0, Disp, /*BaseReg=*/basereg, 1328 /*IndexReg=*/0, /*Scale=*/1, Loc, Loc, 0); 1329 } 1330 1331 X86Operand *X86AsmParser::DefaultMemDIOperand(SMLoc Loc) { 1332 unsigned basereg = 1333 is64BitMode() ? X86::RDI : (is32BitMode() ? X86::EDI : X86::DI); 1334 const MCExpr *Disp = MCConstantExpr::Create(0, getContext()); 1335 return X86Operand::CreateMem(/*SegReg=*/0, Disp, /*BaseReg=*/basereg, 1336 /*IndexReg=*/0, /*Scale=*/1, Loc, Loc, 0); 1337 } 1338 1339 X86Operand *X86AsmParser::ParseOperand() { 1340 if (isParsingIntelSyntax()) 1341 return ParseIntelOperand(); 1342 return ParseATTOperand(); 1343 } 1344 1345 /// getIntelMemOperandSize - Return intel memory operand size. 1346 static unsigned getIntelMemOperandSize(StringRef OpStr) { 1347 unsigned Size = StringSwitch<unsigned>(OpStr) 1348 .Cases("BYTE", "byte", 8) 1349 .Cases("WORD", "word", 16) 1350 .Cases("DWORD", "dword", 32) 1351 .Cases("QWORD", "qword", 64) 1352 .Cases("XWORD", "xword", 80) 1353 .Cases("XMMWORD", "xmmword", 128) 1354 .Cases("YMMWORD", "ymmword", 256) 1355 .Cases("ZMMWORD", "zmmword", 512) 1356 .Cases("OPAQUE", "opaque", -1U) // needs to be non-zero, but doesn't matter 1357 .Default(0); 1358 return Size; 1359 } 1360 1361 X86Operand * 1362 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp, 1363 unsigned BaseReg, unsigned IndexReg, 1364 unsigned Scale, SMLoc Start, SMLoc End, 1365 unsigned Size, StringRef Identifier, 1366 InlineAsmIdentifierInfo &Info){ 1367 if (isa<MCSymbolRefExpr>(Disp)) { 1368 // If this is not a VarDecl then assume it is a FuncDecl or some other label 1369 // reference. We need an 'r' constraint here, so we need to create register 1370 // operand to ensure proper matching. Just pick a GPR based on the size of 1371 // a pointer. 1372 if (!Info.IsVarDecl) { 1373 unsigned RegNo = 1374 is64BitMode() ? X86::RBX : (is32BitMode() ? X86::EBX : X86::BX); 1375 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true, 1376 SMLoc(), Identifier, Info.OpDecl); 1377 } 1378 if (!Size) { 1379 Size = Info.Type * 8; // Size is in terms of bits in this context. 1380 if (Size) 1381 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start, 1382 /*Len=*/0, Size)); 1383 } 1384 } 1385 1386 // When parsing inline assembly we set the base register to a non-zero value 1387 // if we don't know the actual value at this time. This is necessary to 1388 // get the matching correct in some cases. 1389 BaseReg = BaseReg ? BaseReg : 1; 1390 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start, 1391 End, Size, Identifier, Info.OpDecl); 1392 } 1393 1394 static void 1395 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites, 1396 StringRef SymName, int64_t ImmDisp, 1397 int64_t FinalImmDisp, SMLoc &BracLoc, 1398 SMLoc &StartInBrac, SMLoc &End) { 1399 // Remove the '[' and ']' from the IR string. 1400 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1)); 1401 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1)); 1402 1403 // If ImmDisp is non-zero, then we parsed a displacement before the 1404 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp]) 1405 // If ImmDisp doesn't match the displacement computed by the state machine 1406 // then we have an additional displacement in the bracketed expression. 1407 if (ImmDisp != FinalImmDisp) { 1408 if (ImmDisp) { 1409 // We have an immediate displacement before the bracketed expression. 1410 // Adjust this to match the final immediate displacement. 1411 bool Found = false; 1412 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(), 1413 E = AsmRewrites->end(); I != E; ++I) { 1414 if ((*I).Loc.getPointer() > BracLoc.getPointer()) 1415 continue; 1416 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) { 1417 assert (!Found && "ImmDisp already rewritten."); 1418 (*I).Kind = AOK_Imm; 1419 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer(); 1420 (*I).Val = FinalImmDisp; 1421 Found = true; 1422 break; 1423 } 1424 } 1425 assert (Found && "Unable to rewrite ImmDisp."); 1426 (void)Found; 1427 } else { 1428 // We have a symbolic and an immediate displacement, but no displacement 1429 // before the bracketed expression. Put the immediate displacement 1430 // before the bracketed expression. 1431 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp)); 1432 } 1433 } 1434 // Remove all the ImmPrefix rewrites within the brackets. 1435 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(), 1436 E = AsmRewrites->end(); I != E; ++I) { 1437 if ((*I).Loc.getPointer() < StartInBrac.getPointer()) 1438 continue; 1439 if ((*I).Kind == AOK_ImmPrefix) 1440 (*I).Kind = AOK_Delete; 1441 } 1442 const char *SymLocPtr = SymName.data(); 1443 // Skip everything before the symbol. 1444 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) { 1445 assert(Len > 0 && "Expected a non-negative length."); 1446 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len)); 1447 } 1448 // Skip everything after the symbol. 1449 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) { 1450 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size()); 1451 assert(Len > 0 && "Expected a non-negative length."); 1452 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len)); 1453 } 1454 } 1455 1456 bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) { 1457 const AsmToken &Tok = Parser.getTok(); 1458 1459 bool Done = false; 1460 while (!Done) { 1461 bool UpdateLocLex = true; 1462 1463 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an 1464 // identifier. Don't try an parse it as a register. 1465 if (Tok.getString().startswith(".")) 1466 break; 1467 1468 // If we're parsing an immediate expression, we don't expect a '['. 1469 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac) 1470 break; 1471 1472 switch (getLexer().getKind()) { 1473 default: { 1474 if (SM.isValidEndState()) { 1475 Done = true; 1476 break; 1477 } 1478 return Error(Tok.getLoc(), "unknown token in expression"); 1479 } 1480 case AsmToken::EndOfStatement: { 1481 Done = true; 1482 break; 1483 } 1484 case AsmToken::Identifier: { 1485 // This could be a register or a symbolic displacement. 1486 unsigned TmpReg; 1487 const MCExpr *Val; 1488 SMLoc IdentLoc = Tok.getLoc(); 1489 StringRef Identifier = Tok.getString(); 1490 if(!ParseRegister(TmpReg, IdentLoc, End)) { 1491 SM.onRegister(TmpReg); 1492 UpdateLocLex = false; 1493 break; 1494 } else { 1495 if (!isParsingInlineAsm()) { 1496 if (getParser().parsePrimaryExpr(Val, End)) 1497 return Error(Tok.getLoc(), "Unexpected identifier!"); 1498 } else { 1499 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo(); 1500 if (ParseIntelIdentifier(Val, Identifier, Info, 1501 /*Unevaluated=*/false, End)) 1502 return true; 1503 } 1504 SM.onIdentifierExpr(Val, Identifier); 1505 UpdateLocLex = false; 1506 break; 1507 } 1508 return Error(Tok.getLoc(), "Unexpected identifier!"); 1509 } 1510 case AsmToken::Integer: { 1511 StringRef ErrMsg; 1512 if (isParsingInlineAsm() && SM.getAddImmPrefix()) 1513 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, 1514 Tok.getLoc())); 1515 // Look for 'b' or 'f' following an Integer as a directional label 1516 SMLoc Loc = getTok().getLoc(); 1517 int64_t IntVal = getTok().getIntVal(); 1518 End = consumeToken(); 1519 UpdateLocLex = false; 1520 if (getLexer().getKind() == AsmToken::Identifier) { 1521 StringRef IDVal = getTok().getString(); 1522 if (IDVal == "f" || IDVal == "b") { 1523 MCSymbol *Sym = 1524 getContext().GetDirectionalLocalSymbol(IntVal, 1525 IDVal == "f" ? 1 : 0); 1526 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1527 const MCExpr *Val = 1528 MCSymbolRefExpr::Create(Sym, Variant, getContext()); 1529 if (IDVal == "b" && Sym->isUndefined()) 1530 return Error(Loc, "invalid reference to undefined symbol"); 1531 StringRef Identifier = Sym->getName(); 1532 SM.onIdentifierExpr(Val, Identifier); 1533 End = consumeToken(); 1534 } else { 1535 if (SM.onInteger(IntVal, ErrMsg)) 1536 return Error(Loc, ErrMsg); 1537 } 1538 } else { 1539 if (SM.onInteger(IntVal, ErrMsg)) 1540 return Error(Loc, ErrMsg); 1541 } 1542 break; 1543 } 1544 case AsmToken::Plus: SM.onPlus(); break; 1545 case AsmToken::Minus: SM.onMinus(); break; 1546 case AsmToken::Star: SM.onStar(); break; 1547 case AsmToken::Slash: SM.onDivide(); break; 1548 case AsmToken::Pipe: SM.onOr(); break; 1549 case AsmToken::Amp: SM.onAnd(); break; 1550 case AsmToken::LBrac: SM.onLBrac(); break; 1551 case AsmToken::RBrac: SM.onRBrac(); break; 1552 case AsmToken::LParen: SM.onLParen(); break; 1553 case AsmToken::RParen: SM.onRParen(); break; 1554 } 1555 if (SM.hadError()) 1556 return Error(Tok.getLoc(), "unknown token in expression"); 1557 1558 if (!Done && UpdateLocLex) 1559 End = consumeToken(); 1560 } 1561 return false; 1562 } 1563 1564 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start, 1565 int64_t ImmDisp, 1566 unsigned Size) { 1567 const AsmToken &Tok = Parser.getTok(); 1568 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc(); 1569 if (getLexer().isNot(AsmToken::LBrac)) 1570 return ErrorOperand(BracLoc, "Expected '[' token!"); 1571 Parser.Lex(); // Eat '[' 1572 1573 SMLoc StartInBrac = Tok.getLoc(); 1574 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We 1575 // may have already parsed an immediate displacement before the bracketed 1576 // expression. 1577 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true); 1578 if (ParseIntelExpression(SM, End)) 1579 return 0; 1580 1581 const MCExpr *Disp; 1582 if (const MCExpr *Sym = SM.getSym()) { 1583 // A symbolic displacement. 1584 Disp = Sym; 1585 if (isParsingInlineAsm()) 1586 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(), 1587 ImmDisp, SM.getImm(), BracLoc, StartInBrac, 1588 End); 1589 } else { 1590 // An immediate displacement only. 1591 Disp = MCConstantExpr::Create(SM.getImm(), getContext()); 1592 } 1593 1594 // Parse the dot operator (e.g., [ebx].foo.bar). 1595 if (Tok.getString().startswith(".")) { 1596 const MCExpr *NewDisp; 1597 if (ParseIntelDotOperator(Disp, NewDisp)) 1598 return 0; 1599 1600 End = Tok.getEndLoc(); 1601 Parser.Lex(); // Eat the field. 1602 Disp = NewDisp; 1603 } 1604 1605 int BaseReg = SM.getBaseReg(); 1606 int IndexReg = SM.getIndexReg(); 1607 int Scale = SM.getScale(); 1608 if (!isParsingInlineAsm()) { 1609 // handle [-42] 1610 if (!BaseReg && !IndexReg) { 1611 if (!SegReg) 1612 return X86Operand::CreateMem(Disp, Start, End, Size); 1613 else 1614 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size); 1615 } 1616 StringRef ErrMsg; 1617 if (CheckBaseRegAndIndexReg(BaseReg, IndexReg, ErrMsg)) { 1618 Error(StartInBrac, ErrMsg); 1619 return 0; 1620 } 1621 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start, 1622 End, Size); 1623 } 1624 1625 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo(); 1626 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start, 1627 End, Size, SM.getSymName(), Info); 1628 } 1629 1630 // Inline assembly may use variable names with namespace alias qualifiers. 1631 bool X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val, 1632 StringRef &Identifier, 1633 InlineAsmIdentifierInfo &Info, 1634 bool IsUnevaluatedOperand, SMLoc &End) { 1635 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly."); 1636 Val = 0; 1637 1638 StringRef LineBuf(Identifier.data()); 1639 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand); 1640 1641 const AsmToken &Tok = Parser.getTok(); 1642 1643 // Advance the token stream until the end of the current token is 1644 // after the end of what the frontend claimed. 1645 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size(); 1646 while (true) { 1647 End = Tok.getEndLoc(); 1648 getLexer().Lex(); 1649 1650 assert(End.getPointer() <= EndPtr && "frontend claimed part of a token?"); 1651 if (End.getPointer() == EndPtr) break; 1652 } 1653 1654 // Create the symbol reference. 1655 Identifier = LineBuf; 1656 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier); 1657 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1658 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext()); 1659 return false; 1660 } 1661 1662 /// \brief Parse intel style segment override. 1663 X86Operand *X86AsmParser::ParseIntelSegmentOverride(unsigned SegReg, 1664 SMLoc Start, 1665 unsigned Size) { 1666 assert(SegReg != 0 && "Tried to parse a segment override without a segment!"); 1667 const AsmToken &Tok = Parser.getTok(); // Eat colon. 1668 if (Tok.isNot(AsmToken::Colon)) 1669 return ErrorOperand(Tok.getLoc(), "Expected ':' token!"); 1670 Parser.Lex(); // Eat ':' 1671 1672 int64_t ImmDisp = 0; 1673 if (getLexer().is(AsmToken::Integer)) { 1674 ImmDisp = Tok.getIntVal(); 1675 AsmToken ImmDispToken = Parser.Lex(); // Eat the integer. 1676 1677 if (isParsingInlineAsm()) 1678 InstInfo->AsmRewrites->push_back( 1679 AsmRewrite(AOK_ImmPrefix, ImmDispToken.getLoc())); 1680 1681 if (getLexer().isNot(AsmToken::LBrac)) { 1682 // An immediate following a 'segment register', 'colon' token sequence can 1683 // be followed by a bracketed expression. If it isn't we know we have our 1684 // final segment override. 1685 const MCExpr *Disp = MCConstantExpr::Create(ImmDisp, getContext()); 1686 return X86Operand::CreateMem(SegReg, Disp, /*BaseReg=*/0, /*IndexReg=*/0, 1687 /*Scale=*/1, Start, ImmDispToken.getEndLoc(), 1688 Size); 1689 } 1690 } 1691 1692 if (getLexer().is(AsmToken::LBrac)) 1693 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size); 1694 1695 const MCExpr *Val; 1696 SMLoc End; 1697 if (!isParsingInlineAsm()) { 1698 if (getParser().parsePrimaryExpr(Val, End)) 1699 return ErrorOperand(Tok.getLoc(), "unknown token in expression"); 1700 1701 return X86Operand::CreateMem(Val, Start, End, Size); 1702 } 1703 1704 InlineAsmIdentifierInfo Info; 1705 StringRef Identifier = Tok.getString(); 1706 if (ParseIntelIdentifier(Val, Identifier, Info, 1707 /*Unevaluated=*/false, End)) 1708 return 0; 1709 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0, 1710 /*Scale=*/1, Start, End, Size, Identifier, Info); 1711 } 1712 1713 /// ParseIntelMemOperand - Parse intel style memory operand. 1714 X86Operand *X86AsmParser::ParseIntelMemOperand(int64_t ImmDisp, SMLoc Start, 1715 unsigned Size) { 1716 const AsmToken &Tok = Parser.getTok(); 1717 SMLoc End; 1718 1719 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ]. 1720 if (getLexer().is(AsmToken::LBrac)) 1721 return ParseIntelBracExpression(/*SegReg=*/0, Start, ImmDisp, Size); 1722 1723 const MCExpr *Val; 1724 if (!isParsingInlineAsm()) { 1725 if (getParser().parsePrimaryExpr(Val, End)) 1726 return ErrorOperand(Tok.getLoc(), "unknown token in expression"); 1727 1728 return X86Operand::CreateMem(Val, Start, End, Size); 1729 } 1730 1731 InlineAsmIdentifierInfo Info; 1732 StringRef Identifier = Tok.getString(); 1733 if (ParseIntelIdentifier(Val, Identifier, Info, 1734 /*Unevaluated=*/false, End)) 1735 return 0; 1736 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0, /*IndexReg=*/0, 1737 /*Scale=*/1, Start, End, Size, Identifier, Info); 1738 } 1739 1740 /// Parse the '.' operator. 1741 bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp, 1742 const MCExpr *&NewDisp) { 1743 const AsmToken &Tok = Parser.getTok(); 1744 int64_t OrigDispVal, DotDispVal; 1745 1746 // FIXME: Handle non-constant expressions. 1747 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp)) 1748 OrigDispVal = OrigDisp->getValue(); 1749 else 1750 return Error(Tok.getLoc(), "Non-constant offsets are not supported!"); 1751 1752 // Drop the '.'. 1753 StringRef DotDispStr = Tok.getString().drop_front(1); 1754 1755 // .Imm gets lexed as a real. 1756 if (Tok.is(AsmToken::Real)) { 1757 APInt DotDisp; 1758 DotDispStr.getAsInteger(10, DotDisp); 1759 DotDispVal = DotDisp.getZExtValue(); 1760 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) { 1761 unsigned DotDisp; 1762 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.'); 1763 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second, 1764 DotDisp)) 1765 return Error(Tok.getLoc(), "Unable to lookup field reference!"); 1766 DotDispVal = DotDisp; 1767 } else 1768 return Error(Tok.getLoc(), "Unexpected token type!"); 1769 1770 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) { 1771 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data()); 1772 unsigned Len = DotDispStr.size(); 1773 unsigned Val = OrigDispVal + DotDispVal; 1774 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len, 1775 Val)); 1776 } 1777 1778 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext()); 1779 return false; 1780 } 1781 1782 /// Parse the 'offset' operator. This operator is used to specify the 1783 /// location rather then the content of a variable. 1784 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() { 1785 const AsmToken &Tok = Parser.getTok(); 1786 SMLoc OffsetOfLoc = Tok.getLoc(); 1787 Parser.Lex(); // Eat offset. 1788 1789 const MCExpr *Val; 1790 InlineAsmIdentifierInfo Info; 1791 SMLoc Start = Tok.getLoc(), End; 1792 StringRef Identifier = Tok.getString(); 1793 if (ParseIntelIdentifier(Val, Identifier, Info, 1794 /*Unevaluated=*/false, End)) 1795 return 0; 1796 1797 // Don't emit the offset operator. 1798 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7)); 1799 1800 // The offset operator will have an 'r' constraint, thus we need to create 1801 // register operand to ensure proper matching. Just pick a GPR based on 1802 // the size of a pointer. 1803 unsigned RegNo = 1804 is64BitMode() ? X86::RBX : (is32BitMode() ? X86::EBX : X86::BX); 1805 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true, 1806 OffsetOfLoc, Identifier, Info.OpDecl); 1807 } 1808 1809 enum IntelOperatorKind { 1810 IOK_LENGTH, 1811 IOK_SIZE, 1812 IOK_TYPE 1813 }; 1814 1815 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator 1816 /// returns the number of elements in an array. It returns the value 1 for 1817 /// non-array variables. The SIZE operator returns the size of a C or C++ 1818 /// variable. A variable's size is the product of its LENGTH and TYPE. The 1819 /// TYPE operator returns the size of a C or C++ type or variable. If the 1820 /// variable is an array, TYPE returns the size of a single element. 1821 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) { 1822 const AsmToken &Tok = Parser.getTok(); 1823 SMLoc TypeLoc = Tok.getLoc(); 1824 Parser.Lex(); // Eat operator. 1825 1826 const MCExpr *Val = 0; 1827 InlineAsmIdentifierInfo Info; 1828 SMLoc Start = Tok.getLoc(), End; 1829 StringRef Identifier = Tok.getString(); 1830 if (ParseIntelIdentifier(Val, Identifier, Info, 1831 /*Unevaluated=*/true, End)) 1832 return 0; 1833 1834 if (!Info.OpDecl) 1835 return ErrorOperand(Start, "unable to lookup expression"); 1836 1837 unsigned CVal = 0; 1838 switch(OpKind) { 1839 default: llvm_unreachable("Unexpected operand kind!"); 1840 case IOK_LENGTH: CVal = Info.Length; break; 1841 case IOK_SIZE: CVal = Info.Size; break; 1842 case IOK_TYPE: CVal = Info.Type; break; 1843 } 1844 1845 // Rewrite the type operator and the C or C++ type or variable in terms of an 1846 // immediate. E.g. TYPE foo -> $$4 1847 unsigned Len = End.getPointer() - TypeLoc.getPointer(); 1848 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal)); 1849 1850 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext()); 1851 return X86Operand::CreateImm(Imm, Start, End); 1852 } 1853 1854 X86Operand *X86AsmParser::ParseIntelOperand() { 1855 const AsmToken &Tok = Parser.getTok(); 1856 SMLoc Start, End; 1857 1858 // Offset, length, type and size operators. 1859 if (isParsingInlineAsm()) { 1860 StringRef AsmTokStr = Tok.getString(); 1861 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET") 1862 return ParseIntelOffsetOfOperator(); 1863 if (AsmTokStr == "length" || AsmTokStr == "LENGTH") 1864 return ParseIntelOperator(IOK_LENGTH); 1865 if (AsmTokStr == "size" || AsmTokStr == "SIZE") 1866 return ParseIntelOperator(IOK_SIZE); 1867 if (AsmTokStr == "type" || AsmTokStr == "TYPE") 1868 return ParseIntelOperator(IOK_TYPE); 1869 } 1870 1871 unsigned Size = getIntelMemOperandSize(Tok.getString()); 1872 if (Size) { 1873 Parser.Lex(); // Eat operand size (e.g., byte, word). 1874 if (Tok.getString() != "PTR" && Tok.getString() != "ptr") 1875 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!"); 1876 Parser.Lex(); // Eat ptr. 1877 } 1878 Start = Tok.getLoc(); 1879 1880 // Immediate. 1881 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) || 1882 getLexer().is(AsmToken::LParen)) { 1883 AsmToken StartTok = Tok; 1884 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true, 1885 /*AddImmPrefix=*/false); 1886 if (ParseIntelExpression(SM, End)) 1887 return 0; 1888 1889 int64_t Imm = SM.getImm(); 1890 if (isParsingInlineAsm()) { 1891 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer(); 1892 if (StartTok.getString().size() == Len) 1893 // Just add a prefix if this wasn't a complex immediate expression. 1894 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start)); 1895 else 1896 // Otherwise, rewrite the complex expression as a single immediate. 1897 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm)); 1898 } 1899 1900 if (getLexer().isNot(AsmToken::LBrac)) { 1901 // If a directional label (ie. 1f or 2b) was parsed above from 1902 // ParseIntelExpression() then SM.getSym() was set to a pointer to 1903 // to the MCExpr with the directional local symbol and this is a 1904 // memory operand not an immediate operand. 1905 if (SM.getSym()) 1906 return X86Operand::CreateMem(SM.getSym(), Start, End, Size); 1907 1908 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext()); 1909 return X86Operand::CreateImm(ImmExpr, Start, End); 1910 } 1911 1912 // Only positive immediates are valid. 1913 if (Imm < 0) 1914 return ErrorOperand(Start, "expected a positive immediate displacement " 1915 "before bracketed expr."); 1916 1917 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ]. 1918 return ParseIntelMemOperand(Imm, Start, Size); 1919 } 1920 1921 // Register. 1922 unsigned RegNo = 0; 1923 if (!ParseRegister(RegNo, Start, End)) { 1924 // If this is a segment register followed by a ':', then this is the start 1925 // of a segment override, otherwise this is a normal register reference. 1926 if (getLexer().isNot(AsmToken::Colon)) 1927 return X86Operand::CreateReg(RegNo, Start, End); 1928 1929 return ParseIntelSegmentOverride(/*SegReg=*/RegNo, Start, Size); 1930 } 1931 1932 // Memory operand. 1933 return ParseIntelMemOperand(/*Disp=*/0, Start, Size); 1934 } 1935 1936 X86Operand *X86AsmParser::ParseATTOperand() { 1937 switch (getLexer().getKind()) { 1938 default: 1939 // Parse a memory operand with no segment register. 1940 return ParseMemOperand(0, Parser.getTok().getLoc()); 1941 case AsmToken::Percent: { 1942 // Read the register. 1943 unsigned RegNo; 1944 SMLoc Start, End; 1945 if (ParseRegister(RegNo, Start, End)) return 0; 1946 if (RegNo == X86::EIZ || RegNo == X86::RIZ) { 1947 Error(Start, "%eiz and %riz can only be used as index registers", 1948 SMRange(Start, End)); 1949 return 0; 1950 } 1951 1952 // If this is a segment register followed by a ':', then this is the start 1953 // of a memory reference, otherwise this is a normal register reference. 1954 if (getLexer().isNot(AsmToken::Colon)) 1955 return X86Operand::CreateReg(RegNo, Start, End); 1956 1957 getParser().Lex(); // Eat the colon. 1958 return ParseMemOperand(RegNo, Start); 1959 } 1960 case AsmToken::Dollar: { 1961 // $42 -> immediate. 1962 SMLoc Start = Parser.getTok().getLoc(), End; 1963 Parser.Lex(); 1964 const MCExpr *Val; 1965 if (getParser().parseExpression(Val, End)) 1966 return 0; 1967 return X86Operand::CreateImm(Val, Start, End); 1968 } 1969 } 1970 } 1971 1972 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix 1973 /// has already been parsed if present. 1974 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) { 1975 1976 // We have to disambiguate a parenthesized expression "(4+5)" from the start 1977 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The 1978 // only way to do this without lookahead is to eat the '(' and see what is 1979 // after it. 1980 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext()); 1981 if (getLexer().isNot(AsmToken::LParen)) { 1982 SMLoc ExprEnd; 1983 if (getParser().parseExpression(Disp, ExprEnd)) return 0; 1984 1985 // After parsing the base expression we could either have a parenthesized 1986 // memory address or not. If not, return now. If so, eat the (. 1987 if (getLexer().isNot(AsmToken::LParen)) { 1988 // Unless we have a segment register, treat this as an immediate. 1989 if (SegReg == 0) 1990 return X86Operand::CreateMem(Disp, MemStart, ExprEnd); 1991 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd); 1992 } 1993 1994 // Eat the '('. 1995 Parser.Lex(); 1996 } else { 1997 // Okay, we have a '('. We don't know if this is an expression or not, but 1998 // so we have to eat the ( to see beyond it. 1999 SMLoc LParenLoc = Parser.getTok().getLoc(); 2000 Parser.Lex(); // Eat the '('. 2001 2002 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) { 2003 // Nothing to do here, fall into the code below with the '(' part of the 2004 // memory operand consumed. 2005 } else { 2006 SMLoc ExprEnd; 2007 2008 // It must be an parenthesized expression, parse it now. 2009 if (getParser().parseParenExpression(Disp, ExprEnd)) 2010 return 0; 2011 2012 // After parsing the base expression we could either have a parenthesized 2013 // memory address or not. If not, return now. If so, eat the (. 2014 if (getLexer().isNot(AsmToken::LParen)) { 2015 // Unless we have a segment register, treat this as an immediate. 2016 if (SegReg == 0) 2017 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd); 2018 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd); 2019 } 2020 2021 // Eat the '('. 2022 Parser.Lex(); 2023 } 2024 } 2025 2026 // If we reached here, then we just ate the ( of the memory operand. Process 2027 // the rest of the memory operand. 2028 unsigned BaseReg = 0, IndexReg = 0, Scale = 1; 2029 SMLoc IndexLoc, BaseLoc; 2030 2031 if (getLexer().is(AsmToken::Percent)) { 2032 SMLoc StartLoc, EndLoc; 2033 BaseLoc = Parser.getTok().getLoc(); 2034 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0; 2035 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) { 2036 Error(StartLoc, "eiz and riz can only be used as index registers", 2037 SMRange(StartLoc, EndLoc)); 2038 return 0; 2039 } 2040 } 2041 2042 if (getLexer().is(AsmToken::Comma)) { 2043 Parser.Lex(); // Eat the comma. 2044 IndexLoc = Parser.getTok().getLoc(); 2045 2046 // Following the comma we should have either an index register, or a scale 2047 // value. We don't support the later form, but we want to parse it 2048 // correctly. 2049 // 2050 // Not that even though it would be completely consistent to support syntax 2051 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this. 2052 if (getLexer().is(AsmToken::Percent)) { 2053 SMLoc L; 2054 if (ParseRegister(IndexReg, L, L)) return 0; 2055 2056 if (getLexer().isNot(AsmToken::RParen)) { 2057 // Parse the scale amount: 2058 // ::= ',' [scale-expression] 2059 if (getLexer().isNot(AsmToken::Comma)) { 2060 Error(Parser.getTok().getLoc(), 2061 "expected comma in scale expression"); 2062 return 0; 2063 } 2064 Parser.Lex(); // Eat the comma. 2065 2066 if (getLexer().isNot(AsmToken::RParen)) { 2067 SMLoc Loc = Parser.getTok().getLoc(); 2068 2069 int64_t ScaleVal; 2070 if (getParser().parseAbsoluteExpression(ScaleVal)){ 2071 Error(Loc, "expected scale expression"); 2072 return 0; 2073 } 2074 2075 // Validate the scale amount. 2076 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) && 2077 ScaleVal != 1) { 2078 Error(Loc, "scale factor in 16-bit address must be 1"); 2079 return 0; 2080 } 2081 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){ 2082 Error(Loc, "scale factor in address must be 1, 2, 4 or 8"); 2083 return 0; 2084 } 2085 Scale = (unsigned)ScaleVal; 2086 } 2087 } 2088 } else if (getLexer().isNot(AsmToken::RParen)) { 2089 // A scale amount without an index is ignored. 2090 // index. 2091 SMLoc Loc = Parser.getTok().getLoc(); 2092 2093 int64_t Value; 2094 if (getParser().parseAbsoluteExpression(Value)) 2095 return 0; 2096 2097 if (Value != 1) 2098 Warning(Loc, "scale factor without index register is ignored"); 2099 Scale = 1; 2100 } 2101 } 2102 2103 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too. 2104 if (getLexer().isNot(AsmToken::RParen)) { 2105 Error(Parser.getTok().getLoc(), "unexpected token in memory operand"); 2106 return 0; 2107 } 2108 SMLoc MemEnd = Parser.getTok().getEndLoc(); 2109 Parser.Lex(); // Eat the ')'. 2110 2111 // Check for use of invalid 16-bit registers. Only BX/BP/SI/DI are allowed, 2112 // and then only in non-64-bit modes. Except for DX, which is a special case 2113 // because an unofficial form of in/out instructions uses it. 2114 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) && 2115 (is64BitMode() || (BaseReg != X86::BX && BaseReg != X86::BP && 2116 BaseReg != X86::SI && BaseReg != X86::DI)) && 2117 BaseReg != X86::DX) { 2118 Error(BaseLoc, "invalid 16-bit base register"); 2119 return 0; 2120 } 2121 if (BaseReg == 0 && 2122 X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)) { 2123 Error(IndexLoc, "16-bit memory operand may not include only index register"); 2124 return 0; 2125 } 2126 2127 StringRef ErrMsg; 2128 if (CheckBaseRegAndIndexReg(BaseReg, IndexReg, ErrMsg)) { 2129 Error(BaseLoc, ErrMsg); 2130 return 0; 2131 } 2132 2133 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, 2134 MemStart, MemEnd); 2135 } 2136 2137 bool X86AsmParser:: 2138 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc, 2139 SmallVectorImpl<MCParsedAsmOperand*> &Operands) { 2140 InstInfo = &Info; 2141 StringRef PatchedName = Name; 2142 2143 // FIXME: Hack to recognize setneb as setne. 2144 if (PatchedName.startswith("set") && PatchedName.endswith("b") && 2145 PatchedName != "setb" && PatchedName != "setnb") 2146 PatchedName = PatchedName.substr(0, Name.size()-1); 2147 2148 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}. 2149 const MCExpr *ExtraImmOp = 0; 2150 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) && 2151 (PatchedName.endswith("ss") || PatchedName.endswith("sd") || 2152 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) { 2153 bool IsVCMP = PatchedName[0] == 'v'; 2154 unsigned SSECCIdx = IsVCMP ? 4 : 3; 2155 unsigned SSEComparisonCode = StringSwitch<unsigned>( 2156 PatchedName.slice(SSECCIdx, PatchedName.size() - 2)) 2157 .Case("eq", 0x00) 2158 .Case("lt", 0x01) 2159 .Case("le", 0x02) 2160 .Case("unord", 0x03) 2161 .Case("neq", 0x04) 2162 .Case("nlt", 0x05) 2163 .Case("nle", 0x06) 2164 .Case("ord", 0x07) 2165 /* AVX only from here */ 2166 .Case("eq_uq", 0x08) 2167 .Case("nge", 0x09) 2168 .Case("ngt", 0x0A) 2169 .Case("false", 0x0B) 2170 .Case("neq_oq", 0x0C) 2171 .Case("ge", 0x0D) 2172 .Case("gt", 0x0E) 2173 .Case("true", 0x0F) 2174 .Case("eq_os", 0x10) 2175 .Case("lt_oq", 0x11) 2176 .Case("le_oq", 0x12) 2177 .Case("unord_s", 0x13) 2178 .Case("neq_us", 0x14) 2179 .Case("nlt_uq", 0x15) 2180 .Case("nle_uq", 0x16) 2181 .Case("ord_s", 0x17) 2182 .Case("eq_us", 0x18) 2183 .Case("nge_uq", 0x19) 2184 .Case("ngt_uq", 0x1A) 2185 .Case("false_os", 0x1B) 2186 .Case("neq_os", 0x1C) 2187 .Case("ge_oq", 0x1D) 2188 .Case("gt_oq", 0x1E) 2189 .Case("true_us", 0x1F) 2190 .Default(~0U); 2191 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) { 2192 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode, 2193 getParser().getContext()); 2194 if (PatchedName.endswith("ss")) { 2195 PatchedName = IsVCMP ? "vcmpss" : "cmpss"; 2196 } else if (PatchedName.endswith("sd")) { 2197 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd"; 2198 } else if (PatchedName.endswith("ps")) { 2199 PatchedName = IsVCMP ? "vcmpps" : "cmpps"; 2200 } else { 2201 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!"); 2202 PatchedName = IsVCMP ? "vcmppd" : "cmppd"; 2203 } 2204 } 2205 } 2206 2207 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc)); 2208 2209 if (ExtraImmOp && !isParsingIntelSyntax()) 2210 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc)); 2211 2212 // Determine whether this is an instruction prefix. 2213 bool isPrefix = 2214 Name == "lock" || Name == "rep" || 2215 Name == "repe" || Name == "repz" || 2216 Name == "repne" || Name == "repnz" || 2217 Name == "rex64" || Name == "data16"; 2218 2219 2220 // This does the actual operand parsing. Don't parse any more if we have a 2221 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we 2222 // just want to parse the "lock" as the first instruction and the "incl" as 2223 // the next one. 2224 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) { 2225 2226 // Parse '*' modifier. 2227 if (getLexer().is(AsmToken::Star)) 2228 Operands.push_back(X86Operand::CreateToken("*", consumeToken())); 2229 2230 // Read the first operand. 2231 if (X86Operand *Op = ParseOperand()) 2232 Operands.push_back(Op); 2233 else { 2234 Parser.eatToEndOfStatement(); 2235 return true; 2236 } 2237 2238 while (getLexer().is(AsmToken::Comma)) { 2239 Parser.Lex(); // Eat the comma. 2240 2241 // Parse and remember the operand. 2242 if (X86Operand *Op = ParseOperand()) 2243 Operands.push_back(Op); 2244 else { 2245 Parser.eatToEndOfStatement(); 2246 return true; 2247 } 2248 } 2249 2250 if (STI.getFeatureBits() & X86::FeatureAVX512) { 2251 // Parse mask register {%k1} 2252 if (getLexer().is(AsmToken::LCurly)) { 2253 Operands.push_back(X86Operand::CreateToken("{", consumeToken())); 2254 if (X86Operand *Op = ParseOperand()) { 2255 Operands.push_back(Op); 2256 if (!getLexer().is(AsmToken::RCurly)) { 2257 SMLoc Loc = getLexer().getLoc(); 2258 Parser.eatToEndOfStatement(); 2259 return Error(Loc, "Expected } at this point"); 2260 } 2261 Operands.push_back(X86Operand::CreateToken("}", consumeToken())); 2262 } else { 2263 Parser.eatToEndOfStatement(); 2264 return true; 2265 } 2266 } 2267 // TODO: add parsing of broadcasts {1to8}, {1to16} 2268 // Parse "zeroing non-masked" semantic {z} 2269 if (getLexer().is(AsmToken::LCurly)) { 2270 Operands.push_back(X86Operand::CreateToken("{z}", consumeToken())); 2271 if (!getLexer().is(AsmToken::Identifier) || getLexer().getTok().getIdentifier() != "z") { 2272 SMLoc Loc = getLexer().getLoc(); 2273 Parser.eatToEndOfStatement(); 2274 return Error(Loc, "Expected z at this point"); 2275 } 2276 Parser.Lex(); // Eat the z 2277 if (!getLexer().is(AsmToken::RCurly)) { 2278 SMLoc Loc = getLexer().getLoc(); 2279 Parser.eatToEndOfStatement(); 2280 return Error(Loc, "Expected } at this point"); 2281 } 2282 Parser.Lex(); // Eat the } 2283 } 2284 } 2285 2286 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2287 SMLoc Loc = getLexer().getLoc(); 2288 Parser.eatToEndOfStatement(); 2289 return Error(Loc, "unexpected token in argument list"); 2290 } 2291 } 2292 2293 if (getLexer().is(AsmToken::EndOfStatement)) 2294 Parser.Lex(); // Consume the EndOfStatement 2295 else if (isPrefix && getLexer().is(AsmToken::Slash)) 2296 Parser.Lex(); // Consume the prefix separator Slash 2297 2298 if (ExtraImmOp && isParsingIntelSyntax()) 2299 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc)); 2300 2301 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" -> 2302 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely 2303 // documented form in various unofficial manuals, so a lot of code uses it. 2304 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") && 2305 Operands.size() == 3) { 2306 X86Operand &Op = *(X86Operand*)Operands.back(); 2307 if (Op.isMem() && Op.Mem.SegReg == 0 && 2308 isa<MCConstantExpr>(Op.Mem.Disp) && 2309 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 && 2310 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) { 2311 SMLoc Loc = Op.getEndLoc(); 2312 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc); 2313 delete &Op; 2314 } 2315 } 2316 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al". 2317 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") && 2318 Operands.size() == 3) { 2319 X86Operand &Op = *(X86Operand*)Operands.begin()[1]; 2320 if (Op.isMem() && Op.Mem.SegReg == 0 && 2321 isa<MCConstantExpr>(Op.Mem.Disp) && 2322 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 && 2323 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) { 2324 SMLoc Loc = Op.getEndLoc(); 2325 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc); 2326 delete &Op; 2327 } 2328 } 2329 2330 // Append default arguments to "ins[bwld]" 2331 if (Name.startswith("ins") && Operands.size() == 1 && 2332 (Name == "insb" || Name == "insw" || Name == "insl" || 2333 Name == "insd" )) { 2334 if (isParsingIntelSyntax()) { 2335 Operands.push_back(X86Operand::CreateReg(X86::DX, NameLoc, NameLoc)); 2336 Operands.push_back(DefaultMemDIOperand(NameLoc)); 2337 } else { 2338 Operands.push_back(X86Operand::CreateReg(X86::DX, NameLoc, NameLoc)); 2339 Operands.push_back(DefaultMemDIOperand(NameLoc)); 2340 } 2341 } 2342 2343 // Append default arguments to "outs[bwld]" 2344 if (Name.startswith("outs") && Operands.size() == 1 && 2345 (Name == "outsb" || Name == "outsw" || Name == "outsl" || 2346 Name == "outsd" )) { 2347 if (isParsingIntelSyntax()) { 2348 Operands.push_back(DefaultMemSIOperand(NameLoc)); 2349 Operands.push_back(X86Operand::CreateReg(X86::DX, NameLoc, NameLoc)); 2350 } else { 2351 Operands.push_back(DefaultMemSIOperand(NameLoc)); 2352 Operands.push_back(X86Operand::CreateReg(X86::DX, NameLoc, NameLoc)); 2353 } 2354 } 2355 2356 // Transform "lods[bwlq]" into "lods[bwlq] ($SIREG)" for appropriate 2357 // values of $SIREG according to the mode. It would be nice if this 2358 // could be achieved with InstAlias in the tables. 2359 if (Name.startswith("lods") && Operands.size() == 1 && 2360 (Name == "lods" || Name == "lodsb" || Name == "lodsw" || 2361 Name == "lodsl" || Name == "lodsd" || Name == "lodsq")) 2362 Operands.push_back(DefaultMemSIOperand(NameLoc)); 2363 2364 // Transform "stos[bwlq]" into "stos[bwlq] ($DIREG)" for appropriate 2365 // values of $DIREG according to the mode. It would be nice if this 2366 // could be achieved with InstAlias in the tables. 2367 if (Name.startswith("stos") && Operands.size() == 1 && 2368 (Name == "stos" || Name == "stosb" || Name == "stosw" || 2369 Name == "stosl" || Name == "stosd" || Name == "stosq")) 2370 Operands.push_back(DefaultMemDIOperand(NameLoc)); 2371 2372 // Transform "scas[bwlq]" into "scas[bwlq] ($DIREG)" for appropriate 2373 // values of $DIREG according to the mode. It would be nice if this 2374 // could be achieved with InstAlias in the tables. 2375 if (Name.startswith("scas") && Operands.size() == 1 && 2376 (Name == "scas" || Name == "scasb" || Name == "scasw" || 2377 Name == "scasl" || Name == "scasd" || Name == "scasq")) 2378 Operands.push_back(DefaultMemDIOperand(NameLoc)); 2379 2380 // Add default SI and DI operands to "cmps[bwlq]". 2381 if (Name.startswith("cmps") && 2382 (Name == "cmps" || Name == "cmpsb" || Name == "cmpsw" || 2383 Name == "cmpsl" || Name == "cmpsd" || Name == "cmpsq")) { 2384 if (Operands.size() == 1) { 2385 if (isParsingIntelSyntax()) { 2386 Operands.push_back(DefaultMemSIOperand(NameLoc)); 2387 Operands.push_back(DefaultMemDIOperand(NameLoc)); 2388 } else { 2389 Operands.push_back(DefaultMemDIOperand(NameLoc)); 2390 Operands.push_back(DefaultMemSIOperand(NameLoc)); 2391 } 2392 } else if (Operands.size() == 3) { 2393 X86Operand &Op = *(X86Operand*)Operands.begin()[1]; 2394 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2]; 2395 if (!doSrcDstMatch(Op, Op2)) 2396 return Error(Op.getStartLoc(), 2397 "mismatching source and destination index registers"); 2398 } 2399 } 2400 2401 // Add default SI and DI operands to "movs[bwlq]". 2402 if ((Name.startswith("movs") && 2403 (Name == "movs" || Name == "movsb" || Name == "movsw" || 2404 Name == "movsl" || Name == "movsd" || Name == "movsq")) || 2405 (Name.startswith("smov") && 2406 (Name == "smov" || Name == "smovb" || Name == "smovw" || 2407 Name == "smovl" || Name == "smovd" || Name == "smovq"))) { 2408 if (Operands.size() == 1) { 2409 if (Name == "movsd") 2410 Operands.back() = X86Operand::CreateToken("movsl", NameLoc); 2411 if (isParsingIntelSyntax()) { 2412 Operands.push_back(DefaultMemDIOperand(NameLoc)); 2413 Operands.push_back(DefaultMemSIOperand(NameLoc)); 2414 } else { 2415 Operands.push_back(DefaultMemSIOperand(NameLoc)); 2416 Operands.push_back(DefaultMemDIOperand(NameLoc)); 2417 } 2418 } else if (Operands.size() == 3) { 2419 X86Operand &Op = *(X86Operand*)Operands.begin()[1]; 2420 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2]; 2421 if (!doSrcDstMatch(Op, Op2)) 2422 return Error(Op.getStartLoc(), 2423 "mismatching source and destination index registers"); 2424 } 2425 } 2426 2427 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to 2428 // "shift <op>". 2429 if ((Name.startswith("shr") || Name.startswith("sar") || 2430 Name.startswith("shl") || Name.startswith("sal") || 2431 Name.startswith("rcl") || Name.startswith("rcr") || 2432 Name.startswith("rol") || Name.startswith("ror")) && 2433 Operands.size() == 3) { 2434 if (isParsingIntelSyntax()) { 2435 // Intel syntax 2436 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]); 2437 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) && 2438 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) { 2439 delete Operands[2]; 2440 Operands.pop_back(); 2441 } 2442 } else { 2443 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]); 2444 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) && 2445 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) { 2446 delete Operands[1]; 2447 Operands.erase(Operands.begin() + 1); 2448 } 2449 } 2450 } 2451 2452 // Transforms "int $3" into "int3" as a size optimization. We can't write an 2453 // instalias with an immediate operand yet. 2454 if (Name == "int" && Operands.size() == 2) { 2455 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]); 2456 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) && 2457 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) { 2458 delete Operands[1]; 2459 Operands.erase(Operands.begin() + 1); 2460 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3"); 2461 } 2462 } 2463 2464 return false; 2465 } 2466 2467 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg, 2468 bool isCmp) { 2469 MCInst TmpInst; 2470 TmpInst.setOpcode(Opcode); 2471 if (!isCmp) 2472 TmpInst.addOperand(MCOperand::CreateReg(Reg)); 2473 TmpInst.addOperand(MCOperand::CreateReg(Reg)); 2474 TmpInst.addOperand(Inst.getOperand(0)); 2475 Inst = TmpInst; 2476 return true; 2477 } 2478 2479 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode, 2480 bool isCmp = false) { 2481 if (!Inst.getOperand(0).isImm() || 2482 !isImmSExti16i8Value(Inst.getOperand(0).getImm())) 2483 return false; 2484 2485 return convertToSExti8(Inst, Opcode, X86::AX, isCmp); 2486 } 2487 2488 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode, 2489 bool isCmp = false) { 2490 if (!Inst.getOperand(0).isImm() || 2491 !isImmSExti32i8Value(Inst.getOperand(0).getImm())) 2492 return false; 2493 2494 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp); 2495 } 2496 2497 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode, 2498 bool isCmp = false) { 2499 if (!Inst.getOperand(0).isImm() || 2500 !isImmSExti64i8Value(Inst.getOperand(0).getImm())) 2501 return false; 2502 2503 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp); 2504 } 2505 2506 bool X86AsmParser:: 2507 processInstruction(MCInst &Inst, 2508 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) { 2509 switch (Inst.getOpcode()) { 2510 default: return false; 2511 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8); 2512 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8); 2513 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8); 2514 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8); 2515 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8); 2516 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8); 2517 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8); 2518 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8); 2519 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8); 2520 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true); 2521 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true); 2522 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true); 2523 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8); 2524 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8); 2525 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8); 2526 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8); 2527 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8); 2528 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8); 2529 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8); 2530 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8); 2531 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8); 2532 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8); 2533 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8); 2534 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8); 2535 case X86::VMOVAPDrr: 2536 case X86::VMOVAPDYrr: 2537 case X86::VMOVAPSrr: 2538 case X86::VMOVAPSYrr: 2539 case X86::VMOVDQArr: 2540 case X86::VMOVDQAYrr: 2541 case X86::VMOVDQUrr: 2542 case X86::VMOVDQUYrr: 2543 case X86::VMOVUPDrr: 2544 case X86::VMOVUPDYrr: 2545 case X86::VMOVUPSrr: 2546 case X86::VMOVUPSYrr: { 2547 if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) || 2548 !X86II::isX86_64ExtendedReg(Inst.getOperand(1).getReg())) 2549 return false; 2550 2551 unsigned NewOpc; 2552 switch (Inst.getOpcode()) { 2553 default: llvm_unreachable("Invalid opcode"); 2554 case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break; 2555 case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break; 2556 case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break; 2557 case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break; 2558 case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break; 2559 case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break; 2560 case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break; 2561 case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break; 2562 case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break; 2563 case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break; 2564 case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break; 2565 case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break; 2566 } 2567 Inst.setOpcode(NewOpc); 2568 return true; 2569 } 2570 case X86::VMOVSDrr: 2571 case X86::VMOVSSrr: { 2572 if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) || 2573 !X86II::isX86_64ExtendedReg(Inst.getOperand(2).getReg())) 2574 return false; 2575 unsigned NewOpc; 2576 switch (Inst.getOpcode()) { 2577 default: llvm_unreachable("Invalid opcode"); 2578 case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break; 2579 case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break; 2580 } 2581 Inst.setOpcode(NewOpc); 2582 return true; 2583 } 2584 } 2585 } 2586 2587 static const char *getSubtargetFeatureName(unsigned Val); 2588 bool X86AsmParser:: 2589 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, 2590 SmallVectorImpl<MCParsedAsmOperand*> &Operands, 2591 MCStreamer &Out, unsigned &ErrorInfo, 2592 bool MatchingInlineAsm) { 2593 assert(!Operands.empty() && "Unexpect empty operand list!"); 2594 X86Operand *Op = static_cast<X86Operand*>(Operands[0]); 2595 assert(Op->isToken() && "Leading operand should always be a mnemonic!"); 2596 ArrayRef<SMRange> EmptyRanges = None; 2597 2598 // First, handle aliases that expand to multiple instructions. 2599 // FIXME: This should be replaced with a real .td file alias mechanism. 2600 // Also, MatchInstructionImpl should actually *do* the EmitInstruction 2601 // call. 2602 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" || 2603 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" || 2604 Op->getToken() == "finit" || Op->getToken() == "fsave" || 2605 Op->getToken() == "fstenv" || Op->getToken() == "fclex") { 2606 MCInst Inst; 2607 Inst.setOpcode(X86::WAIT); 2608 Inst.setLoc(IDLoc); 2609 if (!MatchingInlineAsm) 2610 Out.EmitInstruction(Inst, STI); 2611 2612 const char *Repl = 2613 StringSwitch<const char*>(Op->getToken()) 2614 .Case("finit", "fninit") 2615 .Case("fsave", "fnsave") 2616 .Case("fstcw", "fnstcw") 2617 .Case("fstcww", "fnstcw") 2618 .Case("fstenv", "fnstenv") 2619 .Case("fstsw", "fnstsw") 2620 .Case("fstsww", "fnstsw") 2621 .Case("fclex", "fnclex") 2622 .Default(0); 2623 assert(Repl && "Unknown wait-prefixed instruction"); 2624 delete Operands[0]; 2625 Operands[0] = X86Operand::CreateToken(Repl, IDLoc); 2626 } 2627 2628 bool WasOriginallyInvalidOperand = false; 2629 MCInst Inst; 2630 2631 // First, try a direct match. 2632 switch (MatchInstructionImpl(Operands, Inst, 2633 ErrorInfo, MatchingInlineAsm, 2634 isParsingIntelSyntax())) { 2635 default: break; 2636 case Match_Success: 2637 // Some instructions need post-processing to, for example, tweak which 2638 // encoding is selected. Loop on it while changes happen so the 2639 // individual transformations can chain off each other. 2640 if (!MatchingInlineAsm) 2641 while (processInstruction(Inst, Operands)) 2642 ; 2643 2644 Inst.setLoc(IDLoc); 2645 if (!MatchingInlineAsm) 2646 Out.EmitInstruction(Inst, STI); 2647 Opcode = Inst.getOpcode(); 2648 return false; 2649 case Match_MissingFeature: { 2650 assert(ErrorInfo && "Unknown missing feature!"); 2651 // Special case the error message for the very common case where only 2652 // a single subtarget feature is missing. 2653 std::string Msg = "instruction requires:"; 2654 unsigned Mask = 1; 2655 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) { 2656 if (ErrorInfo & Mask) { 2657 Msg += " "; 2658 Msg += getSubtargetFeatureName(ErrorInfo & Mask); 2659 } 2660 Mask <<= 1; 2661 } 2662 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm); 2663 } 2664 case Match_InvalidOperand: 2665 WasOriginallyInvalidOperand = true; 2666 break; 2667 case Match_MnemonicFail: 2668 break; 2669 } 2670 2671 // FIXME: Ideally, we would only attempt suffix matches for things which are 2672 // valid prefixes, and we could just infer the right unambiguous 2673 // type. However, that requires substantially more matcher support than the 2674 // following hack. 2675 2676 // Change the operand to point to a temporary token. 2677 StringRef Base = Op->getToken(); 2678 SmallString<16> Tmp; 2679 Tmp += Base; 2680 Tmp += ' '; 2681 Op->setTokenValue(Tmp.str()); 2682 2683 // If this instruction starts with an 'f', then it is a floating point stack 2684 // instruction. These come in up to three forms for 32-bit, 64-bit, and 2685 // 80-bit floating point, which use the suffixes s,l,t respectively. 2686 // 2687 // Otherwise, we assume that this may be an integer instruction, which comes 2688 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively. 2689 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0"; 2690 2691 // Check for the various suffix matches. 2692 Tmp[Base.size()] = Suffixes[0]; 2693 unsigned ErrorInfoIgnore; 2694 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings. 2695 unsigned Match1, Match2, Match3, Match4; 2696 2697 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore, 2698 MatchingInlineAsm, isParsingIntelSyntax()); 2699 // If this returned as a missing feature failure, remember that. 2700 if (Match1 == Match_MissingFeature) 2701 ErrorInfoMissingFeature = ErrorInfoIgnore; 2702 Tmp[Base.size()] = Suffixes[1]; 2703 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore, 2704 MatchingInlineAsm, isParsingIntelSyntax()); 2705 // If this returned as a missing feature failure, remember that. 2706 if (Match2 == Match_MissingFeature) 2707 ErrorInfoMissingFeature = ErrorInfoIgnore; 2708 Tmp[Base.size()] = Suffixes[2]; 2709 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore, 2710 MatchingInlineAsm, isParsingIntelSyntax()); 2711 // If this returned as a missing feature failure, remember that. 2712 if (Match3 == Match_MissingFeature) 2713 ErrorInfoMissingFeature = ErrorInfoIgnore; 2714 Tmp[Base.size()] = Suffixes[3]; 2715 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore, 2716 MatchingInlineAsm, isParsingIntelSyntax()); 2717 // If this returned as a missing feature failure, remember that. 2718 if (Match4 == Match_MissingFeature) 2719 ErrorInfoMissingFeature = ErrorInfoIgnore; 2720 2721 // Restore the old token. 2722 Op->setTokenValue(Base); 2723 2724 // If exactly one matched, then we treat that as a successful match (and the 2725 // instruction will already have been filled in correctly, since the failing 2726 // matches won't have modified it). 2727 unsigned NumSuccessfulMatches = 2728 (Match1 == Match_Success) + (Match2 == Match_Success) + 2729 (Match3 == Match_Success) + (Match4 == Match_Success); 2730 if (NumSuccessfulMatches == 1) { 2731 Inst.setLoc(IDLoc); 2732 if (!MatchingInlineAsm) 2733 Out.EmitInstruction(Inst, STI); 2734 Opcode = Inst.getOpcode(); 2735 return false; 2736 } 2737 2738 // Otherwise, the match failed, try to produce a decent error message. 2739 2740 // If we had multiple suffix matches, then identify this as an ambiguous 2741 // match. 2742 if (NumSuccessfulMatches > 1) { 2743 char MatchChars[4]; 2744 unsigned NumMatches = 0; 2745 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0]; 2746 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1]; 2747 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2]; 2748 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3]; 2749 2750 SmallString<126> Msg; 2751 raw_svector_ostream OS(Msg); 2752 OS << "ambiguous instructions require an explicit suffix (could be "; 2753 for (unsigned i = 0; i != NumMatches; ++i) { 2754 if (i != 0) 2755 OS << ", "; 2756 if (i + 1 == NumMatches) 2757 OS << "or "; 2758 OS << "'" << Base << MatchChars[i] << "'"; 2759 } 2760 OS << ")"; 2761 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm); 2762 return true; 2763 } 2764 2765 // Okay, we know that none of the variants matched successfully. 2766 2767 // If all of the instructions reported an invalid mnemonic, then the original 2768 // mnemonic was invalid. 2769 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) && 2770 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) { 2771 if (!WasOriginallyInvalidOperand) { 2772 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges : 2773 Op->getLocRange(); 2774 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'", 2775 Ranges, MatchingInlineAsm); 2776 } 2777 2778 // Recover location info for the operand if we know which was the problem. 2779 if (ErrorInfo != ~0U) { 2780 if (ErrorInfo >= Operands.size()) 2781 return Error(IDLoc, "too few operands for instruction", 2782 EmptyRanges, MatchingInlineAsm); 2783 2784 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo]; 2785 if (Operand->getStartLoc().isValid()) { 2786 SMRange OperandRange = Operand->getLocRange(); 2787 return Error(Operand->getStartLoc(), "invalid operand for instruction", 2788 OperandRange, MatchingInlineAsm); 2789 } 2790 } 2791 2792 return Error(IDLoc, "invalid operand for instruction", EmptyRanges, 2793 MatchingInlineAsm); 2794 } 2795 2796 // If one instruction matched with a missing feature, report this as a 2797 // missing feature. 2798 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) + 2799 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){ 2800 std::string Msg = "instruction requires:"; 2801 unsigned Mask = 1; 2802 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) { 2803 if (ErrorInfoMissingFeature & Mask) { 2804 Msg += " "; 2805 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask); 2806 } 2807 Mask <<= 1; 2808 } 2809 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm); 2810 } 2811 2812 // If one instruction matched with an invalid operand, report this as an 2813 // operand failure. 2814 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) + 2815 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){ 2816 Error(IDLoc, "invalid operand for instruction", EmptyRanges, 2817 MatchingInlineAsm); 2818 return true; 2819 } 2820 2821 // If all of these were an outright failure, report it in a useless way. 2822 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix", 2823 EmptyRanges, MatchingInlineAsm); 2824 return true; 2825 } 2826 2827 2828 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) { 2829 StringRef IDVal = DirectiveID.getIdentifier(); 2830 if (IDVal == ".word") 2831 return ParseDirectiveWord(2, DirectiveID.getLoc()); 2832 else if (IDVal.startswith(".code")) 2833 return ParseDirectiveCode(IDVal, DirectiveID.getLoc()); 2834 else if (IDVal.startswith(".att_syntax")) { 2835 getParser().setAssemblerDialect(0); 2836 return false; 2837 } else if (IDVal.startswith(".intel_syntax")) { 2838 getParser().setAssemblerDialect(1); 2839 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2840 // FIXME: Handle noprefix 2841 if (Parser.getTok().getString() == "noprefix") 2842 Parser.Lex(); 2843 } 2844 return false; 2845 } 2846 return true; 2847 } 2848 2849 /// ParseDirectiveWord 2850 /// ::= .word [ expression (, expression)* ] 2851 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) { 2852 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2853 for (;;) { 2854 const MCExpr *Value; 2855 if (getParser().parseExpression(Value)) 2856 return false; 2857 2858 getParser().getStreamer().EmitValue(Value, Size); 2859 2860 if (getLexer().is(AsmToken::EndOfStatement)) 2861 break; 2862 2863 // FIXME: Improve diagnostic. 2864 if (getLexer().isNot(AsmToken::Comma)) { 2865 Error(L, "unexpected token in directive"); 2866 return false; 2867 } 2868 Parser.Lex(); 2869 } 2870 } 2871 2872 Parser.Lex(); 2873 return false; 2874 } 2875 2876 /// ParseDirectiveCode 2877 /// ::= .code16 | .code32 | .code64 2878 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) { 2879 if (IDVal == ".code16") { 2880 Parser.Lex(); 2881 if (!is16BitMode()) { 2882 SwitchMode(X86::Mode16Bit); 2883 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16); 2884 } 2885 } else if (IDVal == ".code32") { 2886 Parser.Lex(); 2887 if (!is32BitMode()) { 2888 SwitchMode(X86::Mode32Bit); 2889 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32); 2890 } 2891 } else if (IDVal == ".code64") { 2892 Parser.Lex(); 2893 if (!is64BitMode()) { 2894 SwitchMode(X86::Mode64Bit); 2895 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64); 2896 } 2897 } else { 2898 Error(L, "unknown directive " + IDVal); 2899 return false; 2900 } 2901 2902 return false; 2903 } 2904 2905 // Force static initialization. 2906 extern "C" void LLVMInitializeX86AsmParser() { 2907 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target); 2908 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target); 2909 } 2910 2911 #define GET_REGISTER_MATCHER 2912 #define GET_MATCHER_IMPLEMENTATION 2913 #define GET_SUBTARGET_FEATURE_NAME 2914 #include "X86GenAsmMatcher.inc" 2915