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 "X86AsmInstrumentation.h" 12 #include "X86AsmParserCommon.h" 13 #include "X86Operand.h" 14 #include "InstPrinter/X86IntelInstPrinter.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/StringSwitch.h" 19 #include "llvm/ADT/Twine.h" 20 #include "llvm/MC/MCContext.h" 21 #include "llvm/MC/MCExpr.h" 22 #include "llvm/MC/MCInst.h" 23 #include "llvm/MC/MCInstrInfo.h" 24 #include "llvm/MC/MCParser/MCAsmLexer.h" 25 #include "llvm/MC/MCParser/MCAsmParser.h" 26 #include "llvm/MC/MCParser/MCParsedAsmOperand.h" 27 #include "llvm/MC/MCParser/MCTargetAsmParser.h" 28 #include "llvm/MC/MCRegisterInfo.h" 29 #include "llvm/MC/MCSection.h" 30 #include "llvm/MC/MCStreamer.h" 31 #include "llvm/MC/MCSubtargetInfo.h" 32 #include "llvm/MC/MCSymbol.h" 33 #include "llvm/Support/SourceMgr.h" 34 #include "llvm/Support/TargetRegistry.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include <algorithm> 37 #include <memory> 38 39 using namespace llvm; 40 41 static bool checkScale(unsigned Scale, StringRef &ErrMsg) { 42 if (Scale != 1 && Scale != 2 && Scale != 4 && Scale != 8) { 43 ErrMsg = "scale factor in address must be 1, 2, 4 or 8"; 44 return true; 45 } 46 return false; 47 } 48 49 namespace { 50 51 static const char OpPrecedence[] = { 52 0, // IC_OR 53 1, // IC_XOR 54 2, // IC_AND 55 3, // IC_LSHIFT 56 3, // IC_RSHIFT 57 4, // IC_PLUS 58 4, // IC_MINUS 59 5, // IC_MULTIPLY 60 5, // IC_DIVIDE 61 5, // IC_MOD 62 6, // IC_NOT 63 7, // IC_NEG 64 8, // IC_RPAREN 65 9, // IC_LPAREN 66 0, // IC_IMM 67 0 // IC_REGISTER 68 }; 69 70 class X86AsmParser : public MCTargetAsmParser { 71 const MCInstrInfo &MII; 72 ParseInstructionInfo *InstInfo; 73 std::unique_ptr<X86AsmInstrumentation> Instrumentation; 74 bool Code16GCC; 75 76 private: 77 SMLoc consumeToken() { 78 MCAsmParser &Parser = getParser(); 79 SMLoc Result = Parser.getTok().getLoc(); 80 Parser.Lex(); 81 return Result; 82 } 83 84 unsigned MatchInstruction(const OperandVector &Operands, MCInst &Inst, 85 uint64_t &ErrorInfo, bool matchingInlineAsm, 86 unsigned VariantID = 0) { 87 // In Code16GCC mode, match as 32-bit. 88 if (Code16GCC) 89 SwitchMode(X86::Mode32Bit); 90 unsigned rv = MatchInstructionImpl(Operands, Inst, ErrorInfo, 91 matchingInlineAsm, VariantID); 92 if (Code16GCC) 93 SwitchMode(X86::Mode16Bit); 94 return rv; 95 } 96 97 enum InfixCalculatorTok { 98 IC_OR = 0, 99 IC_XOR, 100 IC_AND, 101 IC_LSHIFT, 102 IC_RSHIFT, 103 IC_PLUS, 104 IC_MINUS, 105 IC_MULTIPLY, 106 IC_DIVIDE, 107 IC_MOD, 108 IC_NOT, 109 IC_NEG, 110 IC_RPAREN, 111 IC_LPAREN, 112 IC_IMM, 113 IC_REGISTER 114 }; 115 116 enum IntelOperatorKind { 117 IOK_INVALID = 0, 118 IOK_LENGTH, 119 IOK_SIZE, 120 IOK_TYPE, 121 IOK_OFFSET 122 }; 123 124 class InfixCalculator { 125 typedef std::pair< InfixCalculatorTok, int64_t > ICToken; 126 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack; 127 SmallVector<ICToken, 4> PostfixStack; 128 129 bool isUnaryOperator(const InfixCalculatorTok Op) { 130 return Op == IC_NEG || Op == IC_NOT; 131 } 132 133 public: 134 int64_t popOperand() { 135 assert (!PostfixStack.empty() && "Poped an empty stack!"); 136 ICToken Op = PostfixStack.pop_back_val(); 137 if (!(Op.first == IC_IMM || Op.first == IC_REGISTER)) 138 return -1; // The invalid Scale value will be caught later by checkScale 139 return Op.second; 140 } 141 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) { 142 assert ((Op == IC_IMM || Op == IC_REGISTER) && 143 "Unexpected operand!"); 144 PostfixStack.push_back(std::make_pair(Op, Val)); 145 } 146 147 void popOperator() { InfixOperatorStack.pop_back(); } 148 void pushOperator(InfixCalculatorTok Op) { 149 // Push the new operator if the stack is empty. 150 if (InfixOperatorStack.empty()) { 151 InfixOperatorStack.push_back(Op); 152 return; 153 } 154 155 // Push the new operator if it has a higher precedence than the operator 156 // on the top of the stack or the operator on the top of the stack is a 157 // left parentheses. 158 unsigned Idx = InfixOperatorStack.size() - 1; 159 InfixCalculatorTok StackOp = InfixOperatorStack[Idx]; 160 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) { 161 InfixOperatorStack.push_back(Op); 162 return; 163 } 164 165 // The operator on the top of the stack has higher precedence than the 166 // new operator. 167 unsigned ParenCount = 0; 168 while (1) { 169 // Nothing to process. 170 if (InfixOperatorStack.empty()) 171 break; 172 173 Idx = InfixOperatorStack.size() - 1; 174 StackOp = InfixOperatorStack[Idx]; 175 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount)) 176 break; 177 178 // If we have an even parentheses count and we see a left parentheses, 179 // then stop processing. 180 if (!ParenCount && StackOp == IC_LPAREN) 181 break; 182 183 if (StackOp == IC_RPAREN) { 184 ++ParenCount; 185 InfixOperatorStack.pop_back(); 186 } else if (StackOp == IC_LPAREN) { 187 --ParenCount; 188 InfixOperatorStack.pop_back(); 189 } else { 190 InfixOperatorStack.pop_back(); 191 PostfixStack.push_back(std::make_pair(StackOp, 0)); 192 } 193 } 194 // Push the new operator. 195 InfixOperatorStack.push_back(Op); 196 } 197 198 int64_t execute() { 199 // Push any remaining operators onto the postfix stack. 200 while (!InfixOperatorStack.empty()) { 201 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val(); 202 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN) 203 PostfixStack.push_back(std::make_pair(StackOp, 0)); 204 } 205 206 if (PostfixStack.empty()) 207 return 0; 208 209 SmallVector<ICToken, 16> OperandStack; 210 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) { 211 ICToken Op = PostfixStack[i]; 212 if (Op.first == IC_IMM || Op.first == IC_REGISTER) { 213 OperandStack.push_back(Op); 214 } else if (isUnaryOperator(Op.first)) { 215 assert (OperandStack.size() > 0 && "Too few operands."); 216 ICToken Operand = OperandStack.pop_back_val(); 217 assert (Operand.first == IC_IMM && 218 "Unary operation with a register!"); 219 switch (Op.first) { 220 default: 221 report_fatal_error("Unexpected operator!"); 222 break; 223 case IC_NEG: 224 OperandStack.push_back(std::make_pair(IC_IMM, -Operand.second)); 225 break; 226 case IC_NOT: 227 OperandStack.push_back(std::make_pair(IC_IMM, ~Operand.second)); 228 break; 229 } 230 } else { 231 assert (OperandStack.size() > 1 && "Too few operands."); 232 int64_t Val; 233 ICToken Op2 = OperandStack.pop_back_val(); 234 ICToken Op1 = OperandStack.pop_back_val(); 235 switch (Op.first) { 236 default: 237 report_fatal_error("Unexpected operator!"); 238 break; 239 case IC_PLUS: 240 Val = Op1.second + Op2.second; 241 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 242 break; 243 case IC_MINUS: 244 Val = Op1.second - Op2.second; 245 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 246 break; 247 case IC_MULTIPLY: 248 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 249 "Multiply operation with an immediate and a register!"); 250 Val = Op1.second * Op2.second; 251 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 252 break; 253 case IC_DIVIDE: 254 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 255 "Divide operation with an immediate and a register!"); 256 assert (Op2.second != 0 && "Division by zero!"); 257 Val = Op1.second / Op2.second; 258 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 259 break; 260 case IC_MOD: 261 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 262 "Modulo operation with an immediate and a register!"); 263 Val = Op1.second % Op2.second; 264 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 265 break; 266 case IC_OR: 267 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 268 "Or operation with an immediate and a register!"); 269 Val = Op1.second | Op2.second; 270 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 271 break; 272 case IC_XOR: 273 assert(Op1.first == IC_IMM && Op2.first == IC_IMM && 274 "Xor operation with an immediate and a register!"); 275 Val = Op1.second ^ Op2.second; 276 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 277 break; 278 case IC_AND: 279 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 280 "And operation with an immediate and a register!"); 281 Val = Op1.second & Op2.second; 282 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 283 break; 284 case IC_LSHIFT: 285 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 286 "Left shift operation with an immediate and a register!"); 287 Val = Op1.second << Op2.second; 288 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 289 break; 290 case IC_RSHIFT: 291 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 292 "Right shift operation with an immediate and a register!"); 293 Val = Op1.second >> Op2.second; 294 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 295 break; 296 } 297 } 298 } 299 assert (OperandStack.size() == 1 && "Expected a single result."); 300 return OperandStack.pop_back_val().second; 301 } 302 }; 303 304 enum IntelExprState { 305 IES_INIT, 306 IES_OR, 307 IES_XOR, 308 IES_AND, 309 IES_LSHIFT, 310 IES_RSHIFT, 311 IES_PLUS, 312 IES_MINUS, 313 IES_NOT, 314 IES_MULTIPLY, 315 IES_DIVIDE, 316 IES_MOD, 317 IES_LBRAC, 318 IES_RBRAC, 319 IES_LPAREN, 320 IES_RPAREN, 321 IES_REGISTER, 322 IES_INTEGER, 323 IES_IDENTIFIER, 324 IES_ERROR 325 }; 326 327 class IntelExprStateMachine { 328 IntelExprState State, PrevState; 329 unsigned BaseReg, IndexReg, TmpReg, Scale; 330 int64_t Imm; 331 const MCExpr *Sym; 332 StringRef SymName; 333 InfixCalculator IC; 334 InlineAsmIdentifierInfo Info; 335 short BracCount; 336 bool MemExpr; 337 338 public: 339 IntelExprStateMachine() 340 : State(IES_INIT), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), 341 TmpReg(0), Scale(1), Imm(0), Sym(nullptr), BracCount(0), 342 MemExpr(false) { 343 Info.clear(); 344 } 345 346 void addImm(int64_t imm) { Imm += imm; } 347 short getBracCount() { return BracCount; } 348 bool isMemExpr() { return MemExpr; } 349 unsigned getBaseReg() { return BaseReg; } 350 unsigned getIndexReg() { return IndexReg; } 351 unsigned getScale() { return Scale; } 352 const MCExpr *getSym() { return Sym; } 353 StringRef getSymName() { return SymName; } 354 int64_t getImm() { return Imm + IC.execute(); } 355 bool isValidEndState() { 356 return State == IES_RBRAC || State == IES_INTEGER; 357 } 358 bool hadError() { return State == IES_ERROR; } 359 InlineAsmIdentifierInfo &getIdentifierInfo() { return Info; } 360 361 void onOr() { 362 IntelExprState CurrState = State; 363 switch (State) { 364 default: 365 State = IES_ERROR; 366 break; 367 case IES_INTEGER: 368 case IES_RPAREN: 369 case IES_REGISTER: 370 State = IES_OR; 371 IC.pushOperator(IC_OR); 372 break; 373 } 374 PrevState = CurrState; 375 } 376 void onXor() { 377 IntelExprState CurrState = State; 378 switch (State) { 379 default: 380 State = IES_ERROR; 381 break; 382 case IES_INTEGER: 383 case IES_RPAREN: 384 case IES_REGISTER: 385 State = IES_XOR; 386 IC.pushOperator(IC_XOR); 387 break; 388 } 389 PrevState = CurrState; 390 } 391 void onAnd() { 392 IntelExprState CurrState = State; 393 switch (State) { 394 default: 395 State = IES_ERROR; 396 break; 397 case IES_INTEGER: 398 case IES_RPAREN: 399 case IES_REGISTER: 400 State = IES_AND; 401 IC.pushOperator(IC_AND); 402 break; 403 } 404 PrevState = CurrState; 405 } 406 void onLShift() { 407 IntelExprState CurrState = State; 408 switch (State) { 409 default: 410 State = IES_ERROR; 411 break; 412 case IES_INTEGER: 413 case IES_RPAREN: 414 case IES_REGISTER: 415 State = IES_LSHIFT; 416 IC.pushOperator(IC_LSHIFT); 417 break; 418 } 419 PrevState = CurrState; 420 } 421 void onRShift() { 422 IntelExprState CurrState = State; 423 switch (State) { 424 default: 425 State = IES_ERROR; 426 break; 427 case IES_INTEGER: 428 case IES_RPAREN: 429 case IES_REGISTER: 430 State = IES_RSHIFT; 431 IC.pushOperator(IC_RSHIFT); 432 break; 433 } 434 PrevState = CurrState; 435 } 436 bool onPlus(StringRef &ErrMsg) { 437 IntelExprState CurrState = State; 438 switch (State) { 439 default: 440 State = IES_ERROR; 441 break; 442 case IES_INTEGER: 443 case IES_RPAREN: 444 case IES_REGISTER: 445 State = IES_PLUS; 446 IC.pushOperator(IC_PLUS); 447 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) { 448 // If we already have a BaseReg, then assume this is the IndexReg with 449 // a scale of 1. 450 if (!BaseReg) { 451 BaseReg = TmpReg; 452 } else { 453 if (IndexReg) { 454 ErrMsg = "BaseReg/IndexReg already set!"; 455 return true; 456 } 457 IndexReg = TmpReg; 458 Scale = 1; 459 } 460 } 461 break; 462 } 463 PrevState = CurrState; 464 return false; 465 } 466 bool onMinus(StringRef &ErrMsg) { 467 IntelExprState CurrState = State; 468 switch (State) { 469 default: 470 State = IES_ERROR; 471 break; 472 case IES_OR: 473 case IES_XOR: 474 case IES_AND: 475 case IES_LSHIFT: 476 case IES_RSHIFT: 477 case IES_PLUS: 478 case IES_NOT: 479 case IES_MULTIPLY: 480 case IES_DIVIDE: 481 case IES_MOD: 482 case IES_LPAREN: 483 case IES_RPAREN: 484 case IES_LBRAC: 485 case IES_RBRAC: 486 case IES_INTEGER: 487 case IES_REGISTER: 488 case IES_INIT: 489 State = IES_MINUS; 490 // push minus operator if it is not a negate operator 491 if (CurrState == IES_REGISTER || CurrState == IES_RPAREN || 492 CurrState == IES_INTEGER || CurrState == IES_RBRAC) 493 IC.pushOperator(IC_MINUS); 494 else if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) { 495 // We have negate operator for Scale: it's illegal 496 ErrMsg = "Scale can't be negative"; 497 return true; 498 } else 499 IC.pushOperator(IC_NEG); 500 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) { 501 // If we already have a BaseReg, then assume this is the IndexReg with 502 // a scale of 1. 503 if (!BaseReg) { 504 BaseReg = TmpReg; 505 } else { 506 if (IndexReg) { 507 ErrMsg = "BaseReg/IndexReg already set!"; 508 return true; 509 } 510 IndexReg = TmpReg; 511 Scale = 1; 512 } 513 } 514 break; 515 } 516 PrevState = CurrState; 517 return false; 518 } 519 void onNot() { 520 IntelExprState CurrState = State; 521 switch (State) { 522 default: 523 State = IES_ERROR; 524 break; 525 case IES_OR: 526 case IES_XOR: 527 case IES_AND: 528 case IES_LSHIFT: 529 case IES_RSHIFT: 530 case IES_PLUS: 531 case IES_MINUS: 532 case IES_NOT: 533 case IES_MULTIPLY: 534 case IES_DIVIDE: 535 case IES_MOD: 536 case IES_LPAREN: 537 case IES_LBRAC: 538 case IES_INIT: 539 State = IES_NOT; 540 IC.pushOperator(IC_NOT); 541 break; 542 } 543 PrevState = CurrState; 544 } 545 546 bool onRegister(unsigned Reg, StringRef &ErrMsg) { 547 IntelExprState CurrState = State; 548 switch (State) { 549 default: 550 State = IES_ERROR; 551 break; 552 case IES_PLUS: 553 case IES_LPAREN: 554 case IES_LBRAC: 555 State = IES_REGISTER; 556 TmpReg = Reg; 557 IC.pushOperand(IC_REGISTER); 558 break; 559 case IES_MULTIPLY: 560 // Index Register - Scale * Register 561 if (PrevState == IES_INTEGER) { 562 if (IndexReg) { 563 ErrMsg = "BaseReg/IndexReg already set!"; 564 return true; 565 } 566 State = IES_REGISTER; 567 IndexReg = Reg; 568 // Get the scale and replace the 'Scale * Register' with '0'. 569 Scale = IC.popOperand(); 570 if (checkScale(Scale, ErrMsg)) 571 return true; 572 IC.pushOperand(IC_IMM); 573 IC.popOperator(); 574 } else { 575 State = IES_ERROR; 576 } 577 break; 578 } 579 PrevState = CurrState; 580 return false; 581 } 582 bool onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName, 583 StringRef &ErrMsg) { 584 PrevState = State; 585 bool HasSymbol = Sym != nullptr; 586 switch (State) { 587 default: 588 State = IES_ERROR; 589 break; 590 case IES_PLUS: 591 case IES_MINUS: 592 case IES_NOT: 593 case IES_INIT: 594 case IES_LBRAC: 595 MemExpr = !(SymRef->getKind() == MCExpr::Constant); 596 State = IES_INTEGER; 597 Sym = SymRef; 598 SymName = SymRefName; 599 IC.pushOperand(IC_IMM); 600 break; 601 } 602 if (HasSymbol) 603 ErrMsg = "cannot use more than one symbol in memory operand"; 604 return HasSymbol; 605 } 606 bool onInteger(int64_t TmpInt, StringRef &ErrMsg) { 607 IntelExprState CurrState = State; 608 switch (State) { 609 default: 610 State = IES_ERROR; 611 break; 612 case IES_PLUS: 613 case IES_MINUS: 614 case IES_NOT: 615 case IES_OR: 616 case IES_XOR: 617 case IES_AND: 618 case IES_LSHIFT: 619 case IES_RSHIFT: 620 case IES_DIVIDE: 621 case IES_MOD: 622 case IES_MULTIPLY: 623 case IES_LPAREN: 624 case IES_INIT: 625 case IES_LBRAC: 626 State = IES_INTEGER; 627 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) { 628 // Index Register - Register * Scale 629 if (IndexReg) { 630 ErrMsg = "BaseReg/IndexReg already set!"; 631 return true; 632 } 633 IndexReg = TmpReg; 634 Scale = TmpInt; 635 if (checkScale(Scale, ErrMsg)) 636 return true; 637 // Get the scale and replace the 'Register * Scale' with '0'. 638 IC.popOperator(); 639 } else { 640 IC.pushOperand(IC_IMM, TmpInt); 641 } 642 break; 643 } 644 PrevState = CurrState; 645 return false; 646 } 647 void onStar() { 648 PrevState = State; 649 switch (State) { 650 default: 651 State = IES_ERROR; 652 break; 653 case IES_INTEGER: 654 case IES_REGISTER: 655 case IES_RPAREN: 656 State = IES_MULTIPLY; 657 IC.pushOperator(IC_MULTIPLY); 658 break; 659 } 660 } 661 void onDivide() { 662 PrevState = State; 663 switch (State) { 664 default: 665 State = IES_ERROR; 666 break; 667 case IES_INTEGER: 668 case IES_RPAREN: 669 State = IES_DIVIDE; 670 IC.pushOperator(IC_DIVIDE); 671 break; 672 } 673 } 674 void onMod() { 675 PrevState = State; 676 switch (State) { 677 default: 678 State = IES_ERROR; 679 break; 680 case IES_INTEGER: 681 case IES_RPAREN: 682 State = IES_MOD; 683 IC.pushOperator(IC_MOD); 684 break; 685 } 686 } 687 bool onLBrac() { 688 if (BracCount) 689 return true; 690 PrevState = State; 691 switch (State) { 692 default: 693 State = IES_ERROR; 694 break; 695 case IES_RBRAC: 696 case IES_INTEGER: 697 case IES_RPAREN: 698 State = IES_PLUS; 699 IC.pushOperator(IC_PLUS); 700 break; 701 case IES_INIT: 702 assert(!BracCount && "BracCount should be zero on parsing's start"); 703 State = IES_LBRAC; 704 break; 705 } 706 MemExpr = true; 707 BracCount++; 708 return false; 709 } 710 bool onRBrac() { 711 IntelExprState CurrState = State; 712 switch (State) { 713 default: 714 State = IES_ERROR; 715 break; 716 case IES_INTEGER: 717 case IES_REGISTER: 718 case IES_RPAREN: 719 if (BracCount-- != 1) 720 return true; 721 State = IES_RBRAC; 722 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) { 723 // If we already have a BaseReg, then assume this is the IndexReg with 724 // a scale of 1. 725 if (!BaseReg) { 726 BaseReg = TmpReg; 727 } else { 728 assert (!IndexReg && "BaseReg/IndexReg already set!"); 729 IndexReg = TmpReg; 730 Scale = 1; 731 } 732 } 733 break; 734 } 735 PrevState = CurrState; 736 return false; 737 } 738 void onLParen() { 739 IntelExprState CurrState = State; 740 switch (State) { 741 default: 742 State = IES_ERROR; 743 break; 744 case IES_PLUS: 745 case IES_MINUS: 746 case IES_NOT: 747 case IES_OR: 748 case IES_XOR: 749 case IES_AND: 750 case IES_LSHIFT: 751 case IES_RSHIFT: 752 case IES_MULTIPLY: 753 case IES_DIVIDE: 754 case IES_MOD: 755 case IES_LPAREN: 756 case IES_INIT: 757 case IES_LBRAC: 758 State = IES_LPAREN; 759 IC.pushOperator(IC_LPAREN); 760 break; 761 } 762 PrevState = CurrState; 763 } 764 void onRParen() { 765 PrevState = State; 766 switch (State) { 767 default: 768 State = IES_ERROR; 769 break; 770 case IES_INTEGER: 771 case IES_REGISTER: 772 case IES_RPAREN: 773 State = IES_RPAREN; 774 IC.pushOperator(IC_RPAREN); 775 break; 776 } 777 } 778 }; 779 780 bool Error(SMLoc L, const Twine &Msg, SMRange Range = None, 781 bool MatchingInlineAsm = false) { 782 MCAsmParser &Parser = getParser(); 783 if (MatchingInlineAsm) { 784 if (!getLexer().isAtStartOfStatement()) 785 Parser.eatToEndOfStatement(); 786 return false; 787 } 788 return Parser.Error(L, Msg, Range); 789 } 790 791 std::nullptr_t ErrorOperand(SMLoc Loc, StringRef Msg) { 792 Error(Loc, Msg); 793 return nullptr; 794 } 795 796 std::unique_ptr<X86Operand> DefaultMemSIOperand(SMLoc Loc); 797 std::unique_ptr<X86Operand> DefaultMemDIOperand(SMLoc Loc); 798 bool IsSIReg(unsigned Reg); 799 unsigned GetSIDIForRegClass(unsigned RegClassID, unsigned Reg, bool IsSIReg); 800 void 801 AddDefaultSrcDestOperands(OperandVector &Operands, 802 std::unique_ptr<llvm::MCParsedAsmOperand> &&Src, 803 std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst); 804 bool VerifyAndAdjustOperands(OperandVector &OrigOperands, 805 OperandVector &FinalOperands); 806 std::unique_ptr<X86Operand> ParseOperand(); 807 std::unique_ptr<X86Operand> ParseATTOperand(); 808 std::unique_ptr<X86Operand> ParseIntelOperand(); 809 std::unique_ptr<X86Operand> ParseIntelOffsetOfOperator(); 810 bool ParseIntelDotOperator(IntelExprStateMachine &SM, SMLoc &End); 811 unsigned IdentifyIntelInlineAsmOperator(StringRef Name); 812 unsigned ParseIntelInlineAsmOperator(unsigned OpKind); 813 std::unique_ptr<X86Operand> ParseRoundingModeOp(SMLoc Start, SMLoc End); 814 bool ParseIntelNamedOperator(StringRef Name, IntelExprStateMachine &SM); 815 void RewriteIntelExpression(IntelExprStateMachine &SM, SMLoc Start, 816 SMLoc End); 817 bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End); 818 bool ParseIntelInlineAsmIdentifier(const MCExpr *&Val, StringRef &Identifier, 819 InlineAsmIdentifierInfo &Info, 820 bool IsUnevaluatedOperand, SMLoc &End); 821 822 std::unique_ptr<X86Operand> ParseMemOperand(unsigned SegReg, SMLoc StartLoc); 823 824 bool ParseIntelMemoryOperandSize(unsigned &Size); 825 std::unique_ptr<X86Operand> 826 CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp, unsigned BaseReg, 827 unsigned IndexReg, unsigned Scale, SMLoc Start, 828 SMLoc End, unsigned Size, StringRef Identifier, 829 const InlineAsmIdentifierInfo &Info); 830 831 bool parseDirectiveEven(SMLoc L); 832 bool ParseDirectiveWord(unsigned Size, SMLoc L); 833 bool ParseDirectiveCode(StringRef IDVal, SMLoc L); 834 835 bool processInstruction(MCInst &Inst, const OperandVector &Ops); 836 837 /// Wrapper around MCStreamer::EmitInstruction(). Possibly adds 838 /// instrumentation around Inst. 839 void EmitInstruction(MCInst &Inst, OperandVector &Operands, MCStreamer &Out); 840 841 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, 842 OperandVector &Operands, MCStreamer &Out, 843 uint64_t &ErrorInfo, 844 bool MatchingInlineAsm) override; 845 846 void MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op, OperandVector &Operands, 847 MCStreamer &Out, bool MatchingInlineAsm); 848 849 bool ErrorMissingFeature(SMLoc IDLoc, uint64_t ErrorInfo, 850 bool MatchingInlineAsm); 851 852 bool MatchAndEmitATTInstruction(SMLoc IDLoc, unsigned &Opcode, 853 OperandVector &Operands, MCStreamer &Out, 854 uint64_t &ErrorInfo, 855 bool MatchingInlineAsm); 856 857 bool MatchAndEmitIntelInstruction(SMLoc IDLoc, unsigned &Opcode, 858 OperandVector &Operands, MCStreamer &Out, 859 uint64_t &ErrorInfo, 860 bool MatchingInlineAsm); 861 862 bool OmitRegisterFromClobberLists(unsigned RegNo) override; 863 864 /// Parses AVX512 specific operand primitives: masked registers ({%k<NUM>}, {z}) 865 /// and memory broadcasting ({1to<NUM>}) primitives, updating Operands vector if required. 866 /// return false if no parsing errors occurred, true otherwise. 867 bool HandleAVX512Operand(OperandVector &Operands, 868 const MCParsedAsmOperand &Op); 869 870 bool ParseZ(std::unique_ptr<X86Operand> &Z, const SMLoc &StartLoc); 871 872 bool is64BitMode() const { 873 // FIXME: Can tablegen auto-generate this? 874 return getSTI().getFeatureBits()[X86::Mode64Bit]; 875 } 876 bool is32BitMode() const { 877 // FIXME: Can tablegen auto-generate this? 878 return getSTI().getFeatureBits()[X86::Mode32Bit]; 879 } 880 bool is16BitMode() const { 881 // FIXME: Can tablegen auto-generate this? 882 return getSTI().getFeatureBits()[X86::Mode16Bit]; 883 } 884 void SwitchMode(unsigned mode) { 885 MCSubtargetInfo &STI = copySTI(); 886 FeatureBitset AllModes({X86::Mode64Bit, X86::Mode32Bit, X86::Mode16Bit}); 887 FeatureBitset OldMode = STI.getFeatureBits() & AllModes; 888 unsigned FB = ComputeAvailableFeatures( 889 STI.ToggleFeature(OldMode.flip(mode))); 890 setAvailableFeatures(FB); 891 892 assert(FeatureBitset({mode}) == (STI.getFeatureBits() & AllModes)); 893 } 894 895 unsigned getPointerWidth() { 896 if (is16BitMode()) return 16; 897 if (is32BitMode()) return 32; 898 if (is64BitMode()) return 64; 899 llvm_unreachable("invalid mode"); 900 } 901 902 bool isParsingIntelSyntax() { 903 return getParser().getAssemblerDialect(); 904 } 905 906 /// @name Auto-generated Matcher Functions 907 /// { 908 909 #define GET_ASSEMBLER_HEADER 910 #include "X86GenAsmMatcher.inc" 911 912 /// } 913 914 public: 915 916 X86AsmParser(const MCSubtargetInfo &sti, MCAsmParser &Parser, 917 const MCInstrInfo &mii, const MCTargetOptions &Options) 918 : MCTargetAsmParser(Options, sti), MII(mii), InstInfo(nullptr), 919 Code16GCC(false) { 920 921 // Initialize the set of available features. 922 setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits())); 923 Instrumentation.reset( 924 CreateX86AsmInstrumentation(Options, Parser.getContext(), STI)); 925 } 926 927 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override; 928 929 void SetFrameRegister(unsigned RegNo) override; 930 931 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name, 932 SMLoc NameLoc, OperandVector &Operands) override; 933 934 bool ParseDirective(AsmToken DirectiveID) override; 935 }; 936 } // end anonymous namespace 937 938 /// @name Auto-generated Match Functions 939 /// { 940 941 static unsigned MatchRegisterName(StringRef Name); 942 943 /// } 944 945 static bool CheckBaseRegAndIndexRegAndScale(unsigned BaseReg, unsigned IndexReg, 946 unsigned Scale, StringRef &ErrMsg) { 947 // If we have both a base register and an index register make sure they are 948 // both 64-bit or 32-bit registers. 949 // To support VSIB, IndexReg can be 128-bit or 256-bit registers. 950 951 if ((BaseReg == X86::RIP && IndexReg != 0) || (IndexReg == X86::RIP)) { 952 ErrMsg = "invalid base+index expression"; 953 return true; 954 } 955 if (BaseReg != 0 && IndexReg != 0) { 956 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) && 957 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) || 958 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) && 959 IndexReg != X86::RIZ) { 960 ErrMsg = "base register is 64-bit, but index register is not"; 961 return true; 962 } 963 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) && 964 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) || 965 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) && 966 IndexReg != X86::EIZ){ 967 ErrMsg = "base register is 32-bit, but index register is not"; 968 return true; 969 } 970 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg)) { 971 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) || 972 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) { 973 ErrMsg = "base register is 16-bit, but index register is not"; 974 return true; 975 } 976 if (((BaseReg == X86::BX || BaseReg == X86::BP) && 977 IndexReg != X86::SI && IndexReg != X86::DI) || 978 ((BaseReg == X86::SI || BaseReg == X86::DI) && 979 IndexReg != X86::BX && IndexReg != X86::BP)) { 980 ErrMsg = "invalid 16-bit base/index register combination"; 981 return true; 982 } 983 } 984 } 985 return checkScale(Scale, ErrMsg); 986 } 987 988 bool X86AsmParser::ParseRegister(unsigned &RegNo, 989 SMLoc &StartLoc, SMLoc &EndLoc) { 990 MCAsmParser &Parser = getParser(); 991 RegNo = 0; 992 const AsmToken &PercentTok = Parser.getTok(); 993 StartLoc = PercentTok.getLoc(); 994 995 // If we encounter a %, ignore it. This code handles registers with and 996 // without the prefix, unprefixed registers can occur in cfi directives. 997 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent)) 998 Parser.Lex(); // Eat percent token. 999 1000 const AsmToken &Tok = Parser.getTok(); 1001 EndLoc = Tok.getEndLoc(); 1002 1003 if (Tok.isNot(AsmToken::Identifier)) { 1004 if (isParsingIntelSyntax()) return true; 1005 return Error(StartLoc, "invalid register name", 1006 SMRange(StartLoc, EndLoc)); 1007 } 1008 1009 RegNo = MatchRegisterName(Tok.getString()); 1010 1011 // If the match failed, try the register name as lowercase. 1012 if (RegNo == 0) 1013 RegNo = MatchRegisterName(Tok.getString().lower()); 1014 1015 // The "flags" register cannot be referenced directly. 1016 // Treat it as an identifier instead. 1017 if (isParsingInlineAsm() && isParsingIntelSyntax() && RegNo == X86::EFLAGS) 1018 RegNo = 0; 1019 1020 if (!is64BitMode()) { 1021 // FIXME: This should be done using Requires<Not64BitMode> and 1022 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also 1023 // checked. 1024 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a 1025 // REX prefix. 1026 if (RegNo == X86::RIZ || 1027 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) || 1028 X86II::isX86_64NonExtLowByteReg(RegNo) || 1029 X86II::isX86_64ExtendedReg(RegNo)) 1030 return Error(StartLoc, "register %" 1031 + Tok.getString() + " is only available in 64-bit mode", 1032 SMRange(StartLoc, EndLoc)); 1033 } else if (!getSTI().getFeatureBits()[X86::FeatureAVX512]) { 1034 if (X86II::is32ExtendedReg(RegNo)) 1035 return Error(StartLoc, "register %" 1036 + Tok.getString() + " is only available with AVX512", 1037 SMRange(StartLoc, EndLoc)); 1038 } 1039 1040 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens. 1041 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) { 1042 RegNo = X86::ST0; 1043 Parser.Lex(); // Eat 'st' 1044 1045 // Check to see if we have '(4)' after %st. 1046 if (getLexer().isNot(AsmToken::LParen)) 1047 return false; 1048 // Lex the paren. 1049 getParser().Lex(); 1050 1051 const AsmToken &IntTok = Parser.getTok(); 1052 if (IntTok.isNot(AsmToken::Integer)) 1053 return Error(IntTok.getLoc(), "expected stack index"); 1054 switch (IntTok.getIntVal()) { 1055 case 0: RegNo = X86::ST0; break; 1056 case 1: RegNo = X86::ST1; break; 1057 case 2: RegNo = X86::ST2; break; 1058 case 3: RegNo = X86::ST3; break; 1059 case 4: RegNo = X86::ST4; break; 1060 case 5: RegNo = X86::ST5; break; 1061 case 6: RegNo = X86::ST6; break; 1062 case 7: RegNo = X86::ST7; break; 1063 default: return Error(IntTok.getLoc(), "invalid stack index"); 1064 } 1065 1066 if (getParser().Lex().isNot(AsmToken::RParen)) 1067 return Error(Parser.getTok().getLoc(), "expected ')'"); 1068 1069 EndLoc = Parser.getTok().getEndLoc(); 1070 Parser.Lex(); // Eat ')' 1071 return false; 1072 } 1073 1074 EndLoc = Parser.getTok().getEndLoc(); 1075 1076 // If this is "db[0-7]", match it as an alias 1077 // for dr[0-7]. 1078 if (RegNo == 0 && Tok.getString().size() == 3 && 1079 Tok.getString().startswith("db")) { 1080 switch (Tok.getString()[2]) { 1081 case '0': RegNo = X86::DR0; break; 1082 case '1': RegNo = X86::DR1; break; 1083 case '2': RegNo = X86::DR2; break; 1084 case '3': RegNo = X86::DR3; break; 1085 case '4': RegNo = X86::DR4; break; 1086 case '5': RegNo = X86::DR5; break; 1087 case '6': RegNo = X86::DR6; break; 1088 case '7': RegNo = X86::DR7; break; 1089 } 1090 1091 if (RegNo != 0) { 1092 EndLoc = Parser.getTok().getEndLoc(); 1093 Parser.Lex(); // Eat it. 1094 return false; 1095 } 1096 } 1097 1098 if (RegNo == 0) { 1099 if (isParsingIntelSyntax()) return true; 1100 return Error(StartLoc, "invalid register name", 1101 SMRange(StartLoc, EndLoc)); 1102 } 1103 1104 Parser.Lex(); // Eat identifier token. 1105 return false; 1106 } 1107 1108 void X86AsmParser::SetFrameRegister(unsigned RegNo) { 1109 Instrumentation->SetInitialFrameRegister(RegNo); 1110 } 1111 1112 std::unique_ptr<X86Operand> X86AsmParser::DefaultMemSIOperand(SMLoc Loc) { 1113 bool Parse32 = is32BitMode() || Code16GCC; 1114 unsigned Basereg = is64BitMode() ? X86::RSI : (Parse32 ? X86::ESI : X86::SI); 1115 const MCExpr *Disp = MCConstantExpr::create(0, getContext()); 1116 return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp, 1117 /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1, 1118 Loc, Loc, 0); 1119 } 1120 1121 std::unique_ptr<X86Operand> X86AsmParser::DefaultMemDIOperand(SMLoc Loc) { 1122 bool Parse32 = is32BitMode() || Code16GCC; 1123 unsigned Basereg = is64BitMode() ? X86::RDI : (Parse32 ? X86::EDI : X86::DI); 1124 const MCExpr *Disp = MCConstantExpr::create(0, getContext()); 1125 return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp, 1126 /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1, 1127 Loc, Loc, 0); 1128 } 1129 1130 bool X86AsmParser::IsSIReg(unsigned Reg) { 1131 switch (Reg) { 1132 default: llvm_unreachable("Only (R|E)SI and (R|E)DI are expected!"); 1133 case X86::RSI: 1134 case X86::ESI: 1135 case X86::SI: 1136 return true; 1137 case X86::RDI: 1138 case X86::EDI: 1139 case X86::DI: 1140 return false; 1141 } 1142 } 1143 1144 unsigned X86AsmParser::GetSIDIForRegClass(unsigned RegClassID, unsigned Reg, 1145 bool IsSIReg) { 1146 switch (RegClassID) { 1147 default: llvm_unreachable("Unexpected register class"); 1148 case X86::GR64RegClassID: 1149 return IsSIReg ? X86::RSI : X86::RDI; 1150 case X86::GR32RegClassID: 1151 return IsSIReg ? X86::ESI : X86::EDI; 1152 case X86::GR16RegClassID: 1153 return IsSIReg ? X86::SI : X86::DI; 1154 } 1155 } 1156 1157 void X86AsmParser::AddDefaultSrcDestOperands( 1158 OperandVector& Operands, std::unique_ptr<llvm::MCParsedAsmOperand> &&Src, 1159 std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst) { 1160 if (isParsingIntelSyntax()) { 1161 Operands.push_back(std::move(Dst)); 1162 Operands.push_back(std::move(Src)); 1163 } 1164 else { 1165 Operands.push_back(std::move(Src)); 1166 Operands.push_back(std::move(Dst)); 1167 } 1168 } 1169 1170 bool X86AsmParser::VerifyAndAdjustOperands(OperandVector &OrigOperands, 1171 OperandVector &FinalOperands) { 1172 1173 if (OrigOperands.size() > 1) { 1174 // Check if sizes match, OrigOperands also contains the instruction name 1175 assert(OrigOperands.size() == FinalOperands.size() + 1 && 1176 "Operand size mismatch"); 1177 1178 SmallVector<std::pair<SMLoc, std::string>, 2> Warnings; 1179 // Verify types match 1180 int RegClassID = -1; 1181 for (unsigned int i = 0; i < FinalOperands.size(); ++i) { 1182 X86Operand &OrigOp = static_cast<X86Operand &>(*OrigOperands[i + 1]); 1183 X86Operand &FinalOp = static_cast<X86Operand &>(*FinalOperands[i]); 1184 1185 if (FinalOp.isReg() && 1186 (!OrigOp.isReg() || FinalOp.getReg() != OrigOp.getReg())) 1187 // Return false and let a normal complaint about bogus operands happen 1188 return false; 1189 1190 if (FinalOp.isMem()) { 1191 1192 if (!OrigOp.isMem()) 1193 // Return false and let a normal complaint about bogus operands happen 1194 return false; 1195 1196 unsigned OrigReg = OrigOp.Mem.BaseReg; 1197 unsigned FinalReg = FinalOp.Mem.BaseReg; 1198 1199 // If we've already encounterd a register class, make sure all register 1200 // bases are of the same register class 1201 if (RegClassID != -1 && 1202 !X86MCRegisterClasses[RegClassID].contains(OrigReg)) { 1203 return Error(OrigOp.getStartLoc(), 1204 "mismatching source and destination index registers"); 1205 } 1206 1207 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(OrigReg)) 1208 RegClassID = X86::GR64RegClassID; 1209 else if (X86MCRegisterClasses[X86::GR32RegClassID].contains(OrigReg)) 1210 RegClassID = X86::GR32RegClassID; 1211 else if (X86MCRegisterClasses[X86::GR16RegClassID].contains(OrigReg)) 1212 RegClassID = X86::GR16RegClassID; 1213 else 1214 // Unexpected register class type 1215 // Return false and let a normal complaint about bogus operands happen 1216 return false; 1217 1218 bool IsSI = IsSIReg(FinalReg); 1219 FinalReg = GetSIDIForRegClass(RegClassID, FinalReg, IsSI); 1220 1221 if (FinalReg != OrigReg) { 1222 std::string RegName = IsSI ? "ES:(R|E)SI" : "ES:(R|E)DI"; 1223 Warnings.push_back(std::make_pair( 1224 OrigOp.getStartLoc(), 1225 "memory operand is only for determining the size, " + RegName + 1226 " will be used for the location")); 1227 } 1228 1229 FinalOp.Mem.Size = OrigOp.Mem.Size; 1230 FinalOp.Mem.SegReg = OrigOp.Mem.SegReg; 1231 FinalOp.Mem.BaseReg = FinalReg; 1232 } 1233 } 1234 1235 // Produce warnings only if all the operands passed the adjustment - prevent 1236 // legal cases like "movsd (%rax), %xmm0" mistakenly produce warnings 1237 for (auto &WarningMsg : Warnings) { 1238 Warning(WarningMsg.first, WarningMsg.second); 1239 } 1240 1241 // Remove old operands 1242 for (unsigned int i = 0; i < FinalOperands.size(); ++i) 1243 OrigOperands.pop_back(); 1244 } 1245 // OrigOperands.append(FinalOperands.begin(), FinalOperands.end()); 1246 for (unsigned int i = 0; i < FinalOperands.size(); ++i) 1247 OrigOperands.push_back(std::move(FinalOperands[i])); 1248 1249 return false; 1250 } 1251 1252 std::unique_ptr<X86Operand> X86AsmParser::ParseOperand() { 1253 if (isParsingIntelSyntax()) 1254 return ParseIntelOperand(); 1255 return ParseATTOperand(); 1256 } 1257 1258 std::unique_ptr<X86Operand> X86AsmParser::CreateMemForInlineAsm( 1259 unsigned SegReg, const MCExpr *Disp, unsigned BaseReg, unsigned IndexReg, 1260 unsigned Scale, SMLoc Start, SMLoc End, unsigned Size, StringRef Identifier, 1261 const InlineAsmIdentifierInfo &Info) { 1262 // If we found a decl other than a VarDecl, then assume it is a FuncDecl or 1263 // some other label reference. 1264 if (isa<MCSymbolRefExpr>(Disp) && Info.OpDecl && !Info.IsVarDecl) { 1265 // Insert an explicit size if the user didn't have one. 1266 if (!Size) { 1267 Size = getPointerWidth(); 1268 InstInfo->AsmRewrites->emplace_back(AOK_SizeDirective, Start, 1269 /*Len=*/0, Size); 1270 } 1271 1272 // Create an absolute memory reference in order to match against 1273 // instructions taking a PC relative operand. 1274 return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End, Size, 1275 Identifier, Info.OpDecl); 1276 } 1277 1278 1279 // We either have a direct symbol reference, or an offset from a symbol. The 1280 // parser always puts the symbol on the LHS, so look there for size 1281 // calculation purposes. 1282 unsigned FrontendSize = 0; 1283 const MCBinaryExpr *BinOp = dyn_cast<MCBinaryExpr>(Disp); 1284 bool IsSymRef = 1285 isa<MCSymbolRefExpr>(BinOp ? BinOp->getLHS() : Disp); 1286 if (IsSymRef && !Size && Info.Type) 1287 FrontendSize = Info.Type * 8; // Size is in terms of bits in this context. 1288 1289 // When parsing inline assembly we set the base register to a non-zero value 1290 // if we don't know the actual value at this time. This is necessary to 1291 // get the matching correct in some cases. 1292 BaseReg = BaseReg ? BaseReg : 1; 1293 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg, 1294 IndexReg, Scale, Start, End, Size, Identifier, 1295 Info.OpDecl, FrontendSize); 1296 } 1297 1298 // Some binary bitwise operators have a named synonymous 1299 // Query a candidate string for being such a named operator 1300 // and if so - invoke the appropriate handler 1301 bool X86AsmParser::ParseIntelNamedOperator(StringRef Name, IntelExprStateMachine &SM) { 1302 // A named operator should be either lower or upper case, but not a mix 1303 if (Name.compare(Name.lower()) && Name.compare(Name.upper())) 1304 return false; 1305 if (Name.equals_lower("not")) 1306 SM.onNot(); 1307 else if (Name.equals_lower("or")) 1308 SM.onOr(); 1309 else if (Name.equals_lower("shl")) 1310 SM.onLShift(); 1311 else if (Name.equals_lower("shr")) 1312 SM.onRShift(); 1313 else if (Name.equals_lower("xor")) 1314 SM.onXor(); 1315 else if (Name.equals_lower("and")) 1316 SM.onAnd(); 1317 else if (Name.equals_lower("mod")) 1318 SM.onMod(); 1319 else 1320 return false; 1321 return true; 1322 } 1323 1324 bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) { 1325 MCAsmParser &Parser = getParser(); 1326 const AsmToken &Tok = Parser.getTok(); 1327 StringRef ErrMsg; 1328 1329 AsmToken::TokenKind PrevTK = AsmToken::Error; 1330 bool Done = false; 1331 while (!Done) { 1332 bool UpdateLocLex = true; 1333 AsmToken::TokenKind TK = getLexer().getKind(); 1334 1335 switch (TK) { 1336 default: 1337 if ((Done = SM.isValidEndState())) 1338 break; 1339 return Error(Tok.getLoc(), "unknown token in expression"); 1340 case AsmToken::EndOfStatement: 1341 Done = true; 1342 break; 1343 case AsmToken::Real: 1344 // DotOperator: [ebx].0 1345 UpdateLocLex = false; 1346 if (ParseIntelDotOperator(SM, End)) 1347 return true; 1348 break; 1349 case AsmToken::String: 1350 case AsmToken::Identifier: { 1351 // This could be a register or a symbolic displacement. 1352 unsigned TmpReg; 1353 const MCExpr *Val; 1354 SMLoc IdentLoc = Tok.getLoc(); 1355 StringRef Identifier = Tok.getString(); 1356 UpdateLocLex = false; 1357 if (TK != AsmToken::String && !ParseRegister(TmpReg, IdentLoc, End)) { 1358 if (SM.onRegister(TmpReg, ErrMsg)) 1359 return Error(Tok.getLoc(), ErrMsg); 1360 } else if (ParseIntelNamedOperator(Identifier, SM)) { 1361 UpdateLocLex = true; 1362 } else if (!isParsingInlineAsm()) { 1363 if (getParser().parsePrimaryExpr(Val, End)) 1364 return Error(Tok.getLoc(), "Unexpected identifier!"); 1365 if (auto *CE = dyn_cast<MCConstantExpr>(Val)) { 1366 if (SM.onInteger(CE->getValue(), ErrMsg)) 1367 return Error(IdentLoc, ErrMsg); 1368 } else if (SM.onIdentifierExpr(Val, Identifier, ErrMsg)) 1369 return Error(IdentLoc, ErrMsg); 1370 } else if (unsigned OpKind = IdentifyIntelInlineAsmOperator(Identifier)) { 1371 if (OpKind == IOK_OFFSET) 1372 return Error(IdentLoc, "Dealing OFFSET operator as part of" 1373 "a compound immediate expression is yet to be supported"); 1374 int64_t Val = ParseIntelInlineAsmOperator(OpKind); 1375 if (!Val) 1376 return true; 1377 if (SM.onInteger(Val, ErrMsg)) 1378 return Error(IdentLoc, ErrMsg); 1379 } else if (Identifier.count('.') && PrevTK == AsmToken::RBrac) { 1380 if (ParseIntelDotOperator(SM, End)) 1381 return true; 1382 } else if (ParseIntelInlineAsmIdentifier(Val, Identifier, 1383 SM.getIdentifierInfo(), 1384 /*Unevaluated=*/false, End)) { 1385 return true; 1386 } else if (SM.onIdentifierExpr(Val, Identifier, ErrMsg)) { 1387 return Error(IdentLoc, ErrMsg); 1388 } 1389 break; 1390 } 1391 case AsmToken::Integer: { 1392 // Look for 'b' or 'f' following an Integer as a directional label 1393 SMLoc Loc = getTok().getLoc(); 1394 int64_t IntVal = getTok().getIntVal(); 1395 End = consumeToken(); 1396 UpdateLocLex = false; 1397 if (getLexer().getKind() == AsmToken::Identifier) { 1398 StringRef IDVal = getTok().getString(); 1399 if (IDVal == "f" || IDVal == "b") { 1400 MCSymbol *Sym = 1401 getContext().getDirectionalLocalSymbol(IntVal, IDVal == "b"); 1402 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1403 const MCExpr *Val = 1404 MCSymbolRefExpr::create(Sym, Variant, getContext()); 1405 if (IDVal == "b" && Sym->isUndefined()) 1406 return Error(Loc, "invalid reference to undefined symbol"); 1407 StringRef Identifier = Sym->getName(); 1408 if (SM.onIdentifierExpr(Val, Identifier, ErrMsg)) 1409 return Error(Loc, ErrMsg); 1410 End = consumeToken(); 1411 } else { 1412 if (SM.onInteger(IntVal, ErrMsg)) 1413 return Error(Loc, ErrMsg); 1414 } 1415 } else { 1416 if (SM.onInteger(IntVal, ErrMsg)) 1417 return Error(Loc, ErrMsg); 1418 } 1419 break; 1420 } 1421 case AsmToken::Plus: 1422 if (SM.onPlus(ErrMsg)) 1423 return Error(getTok().getLoc(), ErrMsg); 1424 break; 1425 case AsmToken::Minus: 1426 if (SM.onMinus(ErrMsg)) 1427 return Error(getTok().getLoc(), ErrMsg); 1428 break; 1429 case AsmToken::Tilde: SM.onNot(); break; 1430 case AsmToken::Star: SM.onStar(); break; 1431 case AsmToken::Slash: SM.onDivide(); break; 1432 case AsmToken::Pipe: SM.onOr(); break; 1433 case AsmToken::Caret: SM.onXor(); break; 1434 case AsmToken::Amp: SM.onAnd(); break; 1435 case AsmToken::LessLess: 1436 SM.onLShift(); break; 1437 case AsmToken::GreaterGreater: 1438 SM.onRShift(); break; 1439 case AsmToken::LBrac: 1440 if (SM.onLBrac()) 1441 return Error(Tok.getLoc(), "unexpected bracket encountered"); 1442 break; 1443 case AsmToken::RBrac: 1444 if (SM.onRBrac()) 1445 return Error(Tok.getLoc(), "unexpected bracket encountered"); 1446 break; 1447 case AsmToken::LParen: SM.onLParen(); break; 1448 case AsmToken::RParen: SM.onRParen(); break; 1449 } 1450 if (SM.hadError()) 1451 return Error(Tok.getLoc(), "unknown token in expression"); 1452 1453 if (!Done && UpdateLocLex) 1454 End = consumeToken(); 1455 1456 PrevTK = TK; 1457 } 1458 return false; 1459 } 1460 1461 void X86AsmParser::RewriteIntelExpression(IntelExprStateMachine &SM, 1462 SMLoc Start, SMLoc End) { 1463 SMLoc Loc = Start; 1464 unsigned ExprLen = End.getPointer() - Start.getPointer(); 1465 // Skip everything before a symbol displacement (if we have one) 1466 if (SM.getSym()) { 1467 StringRef SymName = SM.getSymName(); 1468 if (unsigned Len = SymName.data() - Start.getPointer()) 1469 InstInfo->AsmRewrites->emplace_back(AOK_Skip, Start, Len); 1470 Loc = SMLoc::getFromPointer(SymName.data() + SymName.size()); 1471 ExprLen = End.getPointer() - (SymName.data() + SymName.size()); 1472 // If we have only a symbol than there's no need for complex rewrite, 1473 // simply skip everything after it 1474 if (!(SM.getBaseReg() || SM.getIndexReg() || SM.getImm())) { 1475 if (ExprLen) 1476 InstInfo->AsmRewrites->emplace_back(AOK_Skip, Loc, ExprLen); 1477 return; 1478 } 1479 } 1480 // Build an Intel Expression rewrite 1481 StringRef BaseRegStr; 1482 StringRef IndexRegStr; 1483 if (SM.getBaseReg()) 1484 BaseRegStr = X86IntelInstPrinter::getRegisterName(SM.getBaseReg()); 1485 if (SM.getIndexReg()) 1486 IndexRegStr = X86IntelInstPrinter::getRegisterName(SM.getIndexReg()); 1487 // Emit it 1488 IntelExpr Expr(BaseRegStr, IndexRegStr, SM.getScale(), SM.getImm(), SM.isMemExpr()); 1489 InstInfo->AsmRewrites->emplace_back(Loc, ExprLen, Expr); 1490 } 1491 1492 // Inline assembly may use variable names with namespace alias qualifiers. 1493 bool X86AsmParser::ParseIntelInlineAsmIdentifier(const MCExpr *&Val, 1494 StringRef &Identifier, 1495 InlineAsmIdentifierInfo &Info, 1496 bool IsUnevaluatedOperand, 1497 SMLoc &End) { 1498 MCAsmParser &Parser = getParser(); 1499 assert(isParsingInlineAsm() && "Expected to be parsing inline assembly."); 1500 Val = nullptr; 1501 1502 StringRef LineBuf(Identifier.data()); 1503 void *Result = 1504 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand); 1505 1506 const AsmToken &Tok = Parser.getTok(); 1507 SMLoc Loc = Tok.getLoc(); 1508 1509 // Advance the token stream until the end of the current token is 1510 // after the end of what the frontend claimed. 1511 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size(); 1512 do { 1513 End = Tok.getEndLoc(); 1514 getLexer().Lex(); 1515 } while (End.getPointer() < EndPtr); 1516 Identifier = LineBuf; 1517 1518 // The frontend should end parsing on an assembler token boundary, unless it 1519 // failed parsing. 1520 assert((End.getPointer() == EndPtr || !Result) && 1521 "frontend claimed part of a token?"); 1522 1523 // If the identifier lookup was unsuccessful, assume that we are dealing with 1524 // a label. 1525 if (!Result) { 1526 StringRef InternalName = 1527 SemaCallback->LookupInlineAsmLabel(Identifier, getSourceManager(), 1528 Loc, false); 1529 assert(InternalName.size() && "We should have an internal name here."); 1530 // Push a rewrite for replacing the identifier name with the internal name. 1531 InstInfo->AsmRewrites->emplace_back(AOK_Label, Loc, Identifier.size(), 1532 InternalName); 1533 } 1534 1535 // Create the symbol reference. 1536 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier); 1537 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1538 Val = MCSymbolRefExpr::create(Sym, Variant, getParser().getContext()); 1539 return false; 1540 } 1541 1542 //ParseRoundingModeOp - Parse AVX-512 rounding mode operand 1543 std::unique_ptr<X86Operand> 1544 X86AsmParser::ParseRoundingModeOp(SMLoc Start, SMLoc End) { 1545 MCAsmParser &Parser = getParser(); 1546 const AsmToken &Tok = Parser.getTok(); 1547 // Eat "{" and mark the current place. 1548 const SMLoc consumedToken = consumeToken(); 1549 if (Tok.getIdentifier().startswith("r")){ 1550 int rndMode = StringSwitch<int>(Tok.getIdentifier()) 1551 .Case("rn", X86::STATIC_ROUNDING::TO_NEAREST_INT) 1552 .Case("rd", X86::STATIC_ROUNDING::TO_NEG_INF) 1553 .Case("ru", X86::STATIC_ROUNDING::TO_POS_INF) 1554 .Case("rz", X86::STATIC_ROUNDING::TO_ZERO) 1555 .Default(-1); 1556 if (-1 == rndMode) 1557 return ErrorOperand(Tok.getLoc(), "Invalid rounding mode."); 1558 Parser.Lex(); // Eat "r*" of r*-sae 1559 if (!getLexer().is(AsmToken::Minus)) 1560 return ErrorOperand(Tok.getLoc(), "Expected - at this point"); 1561 Parser.Lex(); // Eat "-" 1562 Parser.Lex(); // Eat the sae 1563 if (!getLexer().is(AsmToken::RCurly)) 1564 return ErrorOperand(Tok.getLoc(), "Expected } at this point"); 1565 Parser.Lex(); // Eat "}" 1566 const MCExpr *RndModeOp = 1567 MCConstantExpr::create(rndMode, Parser.getContext()); 1568 return X86Operand::CreateImm(RndModeOp, Start, End); 1569 } 1570 if(Tok.getIdentifier().equals("sae")){ 1571 Parser.Lex(); // Eat the sae 1572 if (!getLexer().is(AsmToken::RCurly)) 1573 return ErrorOperand(Tok.getLoc(), "Expected } at this point"); 1574 Parser.Lex(); // Eat "}" 1575 return X86Operand::CreateToken("{sae}", consumedToken); 1576 } 1577 return ErrorOperand(Tok.getLoc(), "unknown token in expression"); 1578 } 1579 1580 /// Parse the '.' operator. 1581 bool X86AsmParser::ParseIntelDotOperator(IntelExprStateMachine &SM, SMLoc &End) { 1582 const AsmToken &Tok = getTok(); 1583 unsigned Offset; 1584 1585 // Drop the optional '.'. 1586 StringRef DotDispStr = Tok.getString(); 1587 if (DotDispStr.startswith(".")) 1588 DotDispStr = DotDispStr.drop_front(1); 1589 1590 // .Imm gets lexed as a real. 1591 if (Tok.is(AsmToken::Real)) { 1592 APInt DotDisp; 1593 DotDispStr.getAsInteger(10, DotDisp); 1594 Offset = DotDisp.getZExtValue(); 1595 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) { 1596 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.'); 1597 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second, 1598 Offset)) 1599 return Error(Tok.getLoc(), "Unable to lookup field reference!"); 1600 } else 1601 return Error(Tok.getLoc(), "Unexpected token type!"); 1602 1603 // Eat the DotExpression and update End 1604 End = SMLoc::getFromPointer(DotDispStr.data()); 1605 const char *DotExprEndLoc = DotDispStr.data() + DotDispStr.size(); 1606 while (Tok.getLoc().getPointer() < DotExprEndLoc) 1607 Lex(); 1608 SM.addImm(Offset); 1609 return false; 1610 } 1611 1612 /// Parse the 'offset' operator. This operator is used to specify the 1613 /// location rather then the content of a variable. 1614 std::unique_ptr<X86Operand> X86AsmParser::ParseIntelOffsetOfOperator() { 1615 MCAsmParser &Parser = getParser(); 1616 const AsmToken &Tok = Parser.getTok(); 1617 SMLoc OffsetOfLoc = Tok.getLoc(); 1618 Parser.Lex(); // Eat offset. 1619 1620 const MCExpr *Val; 1621 InlineAsmIdentifierInfo Info; 1622 SMLoc Start = Tok.getLoc(), End; 1623 StringRef Identifier = Tok.getString(); 1624 if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info, 1625 /*Unevaluated=*/false, End)) 1626 return nullptr; 1627 1628 // Don't emit the offset operator. 1629 InstInfo->AsmRewrites->emplace_back(AOK_Skip, OffsetOfLoc, 7); 1630 1631 // The offset operator will have an 'r' constraint, thus we need to create 1632 // register operand to ensure proper matching. Just pick a GPR based on 1633 // the size of a pointer. 1634 bool Parse32 = is32BitMode() || Code16GCC; 1635 unsigned RegNo = is64BitMode() ? X86::RBX : (Parse32 ? X86::EBX : X86::BX); 1636 1637 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true, 1638 OffsetOfLoc, Identifier, Info.OpDecl); 1639 } 1640 1641 // Query a candidate string for being an Intel assembly operator 1642 // Report back its kind, or IOK_INVALID if does not evaluated as a known one 1643 unsigned X86AsmParser::IdentifyIntelInlineAsmOperator(StringRef Name) { 1644 return StringSwitch<unsigned>(Name) 1645 .Cases("TYPE","type",IOK_TYPE) 1646 .Cases("SIZE","size",IOK_SIZE) 1647 .Cases("LENGTH","length",IOK_LENGTH) 1648 .Cases("OFFSET","offset",IOK_OFFSET) 1649 .Default(IOK_INVALID); 1650 } 1651 1652 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator 1653 /// returns the number of elements in an array. It returns the value 1 for 1654 /// non-array variables. The SIZE operator returns the size of a C or C++ 1655 /// variable. A variable's size is the product of its LENGTH and TYPE. The 1656 /// TYPE operator returns the size of a C or C++ type or variable. If the 1657 /// variable is an array, TYPE returns the size of a single element. 1658 unsigned X86AsmParser::ParseIntelInlineAsmOperator(unsigned OpKind) { 1659 MCAsmParser &Parser = getParser(); 1660 const AsmToken &Tok = Parser.getTok(); 1661 Parser.Lex(); // Eat operator. 1662 1663 const MCExpr *Val = nullptr; 1664 InlineAsmIdentifierInfo Info; 1665 SMLoc Start = Tok.getLoc(), End; 1666 StringRef Identifier = Tok.getString(); 1667 if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info, 1668 /*Unevaluated=*/true, End)) 1669 return 0; 1670 1671 if (!Info.OpDecl) { 1672 Error(Start, "unable to lookup expression"); 1673 return 0; 1674 } 1675 1676 unsigned CVal = 0; 1677 switch(OpKind) { 1678 default: llvm_unreachable("Unexpected operand kind!"); 1679 case IOK_LENGTH: CVal = Info.Length; break; 1680 case IOK_SIZE: CVal = Info.Size; break; 1681 case IOK_TYPE: CVal = Info.Type; break; 1682 } 1683 1684 return CVal; 1685 } 1686 1687 bool X86AsmParser::ParseIntelMemoryOperandSize(unsigned &Size) { 1688 Size = StringSwitch<unsigned>(getTok().getString()) 1689 .Cases("BYTE", "byte", 8) 1690 .Cases("WORD", "word", 16) 1691 .Cases("DWORD", "dword", 32) 1692 .Cases("FWORD", "fword", 48) 1693 .Cases("QWORD", "qword", 64) 1694 .Cases("MMWORD","mmword", 64) 1695 .Cases("XWORD", "xword", 80) 1696 .Cases("TBYTE", "tbyte", 80) 1697 .Cases("XMMWORD", "xmmword", 128) 1698 .Cases("YMMWORD", "ymmword", 256) 1699 .Cases("ZMMWORD", "zmmword", 512) 1700 .Cases("OPAQUE", "opaque", -1U) // needs to be non-zero, but doesn't matter 1701 .Default(0); 1702 if (Size) { 1703 const AsmToken &Tok = Lex(); // Eat operand size (e.g., byte, word). 1704 if (!(Tok.getString().equals("PTR") || Tok.getString().equals("ptr"))) 1705 return Error(Tok.getLoc(), "Expected 'PTR' or 'ptr' token!"); 1706 Lex(); // Eat ptr. 1707 } 1708 return false; 1709 } 1710 1711 std::unique_ptr<X86Operand> X86AsmParser::ParseIntelOperand() { 1712 MCAsmParser &Parser = getParser(); 1713 const AsmToken &Tok = Parser.getTok(); 1714 SMLoc Start, End; 1715 1716 // FIXME: Offset operator 1717 // Should be handled as part of immediate expression, as other operators 1718 // Currently, only supported as a stand-alone operand 1719 if (isParsingInlineAsm()) 1720 if (IdentifyIntelInlineAsmOperator(Tok.getString()) == IOK_OFFSET) 1721 return ParseIntelOffsetOfOperator(); 1722 1723 // Parse optional Size directive. 1724 unsigned Size; 1725 if (ParseIntelMemoryOperandSize(Size)) 1726 return nullptr; 1727 bool PtrInOperand = bool(Size); 1728 1729 Start = Tok.getLoc(); 1730 1731 // Rounding mode operand. 1732 if (getSTI().getFeatureBits()[X86::FeatureAVX512] && 1733 getLexer().is(AsmToken::LCurly)) 1734 return ParseRoundingModeOp(Start, End); 1735 1736 // Register operand. 1737 unsigned RegNo = 0; 1738 if (Tok.is(AsmToken::Identifier) && !ParseRegister(RegNo, Start, End)) { 1739 if (RegNo == X86::RIP) 1740 return ErrorOperand(Start, "rip can only be used as a base register"); 1741 // A Register followed by ':' is considered a segment override 1742 if (Tok.isNot(AsmToken::Colon)) 1743 return !PtrInOperand ? X86Operand::CreateReg(RegNo, Start, End) : 1744 ErrorOperand(Start, "expected memory operand after 'ptr', " 1745 "found register operand instead"); 1746 // An alleged segment override. check if we have a valid segment register 1747 if (!X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo)) 1748 return ErrorOperand(Start, "invalid segment register"); 1749 // Eat ':' and update Start location 1750 Start = Lex().getLoc(); 1751 } 1752 1753 // Immediates and Memory 1754 IntelExprStateMachine SM; 1755 if (ParseIntelExpression(SM, End)) 1756 return nullptr; 1757 1758 if (isParsingInlineAsm()) 1759 RewriteIntelExpression(SM, Start, Tok.getLoc()); 1760 1761 int64_t Imm = SM.getImm(); 1762 const MCExpr *Disp = SM.getSym(); 1763 const MCExpr *ImmDisp = MCConstantExpr::create(Imm, getContext()); 1764 if (Disp && Imm) 1765 Disp = MCBinaryExpr::createAdd(Disp, ImmDisp, getContext()); 1766 if (!Disp) 1767 Disp = ImmDisp; 1768 1769 // RegNo != 0 specifies a valid segment register, 1770 // and we are parsing a segment override 1771 if (!SM.isMemExpr() && !RegNo) 1772 return X86Operand::CreateImm(Disp, Start, End); 1773 1774 StringRef ErrMsg; 1775 unsigned BaseReg = SM.getBaseReg(); 1776 unsigned IndexReg = SM.getIndexReg(); 1777 unsigned Scale = SM.getScale(); 1778 1779 if ((BaseReg || IndexReg) && 1780 CheckBaseRegAndIndexRegAndScale(BaseReg, IndexReg, Scale, ErrMsg)) 1781 return ErrorOperand(Start, ErrMsg); 1782 if (isParsingInlineAsm()) 1783 return CreateMemForInlineAsm(RegNo, Disp, BaseReg, IndexReg, 1784 Scale, Start, End, Size, SM.getSymName(), 1785 SM.getIdentifierInfo()); 1786 if (!(BaseReg || IndexReg || RegNo)) 1787 return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End, Size); 1788 return X86Operand::CreateMem(getPointerWidth(), RegNo, Disp, 1789 BaseReg, IndexReg, Scale, Start, End, Size); 1790 } 1791 1792 std::unique_ptr<X86Operand> X86AsmParser::ParseATTOperand() { 1793 MCAsmParser &Parser = getParser(); 1794 switch (getLexer().getKind()) { 1795 default: 1796 // Parse a memory operand with no segment register. 1797 return ParseMemOperand(0, Parser.getTok().getLoc()); 1798 case AsmToken::Percent: { 1799 // Read the register. 1800 unsigned RegNo; 1801 SMLoc Start, End; 1802 if (ParseRegister(RegNo, Start, End)) return nullptr; 1803 if (RegNo == X86::EIZ || RegNo == X86::RIZ) { 1804 Error(Start, "%eiz and %riz can only be used as index registers", 1805 SMRange(Start, End)); 1806 return nullptr; 1807 } 1808 if (RegNo == X86::RIP) { 1809 Error(Start, "%rip can only be used as a base register", 1810 SMRange(Start, End)); 1811 return nullptr; 1812 } 1813 1814 // If this is a segment register followed by a ':', then this is the start 1815 // of a memory reference, otherwise this is a normal register reference. 1816 if (getLexer().isNot(AsmToken::Colon)) 1817 return X86Operand::CreateReg(RegNo, Start, End); 1818 1819 if (!X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo)) 1820 return ErrorOperand(Start, "invalid segment register"); 1821 1822 getParser().Lex(); // Eat the colon. 1823 return ParseMemOperand(RegNo, Start); 1824 } 1825 case AsmToken::Dollar: { 1826 // $42 -> immediate. 1827 SMLoc Start = Parser.getTok().getLoc(), End; 1828 Parser.Lex(); 1829 const MCExpr *Val; 1830 if (getParser().parseExpression(Val, End)) 1831 return nullptr; 1832 return X86Operand::CreateImm(Val, Start, End); 1833 } 1834 case AsmToken::LCurly:{ 1835 SMLoc Start = Parser.getTok().getLoc(), End; 1836 if (getSTI().getFeatureBits()[X86::FeatureAVX512]) 1837 return ParseRoundingModeOp(Start, End); 1838 return ErrorOperand(Start, "Unexpected '{' in expression"); 1839 } 1840 } 1841 } 1842 1843 // true on failure, false otherwise 1844 // If no {z} mark was found - Parser doesn't advance 1845 bool X86AsmParser::ParseZ(std::unique_ptr<X86Operand> &Z, 1846 const SMLoc &StartLoc) { 1847 MCAsmParser &Parser = getParser(); 1848 // Assuming we are just pass the '{' mark, quering the next token 1849 // Searched for {z}, but none was found. Return false, as no parsing error was 1850 // encountered 1851 if (!(getLexer().is(AsmToken::Identifier) && 1852 (getLexer().getTok().getIdentifier() == "z"))) 1853 return false; 1854 Parser.Lex(); // Eat z 1855 // Query and eat the '}' mark 1856 if (!getLexer().is(AsmToken::RCurly)) 1857 return Error(getLexer().getLoc(), "Expected } at this point"); 1858 Parser.Lex(); // Eat '}' 1859 // Assign Z with the {z} mark opernad 1860 Z = X86Operand::CreateToken("{z}", StartLoc); 1861 return false; 1862 } 1863 1864 // true on failure, false otherwise 1865 bool X86AsmParser::HandleAVX512Operand(OperandVector &Operands, 1866 const MCParsedAsmOperand &Op) { 1867 MCAsmParser &Parser = getParser(); 1868 if(getSTI().getFeatureBits()[X86::FeatureAVX512]) { 1869 if (getLexer().is(AsmToken::LCurly)) { 1870 // Eat "{" and mark the current place. 1871 const SMLoc consumedToken = consumeToken(); 1872 // Distinguish {1to<NUM>} from {%k<NUM>}. 1873 if(getLexer().is(AsmToken::Integer)) { 1874 // Parse memory broadcasting ({1to<NUM>}). 1875 if (getLexer().getTok().getIntVal() != 1) 1876 return TokError("Expected 1to<NUM> at this point"); 1877 Parser.Lex(); // Eat "1" of 1to8 1878 if (!getLexer().is(AsmToken::Identifier) || 1879 !getLexer().getTok().getIdentifier().startswith("to")) 1880 return TokError("Expected 1to<NUM> at this point"); 1881 // Recognize only reasonable suffixes. 1882 const char *BroadcastPrimitive = 1883 StringSwitch<const char*>(getLexer().getTok().getIdentifier()) 1884 .Case("to2", "{1to2}") 1885 .Case("to4", "{1to4}") 1886 .Case("to8", "{1to8}") 1887 .Case("to16", "{1to16}") 1888 .Default(nullptr); 1889 if (!BroadcastPrimitive) 1890 return TokError("Invalid memory broadcast primitive."); 1891 Parser.Lex(); // Eat "toN" of 1toN 1892 if (!getLexer().is(AsmToken::RCurly)) 1893 return TokError("Expected } at this point"); 1894 Parser.Lex(); // Eat "}" 1895 Operands.push_back(X86Operand::CreateToken(BroadcastPrimitive, 1896 consumedToken)); 1897 // No AVX512 specific primitives can pass 1898 // after memory broadcasting, so return. 1899 return false; 1900 } else { 1901 // Parse either {k}{z}, {z}{k}, {k} or {z} 1902 // last one have no meaning, but GCC accepts it 1903 // Currently, we're just pass a '{' mark 1904 std::unique_ptr<X86Operand> Z; 1905 if (ParseZ(Z, consumedToken)) 1906 return true; 1907 // Reaching here means that parsing of the allegadly '{z}' mark yielded 1908 // no errors. 1909 // Query for the need of further parsing for a {%k<NUM>} mark 1910 if (!Z || getLexer().is(AsmToken::LCurly)) { 1911 SMLoc StartLoc = Z ? consumeToken() : consumedToken; 1912 // Parse an op-mask register mark ({%k<NUM>}), which is now to be 1913 // expected 1914 unsigned RegNo; 1915 SMLoc RegLoc; 1916 if (!ParseRegister(RegNo, RegLoc, StartLoc) && 1917 X86MCRegisterClasses[X86::VK1RegClassID].contains(RegNo)) { 1918 if (RegNo == X86::K0) 1919 return Error(RegLoc, "Register k0 can't be used as write mask"); 1920 if (!getLexer().is(AsmToken::RCurly)) 1921 return Error(getLexer().getLoc(), "Expected } at this point"); 1922 Operands.push_back(X86Operand::CreateToken("{", StartLoc)); 1923 Operands.push_back( 1924 X86Operand::CreateReg(RegNo, StartLoc, StartLoc)); 1925 Operands.push_back(X86Operand::CreateToken("}", consumeToken())); 1926 } else 1927 return Error(getLexer().getLoc(), 1928 "Expected an op-mask register at this point"); 1929 // {%k<NUM>} mark is found, inquire for {z} 1930 if (getLexer().is(AsmToken::LCurly) && !Z) { 1931 // Have we've found a parsing error, or found no (expected) {z} mark 1932 // - report an error 1933 if (ParseZ(Z, consumeToken()) || !Z) 1934 return Error(getLexer().getLoc(), 1935 "Expected a {z} mark at this point"); 1936 1937 } 1938 // '{z}' on its own is meaningless, hence should be ignored. 1939 // on the contrary - have it been accompanied by a K register, 1940 // allow it. 1941 if (Z) 1942 Operands.push_back(std::move(Z)); 1943 } 1944 } 1945 } 1946 } 1947 return false; 1948 } 1949 1950 /// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix 1951 /// has already been parsed if present. 1952 std::unique_ptr<X86Operand> X86AsmParser::ParseMemOperand(unsigned SegReg, 1953 SMLoc MemStart) { 1954 1955 MCAsmParser &Parser = getParser(); 1956 // We have to disambiguate a parenthesized expression "(4+5)" from the start 1957 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The 1958 // only way to do this without lookahead is to eat the '(' and see what is 1959 // after it. 1960 const MCExpr *Disp = MCConstantExpr::create(0, getParser().getContext()); 1961 if (getLexer().isNot(AsmToken::LParen)) { 1962 SMLoc ExprEnd; 1963 if (getParser().parseExpression(Disp, ExprEnd)) return nullptr; 1964 1965 // After parsing the base expression we could either have a parenthesized 1966 // memory address or not. If not, return now. If so, eat the (. 1967 if (getLexer().isNot(AsmToken::LParen)) { 1968 // Unless we have a segment register, treat this as an immediate. 1969 if (SegReg == 0) 1970 return X86Operand::CreateMem(getPointerWidth(), Disp, MemStart, ExprEnd); 1971 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, 0, 0, 1, 1972 MemStart, ExprEnd); 1973 } 1974 1975 // Eat the '('. 1976 Parser.Lex(); 1977 } else { 1978 // Okay, we have a '('. We don't know if this is an expression or not, but 1979 // so we have to eat the ( to see beyond it. 1980 SMLoc LParenLoc = Parser.getTok().getLoc(); 1981 Parser.Lex(); // Eat the '('. 1982 1983 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) { 1984 // Nothing to do here, fall into the code below with the '(' part of the 1985 // memory operand consumed. 1986 } else { 1987 SMLoc ExprEnd; 1988 getLexer().UnLex(AsmToken(AsmToken::LParen, "(")); 1989 1990 // It must be either an parenthesized expression, or an expression that 1991 // begins from a parenthesized expression, parse it now. Example: (1+2) or 1992 // (1+2)+3 1993 if (getParser().parseExpression(Disp, ExprEnd)) 1994 return nullptr; 1995 1996 // After parsing the base expression we could either have a parenthesized 1997 // memory address or not. If not, return now. If so, eat the (. 1998 if (getLexer().isNot(AsmToken::LParen)) { 1999 // Unless we have a segment register, treat this as an immediate. 2000 if (SegReg == 0) 2001 return X86Operand::CreateMem(getPointerWidth(), Disp, LParenLoc, 2002 ExprEnd); 2003 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, 0, 0, 1, 2004 MemStart, ExprEnd); 2005 } 2006 2007 // Eat the '('. 2008 Parser.Lex(); 2009 } 2010 } 2011 2012 // If we reached here, then we just ate the ( of the memory operand. Process 2013 // the rest of the memory operand. 2014 unsigned BaseReg = 0, IndexReg = 0, Scale = 1; 2015 SMLoc IndexLoc, BaseLoc; 2016 2017 if (getLexer().is(AsmToken::Percent)) { 2018 SMLoc StartLoc, EndLoc; 2019 BaseLoc = Parser.getTok().getLoc(); 2020 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return nullptr; 2021 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) { 2022 Error(StartLoc, "eiz and riz can only be used as index registers", 2023 SMRange(StartLoc, EndLoc)); 2024 return nullptr; 2025 } 2026 } 2027 2028 if (getLexer().is(AsmToken::Comma)) { 2029 Parser.Lex(); // Eat the comma. 2030 IndexLoc = Parser.getTok().getLoc(); 2031 2032 // Following the comma we should have either an index register, or a scale 2033 // value. We don't support the later form, but we want to parse it 2034 // correctly. 2035 // 2036 // Not that even though it would be completely consistent to support syntax 2037 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this. 2038 if (getLexer().is(AsmToken::Percent)) { 2039 SMLoc L; 2040 if (ParseRegister(IndexReg, L, L)) 2041 return nullptr; 2042 if (BaseReg == X86::RIP) { 2043 Error(IndexLoc, "%rip as base register can not have an index register"); 2044 return nullptr; 2045 } 2046 if (IndexReg == X86::RIP) { 2047 Error(IndexLoc, "%rip is not allowed as an index register"); 2048 return nullptr; 2049 } 2050 2051 if (getLexer().isNot(AsmToken::RParen)) { 2052 // Parse the scale amount: 2053 // ::= ',' [scale-expression] 2054 if (getLexer().isNot(AsmToken::Comma)) { 2055 Error(Parser.getTok().getLoc(), 2056 "expected comma in scale expression"); 2057 return nullptr; 2058 } 2059 Parser.Lex(); // Eat the comma. 2060 2061 if (getLexer().isNot(AsmToken::RParen)) { 2062 SMLoc Loc = Parser.getTok().getLoc(); 2063 2064 int64_t ScaleVal; 2065 if (getParser().parseAbsoluteExpression(ScaleVal)){ 2066 Error(Loc, "expected scale expression"); 2067 return nullptr; 2068 } 2069 2070 // Validate the scale amount. 2071 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) && 2072 ScaleVal != 1) { 2073 Error(Loc, "scale factor in 16-bit address must be 1"); 2074 return nullptr; 2075 } 2076 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && 2077 ScaleVal != 8) { 2078 Error(Loc, "scale factor in address must be 1, 2, 4 or 8"); 2079 return nullptr; 2080 } 2081 Scale = (unsigned)ScaleVal; 2082 } 2083 } 2084 } else if (getLexer().isNot(AsmToken::RParen)) { 2085 // A scale amount without an index is ignored. 2086 // index. 2087 SMLoc Loc = Parser.getTok().getLoc(); 2088 2089 int64_t Value; 2090 if (getParser().parseAbsoluteExpression(Value)) 2091 return nullptr; 2092 2093 if (Value != 1) 2094 Warning(Loc, "scale factor without index register is ignored"); 2095 Scale = 1; 2096 } 2097 } 2098 2099 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too. 2100 if (getLexer().isNot(AsmToken::RParen)) { 2101 Error(Parser.getTok().getLoc(), "unexpected token in memory operand"); 2102 return nullptr; 2103 } 2104 SMLoc MemEnd = Parser.getTok().getEndLoc(); 2105 Parser.Lex(); // Eat the ')'. 2106 2107 // Check for use of invalid 16-bit registers. Only BX/BP/SI/DI are allowed, 2108 // and then only in non-64-bit modes. Except for DX, which is a special case 2109 // because an unofficial form of in/out instructions uses it. 2110 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) && 2111 (is64BitMode() || (BaseReg != X86::BX && BaseReg != X86::BP && 2112 BaseReg != X86::SI && BaseReg != X86::DI)) && 2113 BaseReg != X86::DX) { 2114 Error(BaseLoc, "invalid 16-bit base register"); 2115 return nullptr; 2116 } 2117 if (BaseReg == 0 && 2118 X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)) { 2119 Error(IndexLoc, "16-bit memory operand may not include only index register"); 2120 return nullptr; 2121 } 2122 2123 StringRef ErrMsg; 2124 if (CheckBaseRegAndIndexRegAndScale(BaseReg, IndexReg, Scale, ErrMsg)) { 2125 Error(BaseLoc, ErrMsg); 2126 return nullptr; 2127 } 2128 2129 if (SegReg || BaseReg || IndexReg) 2130 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg, 2131 IndexReg, Scale, MemStart, MemEnd); 2132 return X86Operand::CreateMem(getPointerWidth(), Disp, MemStart, MemEnd); 2133 } 2134 2135 bool X86AsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name, 2136 SMLoc NameLoc, OperandVector &Operands) { 2137 MCAsmParser &Parser = getParser(); 2138 InstInfo = &Info; 2139 StringRef PatchedName = Name; 2140 2141 if ((Name.equals("jmp") || Name.equals("jc") || Name.equals("jz")) && 2142 isParsingIntelSyntax() && isParsingInlineAsm()) { 2143 StringRef NextTok = Parser.getTok().getString(); 2144 if (NextTok == "short") { 2145 SMLoc NameEndLoc = 2146 NameLoc.getFromPointer(NameLoc.getPointer() + Name.size()); 2147 // Eat the short keyword 2148 Parser.Lex(); 2149 // MS ignores the short keyword, it determines the jmp type based 2150 // on the distance of the label 2151 InstInfo->AsmRewrites->emplace_back(AOK_Skip, NameEndLoc, 2152 NextTok.size() + 1); 2153 } 2154 } 2155 2156 // FIXME: Hack to recognize setneb as setne. 2157 if (PatchedName.startswith("set") && PatchedName.endswith("b") && 2158 PatchedName != "setb" && PatchedName != "setnb") 2159 PatchedName = PatchedName.substr(0, Name.size()-1); 2160 2161 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}. 2162 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) && 2163 (PatchedName.endswith("ss") || PatchedName.endswith("sd") || 2164 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) { 2165 bool IsVCMP = PatchedName[0] == 'v'; 2166 unsigned CCIdx = IsVCMP ? 4 : 3; 2167 unsigned ComparisonCode = StringSwitch<unsigned>( 2168 PatchedName.slice(CCIdx, PatchedName.size() - 2)) 2169 .Case("eq", 0x00) 2170 .Case("eq_oq", 0x00) 2171 .Case("lt", 0x01) 2172 .Case("lt_os", 0x01) 2173 .Case("le", 0x02) 2174 .Case("le_os", 0x02) 2175 .Case("unord", 0x03) 2176 .Case("unord_q", 0x03) 2177 .Case("neq", 0x04) 2178 .Case("neq_uq", 0x04) 2179 .Case("nlt", 0x05) 2180 .Case("nlt_us", 0x05) 2181 .Case("nle", 0x06) 2182 .Case("nle_us", 0x06) 2183 .Case("ord", 0x07) 2184 .Case("ord_q", 0x07) 2185 /* AVX only from here */ 2186 .Case("eq_uq", 0x08) 2187 .Case("nge", 0x09) 2188 .Case("nge_us", 0x09) 2189 .Case("ngt", 0x0A) 2190 .Case("ngt_us", 0x0A) 2191 .Case("false", 0x0B) 2192 .Case("false_oq", 0x0B) 2193 .Case("neq_oq", 0x0C) 2194 .Case("ge", 0x0D) 2195 .Case("ge_os", 0x0D) 2196 .Case("gt", 0x0E) 2197 .Case("gt_os", 0x0E) 2198 .Case("true", 0x0F) 2199 .Case("true_uq", 0x0F) 2200 .Case("eq_os", 0x10) 2201 .Case("lt_oq", 0x11) 2202 .Case("le_oq", 0x12) 2203 .Case("unord_s", 0x13) 2204 .Case("neq_us", 0x14) 2205 .Case("nlt_uq", 0x15) 2206 .Case("nle_uq", 0x16) 2207 .Case("ord_s", 0x17) 2208 .Case("eq_us", 0x18) 2209 .Case("nge_uq", 0x19) 2210 .Case("ngt_uq", 0x1A) 2211 .Case("false_os", 0x1B) 2212 .Case("neq_os", 0x1C) 2213 .Case("ge_oq", 0x1D) 2214 .Case("gt_oq", 0x1E) 2215 .Case("true_us", 0x1F) 2216 .Default(~0U); 2217 if (ComparisonCode != ~0U && (IsVCMP || ComparisonCode < 8)) { 2218 2219 Operands.push_back(X86Operand::CreateToken(PatchedName.slice(0, CCIdx), 2220 NameLoc)); 2221 2222 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonCode, 2223 getParser().getContext()); 2224 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc)); 2225 2226 PatchedName = PatchedName.substr(PatchedName.size() - 2); 2227 } 2228 } 2229 2230 // FIXME: Hack to recognize vpcmp<comparison code>{ub,uw,ud,uq,b,w,d,q}. 2231 if (PatchedName.startswith("vpcmp") && 2232 (PatchedName.endswith("b") || PatchedName.endswith("w") || 2233 PatchedName.endswith("d") || PatchedName.endswith("q"))) { 2234 unsigned CCIdx = PatchedName.drop_back().back() == 'u' ? 2 : 1; 2235 unsigned ComparisonCode = StringSwitch<unsigned>( 2236 PatchedName.slice(5, PatchedName.size() - CCIdx)) 2237 .Case("eq", 0x0) // Only allowed on unsigned. Checked below. 2238 .Case("lt", 0x1) 2239 .Case("le", 0x2) 2240 //.Case("false", 0x3) // Not a documented alias. 2241 .Case("neq", 0x4) 2242 .Case("nlt", 0x5) 2243 .Case("nle", 0x6) 2244 //.Case("true", 0x7) // Not a documented alias. 2245 .Default(~0U); 2246 if (ComparisonCode != ~0U && (ComparisonCode != 0 || CCIdx == 2)) { 2247 Operands.push_back(X86Operand::CreateToken("vpcmp", NameLoc)); 2248 2249 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonCode, 2250 getParser().getContext()); 2251 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc)); 2252 2253 PatchedName = PatchedName.substr(PatchedName.size() - CCIdx); 2254 } 2255 } 2256 2257 // FIXME: Hack to recognize vpcom<comparison code>{ub,uw,ud,uq,b,w,d,q}. 2258 if (PatchedName.startswith("vpcom") && 2259 (PatchedName.endswith("b") || PatchedName.endswith("w") || 2260 PatchedName.endswith("d") || PatchedName.endswith("q"))) { 2261 unsigned CCIdx = PatchedName.drop_back().back() == 'u' ? 2 : 1; 2262 unsigned ComparisonCode = StringSwitch<unsigned>( 2263 PatchedName.slice(5, PatchedName.size() - CCIdx)) 2264 .Case("lt", 0x0) 2265 .Case("le", 0x1) 2266 .Case("gt", 0x2) 2267 .Case("ge", 0x3) 2268 .Case("eq", 0x4) 2269 .Case("neq", 0x5) 2270 .Case("false", 0x6) 2271 .Case("true", 0x7) 2272 .Default(~0U); 2273 if (ComparisonCode != ~0U) { 2274 Operands.push_back(X86Operand::CreateToken("vpcom", NameLoc)); 2275 2276 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonCode, 2277 getParser().getContext()); 2278 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc)); 2279 2280 PatchedName = PatchedName.substr(PatchedName.size() - CCIdx); 2281 } 2282 } 2283 2284 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc)); 2285 2286 // Determine whether this is an instruction prefix. 2287 // FIXME: 2288 // Enhance prefixes integrity robustness. for example, following forms 2289 // are currently tolerated: 2290 // repz repnz <insn> ; GAS errors for the use of two similar prefixes 2291 // lock addq %rax, %rbx ; Destination operand must be of memory type 2292 // xacquire <insn> ; xacquire must be accompanied by 'lock' 2293 bool isPrefix = StringSwitch<bool>(Name) 2294 .Cases("lock", 2295 "rep", "repe", 2296 "repz", "repne", 2297 "repnz", "rex64", 2298 "data32", "data16", true) 2299 .Cases("xacquire", "xrelease", true) 2300 .Cases("acquire", "release", isParsingIntelSyntax()) 2301 .Default(false); 2302 2303 bool CurlyAsEndOfStatement = false; 2304 // This does the actual operand parsing. Don't parse any more if we have a 2305 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we 2306 // just want to parse the "lock" as the first instruction and the "incl" as 2307 // the next one. 2308 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) { 2309 2310 // Parse '*' modifier. 2311 if (getLexer().is(AsmToken::Star)) 2312 Operands.push_back(X86Operand::CreateToken("*", consumeToken())); 2313 2314 // Read the operands. 2315 while(1) { 2316 if (std::unique_ptr<X86Operand> Op = ParseOperand()) { 2317 Operands.push_back(std::move(Op)); 2318 if (HandleAVX512Operand(Operands, *Operands.back())) 2319 return true; 2320 } else { 2321 return true; 2322 } 2323 // check for comma and eat it 2324 if (getLexer().is(AsmToken::Comma)) 2325 Parser.Lex(); 2326 else 2327 break; 2328 } 2329 2330 // In MS inline asm curly braces mark the beginning/end of a block, 2331 // therefore they should be interepreted as end of statement 2332 CurlyAsEndOfStatement = 2333 isParsingIntelSyntax() && isParsingInlineAsm() && 2334 (getLexer().is(AsmToken::LCurly) || getLexer().is(AsmToken::RCurly)); 2335 if (getLexer().isNot(AsmToken::EndOfStatement) && !CurlyAsEndOfStatement) 2336 return TokError("unexpected token in argument list"); 2337 } 2338 2339 // Consume the EndOfStatement or the prefix separator Slash 2340 if (getLexer().is(AsmToken::EndOfStatement) || 2341 (isPrefix && getLexer().is(AsmToken::Slash))) 2342 Parser.Lex(); 2343 else if (CurlyAsEndOfStatement) 2344 // Add an actual EndOfStatement before the curly brace 2345 Info.AsmRewrites->emplace_back(AOK_EndOfStatement, 2346 getLexer().getTok().getLoc(), 0); 2347 2348 // This is for gas compatibility and cannot be done in td. 2349 // Adding "p" for some floating point with no argument. 2350 // For example: fsub --> fsubp 2351 bool IsFp = 2352 Name == "fsub" || Name == "fdiv" || Name == "fsubr" || Name == "fdivr"; 2353 if (IsFp && Operands.size() == 1) { 2354 const char *Repl = StringSwitch<const char *>(Name) 2355 .Case("fsub", "fsubp") 2356 .Case("fdiv", "fdivp") 2357 .Case("fsubr", "fsubrp") 2358 .Case("fdivr", "fdivrp"); 2359 static_cast<X86Operand &>(*Operands[0]).setTokenValue(Repl); 2360 } 2361 2362 // Moving a 32 or 16 bit value into a segment register has the same 2363 // behavior. Modify such instructions to always take shorter form. 2364 if ((Name == "mov" || Name == "movw" || Name == "movl") && 2365 (Operands.size() == 3)) { 2366 X86Operand &Op1 = (X86Operand &)*Operands[1]; 2367 X86Operand &Op2 = (X86Operand &)*Operands[2]; 2368 SMLoc Loc = Op1.getEndLoc(); 2369 if (Op1.isReg() && Op2.isReg() && 2370 X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains( 2371 Op2.getReg()) && 2372 (X86MCRegisterClasses[X86::GR16RegClassID].contains(Op1.getReg()) || 2373 X86MCRegisterClasses[X86::GR32RegClassID].contains(Op1.getReg()))) { 2374 // Change instruction name to match new instruction. 2375 if (Name != "mov" && Name[3] == (is16BitMode() ? 'l' : 'w')) { 2376 Name = is16BitMode() ? "movw" : "movl"; 2377 Operands[0] = X86Operand::CreateToken(Name, NameLoc); 2378 } 2379 // Select the correct equivalent 16-/32-bit source register. 2380 unsigned Reg = 2381 getX86SubSuperRegisterOrZero(Op1.getReg(), is16BitMode() ? 16 : 32); 2382 Operands[1] = X86Operand::CreateReg(Reg, Loc, Loc); 2383 } 2384 } 2385 2386 // This is a terrible hack to handle "out[s]?[bwl]? %al, (%dx)" -> 2387 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely 2388 // documented form in various unofficial manuals, so a lot of code uses it. 2389 if ((Name == "outb" || Name == "outsb" || Name == "outw" || Name == "outsw" || 2390 Name == "outl" || Name == "outsl" || Name == "out" || Name == "outs") && 2391 Operands.size() == 3) { 2392 X86Operand &Op = (X86Operand &)*Operands.back(); 2393 if (Op.isMem() && Op.Mem.SegReg == 0 && 2394 isa<MCConstantExpr>(Op.Mem.Disp) && 2395 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 && 2396 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) { 2397 SMLoc Loc = Op.getEndLoc(); 2398 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc); 2399 } 2400 } 2401 // Same hack for "in[s]?[bwl]? (%dx), %al" -> "inb %dx, %al". 2402 if ((Name == "inb" || Name == "insb" || Name == "inw" || Name == "insw" || 2403 Name == "inl" || Name == "insl" || Name == "in" || Name == "ins") && 2404 Operands.size() == 3) { 2405 X86Operand &Op = (X86Operand &)*Operands[1]; 2406 if (Op.isMem() && Op.Mem.SegReg == 0 && 2407 isa<MCConstantExpr>(Op.Mem.Disp) && 2408 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 && 2409 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) { 2410 SMLoc Loc = Op.getEndLoc(); 2411 Operands[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc); 2412 } 2413 } 2414 2415 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 2> TmpOperands; 2416 bool HadVerifyError = false; 2417 2418 // Append default arguments to "ins[bwld]" 2419 if (Name.startswith("ins") && 2420 (Operands.size() == 1 || Operands.size() == 3) && 2421 (Name == "insb" || Name == "insw" || Name == "insl" || Name == "insd" || 2422 Name == "ins")) { 2423 2424 AddDefaultSrcDestOperands(TmpOperands, 2425 X86Operand::CreateReg(X86::DX, NameLoc, NameLoc), 2426 DefaultMemDIOperand(NameLoc)); 2427 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2428 } 2429 2430 // Append default arguments to "outs[bwld]" 2431 if (Name.startswith("outs") && 2432 (Operands.size() == 1 || Operands.size() == 3) && 2433 (Name == "outsb" || Name == "outsw" || Name == "outsl" || 2434 Name == "outsd" || Name == "outs")) { 2435 AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc), 2436 X86Operand::CreateReg(X86::DX, NameLoc, NameLoc)); 2437 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2438 } 2439 2440 // Transform "lods[bwlq]" into "lods[bwlq] ($SIREG)" for appropriate 2441 // values of $SIREG according to the mode. It would be nice if this 2442 // could be achieved with InstAlias in the tables. 2443 if (Name.startswith("lods") && 2444 (Operands.size() == 1 || Operands.size() == 2) && 2445 (Name == "lods" || Name == "lodsb" || Name == "lodsw" || 2446 Name == "lodsl" || Name == "lodsd" || Name == "lodsq")) { 2447 TmpOperands.push_back(DefaultMemSIOperand(NameLoc)); 2448 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2449 } 2450 2451 // Transform "stos[bwlq]" into "stos[bwlq] ($DIREG)" for appropriate 2452 // values of $DIREG according to the mode. It would be nice if this 2453 // could be achieved with InstAlias in the tables. 2454 if (Name.startswith("stos") && 2455 (Operands.size() == 1 || Operands.size() == 2) && 2456 (Name == "stos" || Name == "stosb" || Name == "stosw" || 2457 Name == "stosl" || Name == "stosd" || Name == "stosq")) { 2458 TmpOperands.push_back(DefaultMemDIOperand(NameLoc)); 2459 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2460 } 2461 2462 // Transform "scas[bwlq]" into "scas[bwlq] ($DIREG)" for appropriate 2463 // values of $DIREG according to the mode. It would be nice if this 2464 // could be achieved with InstAlias in the tables. 2465 if (Name.startswith("scas") && 2466 (Operands.size() == 1 || Operands.size() == 2) && 2467 (Name == "scas" || Name == "scasb" || Name == "scasw" || 2468 Name == "scasl" || Name == "scasd" || Name == "scasq")) { 2469 TmpOperands.push_back(DefaultMemDIOperand(NameLoc)); 2470 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2471 } 2472 2473 // Add default SI and DI operands to "cmps[bwlq]". 2474 if (Name.startswith("cmps") && 2475 (Operands.size() == 1 || Operands.size() == 3) && 2476 (Name == "cmps" || Name == "cmpsb" || Name == "cmpsw" || 2477 Name == "cmpsl" || Name == "cmpsd" || Name == "cmpsq")) { 2478 AddDefaultSrcDestOperands(TmpOperands, DefaultMemDIOperand(NameLoc), 2479 DefaultMemSIOperand(NameLoc)); 2480 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2481 } 2482 2483 // Add default SI and DI operands to "movs[bwlq]". 2484 if (((Name.startswith("movs") && 2485 (Name == "movs" || Name == "movsb" || Name == "movsw" || 2486 Name == "movsl" || Name == "movsd" || Name == "movsq")) || 2487 (Name.startswith("smov") && 2488 (Name == "smov" || Name == "smovb" || Name == "smovw" || 2489 Name == "smovl" || Name == "smovd" || Name == "smovq"))) && 2490 (Operands.size() == 1 || Operands.size() == 3)) { 2491 if (Name == "movsd" && Operands.size() == 1 && !isParsingIntelSyntax()) 2492 Operands.back() = X86Operand::CreateToken("movsl", NameLoc); 2493 AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc), 2494 DefaultMemDIOperand(NameLoc)); 2495 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2496 } 2497 2498 // Check if we encountered an error for one the string insturctions 2499 if (HadVerifyError) { 2500 return HadVerifyError; 2501 } 2502 2503 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to 2504 // "shift <op>". 2505 if ((Name.startswith("shr") || Name.startswith("sar") || 2506 Name.startswith("shl") || Name.startswith("sal") || 2507 Name.startswith("rcl") || Name.startswith("rcr") || 2508 Name.startswith("rol") || Name.startswith("ror")) && 2509 Operands.size() == 3) { 2510 if (isParsingIntelSyntax()) { 2511 // Intel syntax 2512 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[2]); 2513 if (Op1.isImm() && isa<MCConstantExpr>(Op1.getImm()) && 2514 cast<MCConstantExpr>(Op1.getImm())->getValue() == 1) 2515 Operands.pop_back(); 2516 } else { 2517 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]); 2518 if (Op1.isImm() && isa<MCConstantExpr>(Op1.getImm()) && 2519 cast<MCConstantExpr>(Op1.getImm())->getValue() == 1) 2520 Operands.erase(Operands.begin() + 1); 2521 } 2522 } 2523 2524 // Transforms "int $3" into "int3" as a size optimization. We can't write an 2525 // instalias with an immediate operand yet. 2526 if (Name == "int" && Operands.size() == 2) { 2527 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]); 2528 if (Op1.isImm()) 2529 if (auto *CE = dyn_cast<MCConstantExpr>(Op1.getImm())) 2530 if (CE->getValue() == 3) { 2531 Operands.erase(Operands.begin() + 1); 2532 static_cast<X86Operand &>(*Operands[0]).setTokenValue("int3"); 2533 } 2534 } 2535 2536 // Transforms "xlat mem8" into "xlatb" 2537 if ((Name == "xlat" || Name == "xlatb") && Operands.size() == 2) { 2538 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]); 2539 if (Op1.isMem8()) { 2540 Warning(Op1.getStartLoc(), "memory operand is only for determining the " 2541 "size, (R|E)BX will be used for the location"); 2542 Operands.pop_back(); 2543 static_cast<X86Operand &>(*Operands[0]).setTokenValue("xlatb"); 2544 } 2545 } 2546 2547 return false; 2548 } 2549 2550 bool X86AsmParser::processInstruction(MCInst &Inst, const OperandVector &Ops) { 2551 return false; 2552 } 2553 2554 static const char *getSubtargetFeatureName(uint64_t Val); 2555 2556 void X86AsmParser::EmitInstruction(MCInst &Inst, OperandVector &Operands, 2557 MCStreamer &Out) { 2558 Instrumentation->InstrumentAndEmitInstruction(Inst, Operands, getContext(), 2559 MII, Out); 2560 } 2561 2562 bool X86AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, 2563 OperandVector &Operands, 2564 MCStreamer &Out, uint64_t &ErrorInfo, 2565 bool MatchingInlineAsm) { 2566 if (isParsingIntelSyntax()) 2567 return MatchAndEmitIntelInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo, 2568 MatchingInlineAsm); 2569 return MatchAndEmitATTInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo, 2570 MatchingInlineAsm); 2571 } 2572 2573 void X86AsmParser::MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op, 2574 OperandVector &Operands, MCStreamer &Out, 2575 bool MatchingInlineAsm) { 2576 // FIXME: This should be replaced with a real .td file alias mechanism. 2577 // Also, MatchInstructionImpl should actually *do* the EmitInstruction 2578 // call. 2579 const char *Repl = StringSwitch<const char *>(Op.getToken()) 2580 .Case("finit", "fninit") 2581 .Case("fsave", "fnsave") 2582 .Case("fstcw", "fnstcw") 2583 .Case("fstcww", "fnstcw") 2584 .Case("fstenv", "fnstenv") 2585 .Case("fstsw", "fnstsw") 2586 .Case("fstsww", "fnstsw") 2587 .Case("fclex", "fnclex") 2588 .Default(nullptr); 2589 if (Repl) { 2590 MCInst Inst; 2591 Inst.setOpcode(X86::WAIT); 2592 Inst.setLoc(IDLoc); 2593 if (!MatchingInlineAsm) 2594 EmitInstruction(Inst, Operands, Out); 2595 Operands[0] = X86Operand::CreateToken(Repl, IDLoc); 2596 } 2597 } 2598 2599 bool X86AsmParser::ErrorMissingFeature(SMLoc IDLoc, uint64_t ErrorInfo, 2600 bool MatchingInlineAsm) { 2601 assert(ErrorInfo && "Unknown missing feature!"); 2602 SmallString<126> Msg; 2603 raw_svector_ostream OS(Msg); 2604 OS << "instruction requires:"; 2605 uint64_t Mask = 1; 2606 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) { 2607 if (ErrorInfo & Mask) 2608 OS << ' ' << getSubtargetFeatureName(ErrorInfo & Mask); 2609 Mask <<= 1; 2610 } 2611 return Error(IDLoc, OS.str(), SMRange(), MatchingInlineAsm); 2612 } 2613 2614 bool X86AsmParser::MatchAndEmitATTInstruction(SMLoc IDLoc, unsigned &Opcode, 2615 OperandVector &Operands, 2616 MCStreamer &Out, 2617 uint64_t &ErrorInfo, 2618 bool MatchingInlineAsm) { 2619 assert(!Operands.empty() && "Unexpect empty operand list!"); 2620 X86Operand &Op = static_cast<X86Operand &>(*Operands[0]); 2621 assert(Op.isToken() && "Leading operand should always be a mnemonic!"); 2622 SMRange EmptyRange = None; 2623 2624 // First, handle aliases that expand to multiple instructions. 2625 MatchFPUWaitAlias(IDLoc, Op, Operands, Out, MatchingInlineAsm); 2626 2627 bool WasOriginallyInvalidOperand = false; 2628 MCInst Inst; 2629 2630 // First, try a direct match. 2631 switch (MatchInstruction(Operands, Inst, ErrorInfo, MatchingInlineAsm, 2632 isParsingIntelSyntax())) { 2633 default: llvm_unreachable("Unexpected match result!"); 2634 case Match_Success: 2635 // Some instructions need post-processing to, for example, tweak which 2636 // encoding is selected. Loop on it while changes happen so the 2637 // individual transformations can chain off each other. 2638 if (!MatchingInlineAsm) 2639 while (processInstruction(Inst, Operands)) 2640 ; 2641 2642 Inst.setLoc(IDLoc); 2643 if (!MatchingInlineAsm) 2644 EmitInstruction(Inst, Operands, Out); 2645 Opcode = Inst.getOpcode(); 2646 return false; 2647 case Match_MissingFeature: 2648 return ErrorMissingFeature(IDLoc, ErrorInfo, MatchingInlineAsm); 2649 case Match_InvalidOperand: 2650 WasOriginallyInvalidOperand = true; 2651 break; 2652 case Match_MnemonicFail: 2653 break; 2654 } 2655 2656 // FIXME: Ideally, we would only attempt suffix matches for things which are 2657 // valid prefixes, and we could just infer the right unambiguous 2658 // type. However, that requires substantially more matcher support than the 2659 // following hack. 2660 2661 // Change the operand to point to a temporary token. 2662 StringRef Base = Op.getToken(); 2663 SmallString<16> Tmp; 2664 Tmp += Base; 2665 Tmp += ' '; 2666 Op.setTokenValue(Tmp); 2667 2668 // If this instruction starts with an 'f', then it is a floating point stack 2669 // instruction. These come in up to three forms for 32-bit, 64-bit, and 2670 // 80-bit floating point, which use the suffixes s,l,t respectively. 2671 // 2672 // Otherwise, we assume that this may be an integer instruction, which comes 2673 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively. 2674 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0"; 2675 2676 // Check for the various suffix matches. 2677 uint64_t ErrorInfoIgnore; 2678 uint64_t ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings. 2679 unsigned Match[4]; 2680 2681 for (unsigned I = 0, E = array_lengthof(Match); I != E; ++I) { 2682 Tmp.back() = Suffixes[I]; 2683 Match[I] = MatchInstruction(Operands, Inst, ErrorInfoIgnore, 2684 MatchingInlineAsm, isParsingIntelSyntax()); 2685 // If this returned as a missing feature failure, remember that. 2686 if (Match[I] == Match_MissingFeature) 2687 ErrorInfoMissingFeature = ErrorInfoIgnore; 2688 } 2689 2690 // Restore the old token. 2691 Op.setTokenValue(Base); 2692 2693 // If exactly one matched, then we treat that as a successful match (and the 2694 // instruction will already have been filled in correctly, since the failing 2695 // matches won't have modified it). 2696 unsigned NumSuccessfulMatches = 2697 std::count(std::begin(Match), std::end(Match), Match_Success); 2698 if (NumSuccessfulMatches == 1) { 2699 Inst.setLoc(IDLoc); 2700 if (!MatchingInlineAsm) 2701 EmitInstruction(Inst, Operands, Out); 2702 Opcode = Inst.getOpcode(); 2703 return false; 2704 } 2705 2706 // Otherwise, the match failed, try to produce a decent error message. 2707 2708 // If we had multiple suffix matches, then identify this as an ambiguous 2709 // match. 2710 if (NumSuccessfulMatches > 1) { 2711 char MatchChars[4]; 2712 unsigned NumMatches = 0; 2713 for (unsigned I = 0, E = array_lengthof(Match); I != E; ++I) 2714 if (Match[I] == Match_Success) 2715 MatchChars[NumMatches++] = Suffixes[I]; 2716 2717 SmallString<126> Msg; 2718 raw_svector_ostream OS(Msg); 2719 OS << "ambiguous instructions require an explicit suffix (could be "; 2720 for (unsigned i = 0; i != NumMatches; ++i) { 2721 if (i != 0) 2722 OS << ", "; 2723 if (i + 1 == NumMatches) 2724 OS << "or "; 2725 OS << "'" << Base << MatchChars[i] << "'"; 2726 } 2727 OS << ")"; 2728 Error(IDLoc, OS.str(), EmptyRange, MatchingInlineAsm); 2729 return true; 2730 } 2731 2732 // Okay, we know that none of the variants matched successfully. 2733 2734 // If all of the instructions reported an invalid mnemonic, then the original 2735 // mnemonic was invalid. 2736 if (std::count(std::begin(Match), std::end(Match), Match_MnemonicFail) == 4) { 2737 if (!WasOriginallyInvalidOperand) { 2738 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'", 2739 Op.getLocRange(), MatchingInlineAsm); 2740 } 2741 2742 // Recover location info for the operand if we know which was the problem. 2743 if (ErrorInfo != ~0ULL) { 2744 if (ErrorInfo >= Operands.size()) 2745 return Error(IDLoc, "too few operands for instruction", EmptyRange, 2746 MatchingInlineAsm); 2747 2748 X86Operand &Operand = (X86Operand &)*Operands[ErrorInfo]; 2749 if (Operand.getStartLoc().isValid()) { 2750 SMRange OperandRange = Operand.getLocRange(); 2751 return Error(Operand.getStartLoc(), "invalid operand for instruction", 2752 OperandRange, MatchingInlineAsm); 2753 } 2754 } 2755 2756 return Error(IDLoc, "invalid operand for instruction", EmptyRange, 2757 MatchingInlineAsm); 2758 } 2759 2760 // If one instruction matched with a missing feature, report this as a 2761 // missing feature. 2762 if (std::count(std::begin(Match), std::end(Match), 2763 Match_MissingFeature) == 1) { 2764 ErrorInfo = ErrorInfoMissingFeature; 2765 return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeature, 2766 MatchingInlineAsm); 2767 } 2768 2769 // If one instruction matched with an invalid operand, report this as an 2770 // operand failure. 2771 if (std::count(std::begin(Match), std::end(Match), 2772 Match_InvalidOperand) == 1) { 2773 return Error(IDLoc, "invalid operand for instruction", EmptyRange, 2774 MatchingInlineAsm); 2775 } 2776 2777 // If all of these were an outright failure, report it in a useless way. 2778 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix", 2779 EmptyRange, MatchingInlineAsm); 2780 return true; 2781 } 2782 2783 bool X86AsmParser::MatchAndEmitIntelInstruction(SMLoc IDLoc, unsigned &Opcode, 2784 OperandVector &Operands, 2785 MCStreamer &Out, 2786 uint64_t &ErrorInfo, 2787 bool MatchingInlineAsm) { 2788 assert(!Operands.empty() && "Unexpect empty operand list!"); 2789 X86Operand &Op = static_cast<X86Operand &>(*Operands[0]); 2790 assert(Op.isToken() && "Leading operand should always be a mnemonic!"); 2791 StringRef Mnemonic = Op.getToken(); 2792 SMRange EmptyRange = None; 2793 StringRef Base = Op.getToken(); 2794 2795 // First, handle aliases that expand to multiple instructions. 2796 MatchFPUWaitAlias(IDLoc, Op, Operands, Out, MatchingInlineAsm); 2797 2798 MCInst Inst; 2799 2800 // Find one unsized memory operand, if present. 2801 X86Operand *UnsizedMemOp = nullptr; 2802 for (const auto &Op : Operands) { 2803 X86Operand *X86Op = static_cast<X86Operand *>(Op.get()); 2804 if (X86Op->isMemUnsized()) { 2805 UnsizedMemOp = X86Op; 2806 // Have we found an unqualified memory operand, 2807 // break. IA allows only one memory operand. 2808 break; 2809 } 2810 } 2811 2812 // Allow some instructions to have implicitly pointer-sized operands. This is 2813 // compatible with gas. 2814 if (UnsizedMemOp) { 2815 static const char *const PtrSizedInstrs[] = {"call", "jmp", "push"}; 2816 for (const char *Instr : PtrSizedInstrs) { 2817 if (Mnemonic == Instr) { 2818 UnsizedMemOp->Mem.Size = getPointerWidth(); 2819 break; 2820 } 2821 } 2822 } 2823 2824 SmallVector<unsigned, 8> Match; 2825 uint64_t ErrorInfoMissingFeature = 0; 2826 2827 // If unsized push has immediate operand we should default the default pointer 2828 // size for the size. 2829 if (Mnemonic == "push" && Operands.size() == 2) { 2830 auto *X86Op = static_cast<X86Operand *>(Operands[1].get()); 2831 if (X86Op->isImm()) { 2832 // If it's not a constant fall through and let remainder take care of it. 2833 const auto *CE = dyn_cast<MCConstantExpr>(X86Op->getImm()); 2834 unsigned Size = getPointerWidth(); 2835 if (CE && 2836 (isIntN(Size, CE->getValue()) || isUIntN(Size, CE->getValue()))) { 2837 SmallString<16> Tmp; 2838 Tmp += Base; 2839 Tmp += (is64BitMode()) 2840 ? "q" 2841 : (is32BitMode()) ? "l" : (is16BitMode()) ? "w" : " "; 2842 Op.setTokenValue(Tmp); 2843 // Do match in ATT mode to allow explicit suffix usage. 2844 Match.push_back(MatchInstruction(Operands, Inst, ErrorInfo, 2845 MatchingInlineAsm, 2846 false /*isParsingIntelSyntax()*/)); 2847 Op.setTokenValue(Base); 2848 } 2849 } 2850 } 2851 2852 // If an unsized memory operand is present, try to match with each memory 2853 // operand size. In Intel assembly, the size is not part of the instruction 2854 // mnemonic. 2855 if (UnsizedMemOp && UnsizedMemOp->isMemUnsized()) { 2856 static const unsigned MopSizes[] = {8, 16, 32, 64, 80, 128, 256, 512}; 2857 for (unsigned Size : MopSizes) { 2858 UnsizedMemOp->Mem.Size = Size; 2859 uint64_t ErrorInfoIgnore; 2860 unsigned LastOpcode = Inst.getOpcode(); 2861 unsigned M = MatchInstruction(Operands, Inst, ErrorInfoIgnore, 2862 MatchingInlineAsm, isParsingIntelSyntax()); 2863 if (Match.empty() || LastOpcode != Inst.getOpcode()) 2864 Match.push_back(M); 2865 2866 // If this returned as a missing feature failure, remember that. 2867 if (Match.back() == Match_MissingFeature) 2868 ErrorInfoMissingFeature = ErrorInfoIgnore; 2869 } 2870 2871 // Restore the size of the unsized memory operand if we modified it. 2872 UnsizedMemOp->Mem.Size = 0; 2873 } 2874 2875 // If we haven't matched anything yet, this is not a basic integer or FPU 2876 // operation. There shouldn't be any ambiguity in our mnemonic table, so try 2877 // matching with the unsized operand. 2878 if (Match.empty()) { 2879 Match.push_back(MatchInstruction( 2880 Operands, Inst, ErrorInfo, MatchingInlineAsm, isParsingIntelSyntax())); 2881 // If this returned as a missing feature failure, remember that. 2882 if (Match.back() == Match_MissingFeature) 2883 ErrorInfoMissingFeature = ErrorInfo; 2884 } 2885 2886 // Restore the size of the unsized memory operand if we modified it. 2887 if (UnsizedMemOp) 2888 UnsizedMemOp->Mem.Size = 0; 2889 2890 // If it's a bad mnemonic, all results will be the same. 2891 if (Match.back() == Match_MnemonicFail) { 2892 return Error(IDLoc, "invalid instruction mnemonic '" + Mnemonic + "'", 2893 Op.getLocRange(), MatchingInlineAsm); 2894 } 2895 2896 unsigned NumSuccessfulMatches = 2897 std::count(std::begin(Match), std::end(Match), Match_Success); 2898 2899 // If matching was ambiguous and we had size information from the frontend, 2900 // try again with that. This handles cases like "movxz eax, m8/m16". 2901 if (UnsizedMemOp && NumSuccessfulMatches > 1 && 2902 UnsizedMemOp->getMemFrontendSize()) { 2903 UnsizedMemOp->Mem.Size = UnsizedMemOp->getMemFrontendSize(); 2904 unsigned M = MatchInstruction( 2905 Operands, Inst, ErrorInfo, MatchingInlineAsm, isParsingIntelSyntax()); 2906 if (M == Match_Success) 2907 NumSuccessfulMatches = 1; 2908 2909 // Add a rewrite that encodes the size information we used from the 2910 // frontend. 2911 InstInfo->AsmRewrites->emplace_back( 2912 AOK_SizeDirective, UnsizedMemOp->getStartLoc(), 2913 /*Len=*/0, UnsizedMemOp->getMemFrontendSize()); 2914 } 2915 2916 // If exactly one matched, then we treat that as a successful match (and the 2917 // instruction will already have been filled in correctly, since the failing 2918 // matches won't have modified it). 2919 if (NumSuccessfulMatches == 1) { 2920 // Some instructions need post-processing to, for example, tweak which 2921 // encoding is selected. Loop on it while changes happen so the individual 2922 // transformations can chain off each other. 2923 if (!MatchingInlineAsm) 2924 while (processInstruction(Inst, Operands)) 2925 ; 2926 Inst.setLoc(IDLoc); 2927 if (!MatchingInlineAsm) 2928 EmitInstruction(Inst, Operands, Out); 2929 Opcode = Inst.getOpcode(); 2930 return false; 2931 } else if (NumSuccessfulMatches > 1) { 2932 assert(UnsizedMemOp && 2933 "multiple matches only possible with unsized memory operands"); 2934 return Error(UnsizedMemOp->getStartLoc(), 2935 "ambiguous operand size for instruction '" + Mnemonic + "\'", 2936 UnsizedMemOp->getLocRange()); 2937 } 2938 2939 // If one instruction matched with a missing feature, report this as a 2940 // missing feature. 2941 if (std::count(std::begin(Match), std::end(Match), 2942 Match_MissingFeature) == 1) { 2943 ErrorInfo = ErrorInfoMissingFeature; 2944 return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeature, 2945 MatchingInlineAsm); 2946 } 2947 2948 // If one instruction matched with an invalid operand, report this as an 2949 // operand failure. 2950 if (std::count(std::begin(Match), std::end(Match), 2951 Match_InvalidOperand) == 1) { 2952 return Error(IDLoc, "invalid operand for instruction", EmptyRange, 2953 MatchingInlineAsm); 2954 } 2955 2956 // If all of these were an outright failure, report it in a useless way. 2957 return Error(IDLoc, "unknown instruction mnemonic", EmptyRange, 2958 MatchingInlineAsm); 2959 } 2960 2961 bool X86AsmParser::OmitRegisterFromClobberLists(unsigned RegNo) { 2962 return X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo); 2963 } 2964 2965 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) { 2966 MCAsmParser &Parser = getParser(); 2967 StringRef IDVal = DirectiveID.getIdentifier(); 2968 if (IDVal == ".word") 2969 return ParseDirectiveWord(2, DirectiveID.getLoc()); 2970 else if (IDVal.startswith(".code")) 2971 return ParseDirectiveCode(IDVal, DirectiveID.getLoc()); 2972 else if (IDVal.startswith(".att_syntax")) { 2973 getParser().setParsingInlineAsm(false); 2974 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2975 if (Parser.getTok().getString() == "prefix") 2976 Parser.Lex(); 2977 else if (Parser.getTok().getString() == "noprefix") 2978 return Error(DirectiveID.getLoc(), "'.att_syntax noprefix' is not " 2979 "supported: registers must have a " 2980 "'%' prefix in .att_syntax"); 2981 } 2982 getParser().setAssemblerDialect(0); 2983 return false; 2984 } else if (IDVal.startswith(".intel_syntax")) { 2985 getParser().setAssemblerDialect(1); 2986 getParser().setParsingInlineAsm(true); 2987 if (getLexer().isNot(AsmToken::EndOfStatement)) { 2988 if (Parser.getTok().getString() == "noprefix") 2989 Parser.Lex(); 2990 else if (Parser.getTok().getString() == "prefix") 2991 return Error(DirectiveID.getLoc(), "'.intel_syntax prefix' is not " 2992 "supported: registers must not have " 2993 "a '%' prefix in .intel_syntax"); 2994 } 2995 return false; 2996 } else if (IDVal == ".even") 2997 return parseDirectiveEven(DirectiveID.getLoc()); 2998 return true; 2999 } 3000 3001 /// parseDirectiveEven 3002 /// ::= .even 3003 bool X86AsmParser::parseDirectiveEven(SMLoc L) { 3004 if (getLexer().isNot(AsmToken::EndOfStatement)) { 3005 TokError("unexpected token in directive"); 3006 return false; 3007 } 3008 const MCSection *Section = getStreamer().getCurrentSectionOnly(); 3009 if (!Section) { 3010 getStreamer().InitSections(false); 3011 Section = getStreamer().getCurrentSectionOnly(); 3012 } 3013 if (Section->UseCodeAlign()) 3014 getStreamer().EmitCodeAlignment(2, 0); 3015 else 3016 getStreamer().EmitValueToAlignment(2, 0, 1, 0); 3017 return false; 3018 } 3019 /// ParseDirectiveWord 3020 /// ::= .word [ expression (, expression)* ] 3021 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) { 3022 MCAsmParser &Parser = getParser(); 3023 if (getLexer().isNot(AsmToken::EndOfStatement)) { 3024 for (;;) { 3025 const MCExpr *Value; 3026 SMLoc ExprLoc = getLexer().getLoc(); 3027 if (getParser().parseExpression(Value)) 3028 return false; 3029 3030 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value)) { 3031 assert(Size <= 8 && "Invalid size"); 3032 uint64_t IntValue = MCE->getValue(); 3033 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue)) 3034 return Error(ExprLoc, "literal value out of range for directive"); 3035 getStreamer().EmitIntValue(IntValue, Size); 3036 } else { 3037 getStreamer().EmitValue(Value, Size, ExprLoc); 3038 } 3039 3040 if (getLexer().is(AsmToken::EndOfStatement)) 3041 break; 3042 3043 // FIXME: Improve diagnostic. 3044 if (getLexer().isNot(AsmToken::Comma)) { 3045 Error(L, "unexpected token in directive"); 3046 return false; 3047 } 3048 Parser.Lex(); 3049 } 3050 } 3051 3052 Parser.Lex(); 3053 return false; 3054 } 3055 3056 /// ParseDirectiveCode 3057 /// ::= .code16 | .code32 | .code64 3058 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) { 3059 MCAsmParser &Parser = getParser(); 3060 Code16GCC = false; 3061 if (IDVal == ".code16") { 3062 Parser.Lex(); 3063 if (!is16BitMode()) { 3064 SwitchMode(X86::Mode16Bit); 3065 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16); 3066 } 3067 } else if (IDVal == ".code16gcc") { 3068 // .code16gcc parses as if in 32-bit mode, but emits code in 16-bit mode. 3069 Parser.Lex(); 3070 Code16GCC = true; 3071 if (!is16BitMode()) { 3072 SwitchMode(X86::Mode16Bit); 3073 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16); 3074 } 3075 } else if (IDVal == ".code32") { 3076 Parser.Lex(); 3077 if (!is32BitMode()) { 3078 SwitchMode(X86::Mode32Bit); 3079 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32); 3080 } 3081 } else if (IDVal == ".code64") { 3082 Parser.Lex(); 3083 if (!is64BitMode()) { 3084 SwitchMode(X86::Mode64Bit); 3085 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64); 3086 } 3087 } else { 3088 Error(L, "unknown directive " + IDVal); 3089 return false; 3090 } 3091 3092 return false; 3093 } 3094 3095 // Force static initialization. 3096 extern "C" void LLVMInitializeX86AsmParser() { 3097 RegisterMCAsmParser<X86AsmParser> X(getTheX86_32Target()); 3098 RegisterMCAsmParser<X86AsmParser> Y(getTheX86_64Target()); 3099 } 3100 3101 #define GET_REGISTER_MATCHER 3102 #define GET_MATCHER_IMPLEMENTATION 3103 #define GET_SUBTARGET_FEATURE_NAME 3104 #include "X86GenAsmMatcher.inc" 3105