1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "MCTargetDesc/X86BaseInfo.h" 10 #include "MCTargetDesc/X86IntelInstPrinter.h" 11 #include "MCTargetDesc/X86MCExpr.h" 12 #include "MCTargetDesc/X86TargetStreamer.h" 13 #include "TargetInfo/X86TargetInfo.h" 14 #include "X86AsmParserCommon.h" 15 #include "X86Operand.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/StringSwitch.h" 20 #include "llvm/ADT/Twine.h" 21 #include "llvm/MC/MCContext.h" 22 #include "llvm/MC/MCExpr.h" 23 #include "llvm/MC/MCInst.h" 24 #include "llvm/MC/MCInstrInfo.h" 25 #include "llvm/MC/MCParser/MCAsmLexer.h" 26 #include "llvm/MC/MCParser/MCAsmParser.h" 27 #include "llvm/MC/MCParser/MCParsedAsmOperand.h" 28 #include "llvm/MC/MCParser/MCTargetAsmParser.h" 29 #include "llvm/MC/MCRegisterInfo.h" 30 #include "llvm/MC/MCSection.h" 31 #include "llvm/MC/MCStreamer.h" 32 #include "llvm/MC/MCSubtargetInfo.h" 33 #include "llvm/MC/MCSymbol.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/SourceMgr.h" 36 #include "llvm/Support/TargetRegistry.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include <algorithm> 39 #include <memory> 40 41 using namespace llvm; 42 43 static cl::opt<bool> LVIInlineAsmHardening( 44 "x86-experimental-lvi-inline-asm-hardening", 45 cl::desc("Harden inline assembly code that may be vulnerable to Load Value" 46 " Injection (LVI). This feature is experimental."), cl::Hidden); 47 48 static bool checkScale(unsigned Scale, StringRef &ErrMsg) { 49 if (Scale != 1 && Scale != 2 && Scale != 4 && Scale != 8) { 50 ErrMsg = "scale factor in address must be 1, 2, 4 or 8"; 51 return true; 52 } 53 return false; 54 } 55 56 namespace { 57 58 static const char OpPrecedence[] = { 59 0, // IC_OR 60 1, // IC_XOR 61 2, // IC_AND 62 3, // IC_LSHIFT 63 3, // IC_RSHIFT 64 4, // IC_PLUS 65 4, // IC_MINUS 66 5, // IC_MULTIPLY 67 5, // IC_DIVIDE 68 5, // IC_MOD 69 6, // IC_NOT 70 7, // IC_NEG 71 8, // IC_RPAREN 72 9, // IC_LPAREN 73 0, // IC_IMM 74 0 // IC_REGISTER 75 }; 76 77 class X86AsmParser : public MCTargetAsmParser { 78 ParseInstructionInfo *InstInfo; 79 bool Code16GCC; 80 81 enum VEXEncoding { 82 VEXEncoding_Default, 83 VEXEncoding_VEX, 84 VEXEncoding_VEX3, 85 VEXEncoding_EVEX, 86 }; 87 88 VEXEncoding ForcedVEXEncoding = VEXEncoding_Default; 89 90 private: 91 SMLoc consumeToken() { 92 MCAsmParser &Parser = getParser(); 93 SMLoc Result = Parser.getTok().getLoc(); 94 Parser.Lex(); 95 return Result; 96 } 97 98 X86TargetStreamer &getTargetStreamer() { 99 assert(getParser().getStreamer().getTargetStreamer() && 100 "do not have a target streamer"); 101 MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer(); 102 return static_cast<X86TargetStreamer &>(TS); 103 } 104 105 unsigned MatchInstruction(const OperandVector &Operands, MCInst &Inst, 106 uint64_t &ErrorInfo, FeatureBitset &MissingFeatures, 107 bool matchingInlineAsm, unsigned VariantID = 0) { 108 // In Code16GCC mode, match as 32-bit. 109 if (Code16GCC) 110 SwitchMode(X86::Mode32Bit); 111 unsigned rv = MatchInstructionImpl(Operands, Inst, ErrorInfo, 112 MissingFeatures, matchingInlineAsm, 113 VariantID); 114 if (Code16GCC) 115 SwitchMode(X86::Mode16Bit); 116 return rv; 117 } 118 119 enum InfixCalculatorTok { 120 IC_OR = 0, 121 IC_XOR, 122 IC_AND, 123 IC_LSHIFT, 124 IC_RSHIFT, 125 IC_PLUS, 126 IC_MINUS, 127 IC_MULTIPLY, 128 IC_DIVIDE, 129 IC_MOD, 130 IC_NOT, 131 IC_NEG, 132 IC_RPAREN, 133 IC_LPAREN, 134 IC_IMM, 135 IC_REGISTER 136 }; 137 138 enum IntelOperatorKind { 139 IOK_INVALID = 0, 140 IOK_LENGTH, 141 IOK_SIZE, 142 IOK_TYPE, 143 }; 144 145 class InfixCalculator { 146 typedef std::pair< InfixCalculatorTok, int64_t > ICToken; 147 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack; 148 SmallVector<ICToken, 4> PostfixStack; 149 150 bool isUnaryOperator(const InfixCalculatorTok Op) { 151 return Op == IC_NEG || Op == IC_NOT; 152 } 153 154 public: 155 int64_t popOperand() { 156 assert (!PostfixStack.empty() && "Poped an empty stack!"); 157 ICToken Op = PostfixStack.pop_back_val(); 158 if (!(Op.first == IC_IMM || Op.first == IC_REGISTER)) 159 return -1; // The invalid Scale value will be caught later by checkScale 160 return Op.second; 161 } 162 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) { 163 assert ((Op == IC_IMM || Op == IC_REGISTER) && 164 "Unexpected operand!"); 165 PostfixStack.push_back(std::make_pair(Op, Val)); 166 } 167 168 void popOperator() { InfixOperatorStack.pop_back(); } 169 void pushOperator(InfixCalculatorTok Op) { 170 // Push the new operator if the stack is empty. 171 if (InfixOperatorStack.empty()) { 172 InfixOperatorStack.push_back(Op); 173 return; 174 } 175 176 // Push the new operator if it has a higher precedence than the operator 177 // on the top of the stack or the operator on the top of the stack is a 178 // left parentheses. 179 unsigned Idx = InfixOperatorStack.size() - 1; 180 InfixCalculatorTok StackOp = InfixOperatorStack[Idx]; 181 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) { 182 InfixOperatorStack.push_back(Op); 183 return; 184 } 185 186 // The operator on the top of the stack has higher precedence than the 187 // new operator. 188 unsigned ParenCount = 0; 189 while (1) { 190 // Nothing to process. 191 if (InfixOperatorStack.empty()) 192 break; 193 194 Idx = InfixOperatorStack.size() - 1; 195 StackOp = InfixOperatorStack[Idx]; 196 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount)) 197 break; 198 199 // If we have an even parentheses count and we see a left parentheses, 200 // then stop processing. 201 if (!ParenCount && StackOp == IC_LPAREN) 202 break; 203 204 if (StackOp == IC_RPAREN) { 205 ++ParenCount; 206 InfixOperatorStack.pop_back(); 207 } else if (StackOp == IC_LPAREN) { 208 --ParenCount; 209 InfixOperatorStack.pop_back(); 210 } else { 211 InfixOperatorStack.pop_back(); 212 PostfixStack.push_back(std::make_pair(StackOp, 0)); 213 } 214 } 215 // Push the new operator. 216 InfixOperatorStack.push_back(Op); 217 } 218 219 int64_t execute() { 220 // Push any remaining operators onto the postfix stack. 221 while (!InfixOperatorStack.empty()) { 222 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val(); 223 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN) 224 PostfixStack.push_back(std::make_pair(StackOp, 0)); 225 } 226 227 if (PostfixStack.empty()) 228 return 0; 229 230 SmallVector<ICToken, 16> OperandStack; 231 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) { 232 ICToken Op = PostfixStack[i]; 233 if (Op.first == IC_IMM || Op.first == IC_REGISTER) { 234 OperandStack.push_back(Op); 235 } else if (isUnaryOperator(Op.first)) { 236 assert (OperandStack.size() > 0 && "Too few operands."); 237 ICToken Operand = OperandStack.pop_back_val(); 238 assert (Operand.first == IC_IMM && 239 "Unary operation with a register!"); 240 switch (Op.first) { 241 default: 242 report_fatal_error("Unexpected operator!"); 243 break; 244 case IC_NEG: 245 OperandStack.push_back(std::make_pair(IC_IMM, -Operand.second)); 246 break; 247 case IC_NOT: 248 OperandStack.push_back(std::make_pair(IC_IMM, ~Operand.second)); 249 break; 250 } 251 } else { 252 assert (OperandStack.size() > 1 && "Too few operands."); 253 int64_t Val; 254 ICToken Op2 = OperandStack.pop_back_val(); 255 ICToken Op1 = OperandStack.pop_back_val(); 256 switch (Op.first) { 257 default: 258 report_fatal_error("Unexpected operator!"); 259 break; 260 case IC_PLUS: 261 Val = Op1.second + Op2.second; 262 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 263 break; 264 case IC_MINUS: 265 Val = Op1.second - Op2.second; 266 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 267 break; 268 case IC_MULTIPLY: 269 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 270 "Multiply operation with an immediate and a register!"); 271 Val = Op1.second * Op2.second; 272 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 273 break; 274 case IC_DIVIDE: 275 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 276 "Divide operation with an immediate and a register!"); 277 assert (Op2.second != 0 && "Division by zero!"); 278 Val = Op1.second / Op2.second; 279 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 280 break; 281 case IC_MOD: 282 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 283 "Modulo operation with an immediate and a register!"); 284 Val = Op1.second % Op2.second; 285 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 286 break; 287 case IC_OR: 288 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 289 "Or operation with an immediate and a register!"); 290 Val = Op1.second | Op2.second; 291 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 292 break; 293 case IC_XOR: 294 assert(Op1.first == IC_IMM && Op2.first == IC_IMM && 295 "Xor operation with an immediate and a register!"); 296 Val = Op1.second ^ Op2.second; 297 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 298 break; 299 case IC_AND: 300 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 301 "And operation with an immediate and a register!"); 302 Val = Op1.second & Op2.second; 303 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 304 break; 305 case IC_LSHIFT: 306 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 307 "Left shift operation with an immediate and a register!"); 308 Val = Op1.second << Op2.second; 309 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 310 break; 311 case IC_RSHIFT: 312 assert (Op1.first == IC_IMM && Op2.first == IC_IMM && 313 "Right shift operation with an immediate and a register!"); 314 Val = Op1.second >> Op2.second; 315 OperandStack.push_back(std::make_pair(IC_IMM, Val)); 316 break; 317 } 318 } 319 } 320 assert (OperandStack.size() == 1 && "Expected a single result."); 321 return OperandStack.pop_back_val().second; 322 } 323 }; 324 325 enum IntelExprState { 326 IES_INIT, 327 IES_OR, 328 IES_XOR, 329 IES_AND, 330 IES_LSHIFT, 331 IES_RSHIFT, 332 IES_PLUS, 333 IES_MINUS, 334 IES_OFFSET, 335 IES_NOT, 336 IES_MULTIPLY, 337 IES_DIVIDE, 338 IES_MOD, 339 IES_LBRAC, 340 IES_RBRAC, 341 IES_LPAREN, 342 IES_RPAREN, 343 IES_REGISTER, 344 IES_INTEGER, 345 IES_IDENTIFIER, 346 IES_ERROR 347 }; 348 349 class IntelExprStateMachine { 350 IntelExprState State, PrevState; 351 unsigned BaseReg, IndexReg, TmpReg, Scale; 352 int64_t Imm; 353 const MCExpr *Sym; 354 StringRef SymName; 355 InfixCalculator IC; 356 InlineAsmIdentifierInfo Info; 357 short BracCount; 358 bool MemExpr; 359 bool OffsetOperator; 360 SMLoc OffsetOperatorLoc; 361 362 bool setSymRef(const MCExpr *Val, StringRef ID, StringRef &ErrMsg) { 363 if (Sym) { 364 ErrMsg = "cannot use more than one symbol in memory operand"; 365 return true; 366 } 367 Sym = Val; 368 SymName = ID; 369 return false; 370 } 371 372 public: 373 IntelExprStateMachine() 374 : State(IES_INIT), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), 375 TmpReg(0), Scale(0), Imm(0), Sym(nullptr), BracCount(0), 376 MemExpr(false), OffsetOperator(false) {} 377 378 void addImm(int64_t imm) { Imm += imm; } 379 short getBracCount() { return BracCount; } 380 bool isMemExpr() { return MemExpr; } 381 bool isOffsetOperator() { return OffsetOperator; } 382 SMLoc getOffsetLoc() { return OffsetOperatorLoc; } 383 unsigned getBaseReg() { return BaseReg; } 384 unsigned getIndexReg() { return IndexReg; } 385 unsigned getScale() { return Scale; } 386 const MCExpr *getSym() { return Sym; } 387 StringRef getSymName() { return SymName; } 388 int64_t getImm() { return Imm + IC.execute(); } 389 bool isValidEndState() { 390 return State == IES_RBRAC || State == IES_INTEGER; 391 } 392 bool hadError() { return State == IES_ERROR; } 393 InlineAsmIdentifierInfo &getIdentifierInfo() { return Info; } 394 395 void onOr() { 396 IntelExprState CurrState = State; 397 switch (State) { 398 default: 399 State = IES_ERROR; 400 break; 401 case IES_INTEGER: 402 case IES_RPAREN: 403 case IES_REGISTER: 404 State = IES_OR; 405 IC.pushOperator(IC_OR); 406 break; 407 } 408 PrevState = CurrState; 409 } 410 void onXor() { 411 IntelExprState CurrState = State; 412 switch (State) { 413 default: 414 State = IES_ERROR; 415 break; 416 case IES_INTEGER: 417 case IES_RPAREN: 418 case IES_REGISTER: 419 State = IES_XOR; 420 IC.pushOperator(IC_XOR); 421 break; 422 } 423 PrevState = CurrState; 424 } 425 void onAnd() { 426 IntelExprState CurrState = State; 427 switch (State) { 428 default: 429 State = IES_ERROR; 430 break; 431 case IES_INTEGER: 432 case IES_RPAREN: 433 case IES_REGISTER: 434 State = IES_AND; 435 IC.pushOperator(IC_AND); 436 break; 437 } 438 PrevState = CurrState; 439 } 440 void onLShift() { 441 IntelExprState CurrState = State; 442 switch (State) { 443 default: 444 State = IES_ERROR; 445 break; 446 case IES_INTEGER: 447 case IES_RPAREN: 448 case IES_REGISTER: 449 State = IES_LSHIFT; 450 IC.pushOperator(IC_LSHIFT); 451 break; 452 } 453 PrevState = CurrState; 454 } 455 void onRShift() { 456 IntelExprState CurrState = State; 457 switch (State) { 458 default: 459 State = IES_ERROR; 460 break; 461 case IES_INTEGER: 462 case IES_RPAREN: 463 case IES_REGISTER: 464 State = IES_RSHIFT; 465 IC.pushOperator(IC_RSHIFT); 466 break; 467 } 468 PrevState = CurrState; 469 } 470 bool onPlus(StringRef &ErrMsg) { 471 IntelExprState CurrState = State; 472 switch (State) { 473 default: 474 State = IES_ERROR; 475 break; 476 case IES_INTEGER: 477 case IES_RPAREN: 478 case IES_REGISTER: 479 case IES_OFFSET: 480 State = IES_PLUS; 481 IC.pushOperator(IC_PLUS); 482 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) { 483 // If we already have a BaseReg, then assume this is the IndexReg with 484 // no explicit scale. 485 if (!BaseReg) { 486 BaseReg = TmpReg; 487 } else { 488 if (IndexReg) { 489 ErrMsg = "BaseReg/IndexReg already set!"; 490 return true; 491 } 492 IndexReg = TmpReg; 493 Scale = 0; 494 } 495 } 496 break; 497 } 498 PrevState = CurrState; 499 return false; 500 } 501 bool onMinus(StringRef &ErrMsg) { 502 IntelExprState CurrState = State; 503 switch (State) { 504 default: 505 State = IES_ERROR; 506 break; 507 case IES_OR: 508 case IES_XOR: 509 case IES_AND: 510 case IES_LSHIFT: 511 case IES_RSHIFT: 512 case IES_PLUS: 513 case IES_NOT: 514 case IES_MULTIPLY: 515 case IES_DIVIDE: 516 case IES_MOD: 517 case IES_LPAREN: 518 case IES_RPAREN: 519 case IES_LBRAC: 520 case IES_RBRAC: 521 case IES_INTEGER: 522 case IES_REGISTER: 523 case IES_INIT: 524 case IES_OFFSET: 525 State = IES_MINUS; 526 // push minus operator if it is not a negate operator 527 if (CurrState == IES_REGISTER || CurrState == IES_RPAREN || 528 CurrState == IES_INTEGER || CurrState == IES_RBRAC || 529 CurrState == IES_OFFSET) 530 IC.pushOperator(IC_MINUS); 531 else if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) { 532 // We have negate operator for Scale: it's illegal 533 ErrMsg = "Scale can't be negative"; 534 return true; 535 } else 536 IC.pushOperator(IC_NEG); 537 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) { 538 // If we already have a BaseReg, then assume this is the IndexReg with 539 // no explicit scale. 540 if (!BaseReg) { 541 BaseReg = TmpReg; 542 } else { 543 if (IndexReg) { 544 ErrMsg = "BaseReg/IndexReg already set!"; 545 return true; 546 } 547 IndexReg = TmpReg; 548 Scale = 0; 549 } 550 } 551 break; 552 } 553 PrevState = CurrState; 554 return false; 555 } 556 void onNot() { 557 IntelExprState CurrState = State; 558 switch (State) { 559 default: 560 State = IES_ERROR; 561 break; 562 case IES_OR: 563 case IES_XOR: 564 case IES_AND: 565 case IES_LSHIFT: 566 case IES_RSHIFT: 567 case IES_PLUS: 568 case IES_MINUS: 569 case IES_NOT: 570 case IES_MULTIPLY: 571 case IES_DIVIDE: 572 case IES_MOD: 573 case IES_LPAREN: 574 case IES_LBRAC: 575 case IES_INIT: 576 State = IES_NOT; 577 IC.pushOperator(IC_NOT); 578 break; 579 } 580 PrevState = CurrState; 581 } 582 bool onRegister(unsigned Reg, StringRef &ErrMsg) { 583 IntelExprState CurrState = State; 584 switch (State) { 585 default: 586 State = IES_ERROR; 587 break; 588 case IES_PLUS: 589 case IES_LPAREN: 590 case IES_LBRAC: 591 State = IES_REGISTER; 592 TmpReg = Reg; 593 IC.pushOperand(IC_REGISTER); 594 break; 595 case IES_MULTIPLY: 596 // Index Register - Scale * Register 597 if (PrevState == IES_INTEGER) { 598 if (IndexReg) { 599 ErrMsg = "BaseReg/IndexReg already set!"; 600 return true; 601 } 602 State = IES_REGISTER; 603 IndexReg = Reg; 604 // Get the scale and replace the 'Scale * Register' with '0'. 605 Scale = IC.popOperand(); 606 if (checkScale(Scale, ErrMsg)) 607 return true; 608 IC.pushOperand(IC_IMM); 609 IC.popOperator(); 610 } else { 611 State = IES_ERROR; 612 } 613 break; 614 } 615 PrevState = CurrState; 616 return false; 617 } 618 bool onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName, 619 const InlineAsmIdentifierInfo &IDInfo, 620 bool ParsingMSInlineAsm, StringRef &ErrMsg) { 621 // InlineAsm: Treat an enum value as an integer 622 if (ParsingMSInlineAsm) 623 if (IDInfo.isKind(InlineAsmIdentifierInfo::IK_EnumVal)) 624 return onInteger(IDInfo.Enum.EnumVal, ErrMsg); 625 // Treat a symbolic constant like an integer 626 if (auto *CE = dyn_cast<MCConstantExpr>(SymRef)) 627 return onInteger(CE->getValue(), ErrMsg); 628 PrevState = State; 629 switch (State) { 630 default: 631 State = IES_ERROR; 632 break; 633 case IES_PLUS: 634 case IES_MINUS: 635 case IES_NOT: 636 case IES_INIT: 637 case IES_LBRAC: 638 if (setSymRef(SymRef, SymRefName, ErrMsg)) 639 return true; 640 MemExpr = true; 641 State = IES_INTEGER; 642 IC.pushOperand(IC_IMM); 643 if (ParsingMSInlineAsm) 644 Info = IDInfo; 645 break; 646 } 647 return false; 648 } 649 bool onInteger(int64_t TmpInt, StringRef &ErrMsg) { 650 IntelExprState CurrState = State; 651 switch (State) { 652 default: 653 State = IES_ERROR; 654 break; 655 case IES_PLUS: 656 case IES_MINUS: 657 case IES_NOT: 658 case IES_OR: 659 case IES_XOR: 660 case IES_AND: 661 case IES_LSHIFT: 662 case IES_RSHIFT: 663 case IES_DIVIDE: 664 case IES_MOD: 665 case IES_MULTIPLY: 666 case IES_LPAREN: 667 case IES_INIT: 668 case IES_LBRAC: 669 State = IES_INTEGER; 670 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) { 671 // Index Register - Register * Scale 672 if (IndexReg) { 673 ErrMsg = "BaseReg/IndexReg already set!"; 674 return true; 675 } 676 IndexReg = TmpReg; 677 Scale = TmpInt; 678 if (checkScale(Scale, ErrMsg)) 679 return true; 680 // Get the scale and replace the 'Register * Scale' with '0'. 681 IC.popOperator(); 682 } else { 683 IC.pushOperand(IC_IMM, TmpInt); 684 } 685 break; 686 } 687 PrevState = CurrState; 688 return false; 689 } 690 void onStar() { 691 PrevState = State; 692 switch (State) { 693 default: 694 State = IES_ERROR; 695 break; 696 case IES_INTEGER: 697 case IES_REGISTER: 698 case IES_RPAREN: 699 State = IES_MULTIPLY; 700 IC.pushOperator(IC_MULTIPLY); 701 break; 702 } 703 } 704 void onDivide() { 705 PrevState = State; 706 switch (State) { 707 default: 708 State = IES_ERROR; 709 break; 710 case IES_INTEGER: 711 case IES_RPAREN: 712 State = IES_DIVIDE; 713 IC.pushOperator(IC_DIVIDE); 714 break; 715 } 716 } 717 void onMod() { 718 PrevState = State; 719 switch (State) { 720 default: 721 State = IES_ERROR; 722 break; 723 case IES_INTEGER: 724 case IES_RPAREN: 725 State = IES_MOD; 726 IC.pushOperator(IC_MOD); 727 break; 728 } 729 } 730 bool onLBrac() { 731 if (BracCount) 732 return true; 733 PrevState = State; 734 switch (State) { 735 default: 736 State = IES_ERROR; 737 break; 738 case IES_RBRAC: 739 case IES_INTEGER: 740 case IES_RPAREN: 741 State = IES_PLUS; 742 IC.pushOperator(IC_PLUS); 743 break; 744 case IES_INIT: 745 assert(!BracCount && "BracCount should be zero on parsing's start"); 746 State = IES_LBRAC; 747 break; 748 } 749 MemExpr = true; 750 BracCount++; 751 return false; 752 } 753 bool onRBrac() { 754 IntelExprState CurrState = State; 755 switch (State) { 756 default: 757 State = IES_ERROR; 758 break; 759 case IES_INTEGER: 760 case IES_OFFSET: 761 case IES_REGISTER: 762 case IES_RPAREN: 763 if (BracCount-- != 1) 764 return true; 765 State = IES_RBRAC; 766 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) { 767 // If we already have a BaseReg, then assume this is the IndexReg with 768 // no explicit scale. 769 if (!BaseReg) { 770 BaseReg = TmpReg; 771 } else { 772 assert (!IndexReg && "BaseReg/IndexReg already set!"); 773 IndexReg = TmpReg; 774 Scale = 0; 775 } 776 } 777 break; 778 } 779 PrevState = CurrState; 780 return false; 781 } 782 void onLParen() { 783 IntelExprState CurrState = State; 784 switch (State) { 785 default: 786 State = IES_ERROR; 787 break; 788 case IES_PLUS: 789 case IES_MINUS: 790 case IES_NOT: 791 case IES_OR: 792 case IES_XOR: 793 case IES_AND: 794 case IES_LSHIFT: 795 case IES_RSHIFT: 796 case IES_MULTIPLY: 797 case IES_DIVIDE: 798 case IES_MOD: 799 case IES_LPAREN: 800 case IES_INIT: 801 case IES_LBRAC: 802 State = IES_LPAREN; 803 IC.pushOperator(IC_LPAREN); 804 break; 805 } 806 PrevState = CurrState; 807 } 808 void onRParen() { 809 PrevState = State; 810 switch (State) { 811 default: 812 State = IES_ERROR; 813 break; 814 case IES_INTEGER: 815 case IES_OFFSET: 816 case IES_REGISTER: 817 case IES_RPAREN: 818 State = IES_RPAREN; 819 IC.pushOperator(IC_RPAREN); 820 break; 821 } 822 } 823 bool onOffset(const MCExpr *Val, SMLoc OffsetLoc, StringRef ID, 824 const InlineAsmIdentifierInfo &IDInfo, bool ParsingMSInlineAsm, 825 StringRef &ErrMsg) { 826 PrevState = State; 827 switch (State) { 828 default: 829 ErrMsg = "unexpected offset operator expression"; 830 return true; 831 case IES_PLUS: 832 case IES_INIT: 833 case IES_LBRAC: 834 if (setSymRef(Val, ID, ErrMsg)) 835 return true; 836 OffsetOperator = true; 837 OffsetOperatorLoc = OffsetLoc; 838 State = IES_OFFSET; 839 // As we cannot yet resolve the actual value (offset), we retain 840 // the requested semantics by pushing a '0' to the operands stack 841 IC.pushOperand(IC_IMM); 842 if (ParsingMSInlineAsm) { 843 Info = IDInfo; 844 } 845 break; 846 } 847 return false; 848 } 849 }; 850 851 bool Error(SMLoc L, const Twine &Msg, SMRange Range = None, 852 bool MatchingInlineAsm = false) { 853 MCAsmParser &Parser = getParser(); 854 if (MatchingInlineAsm) { 855 if (!getLexer().isAtStartOfStatement()) 856 Parser.eatToEndOfStatement(); 857 return false; 858 } 859 return Parser.Error(L, Msg, Range); 860 } 861 862 std::nullptr_t ErrorOperand(SMLoc Loc, StringRef Msg, SMRange R = SMRange()) { 863 Error(Loc, Msg, R); 864 return nullptr; 865 } 866 867 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc, 868 bool RestoreOnFailure); 869 870 std::unique_ptr<X86Operand> DefaultMemSIOperand(SMLoc Loc); 871 std::unique_ptr<X86Operand> DefaultMemDIOperand(SMLoc Loc); 872 bool IsSIReg(unsigned Reg); 873 unsigned GetSIDIForRegClass(unsigned RegClassID, unsigned Reg, bool IsSIReg); 874 void 875 AddDefaultSrcDestOperands(OperandVector &Operands, 876 std::unique_ptr<llvm::MCParsedAsmOperand> &&Src, 877 std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst); 878 bool VerifyAndAdjustOperands(OperandVector &OrigOperands, 879 OperandVector &FinalOperands); 880 std::unique_ptr<X86Operand> ParseOperand(); 881 std::unique_ptr<X86Operand> ParseATTOperand(); 882 std::unique_ptr<X86Operand> ParseIntelOperand(); 883 bool ParseIntelOffsetOperator(const MCExpr *&Val, StringRef &ID, 884 InlineAsmIdentifierInfo &Info, SMLoc &End); 885 bool ParseIntelDotOperator(IntelExprStateMachine &SM, SMLoc &End); 886 unsigned IdentifyIntelInlineAsmOperator(StringRef Name); 887 unsigned ParseIntelInlineAsmOperator(unsigned OpKind); 888 std::unique_ptr<X86Operand> ParseRoundingModeOp(SMLoc Start); 889 bool ParseIntelNamedOperator(StringRef Name, IntelExprStateMachine &SM, 890 bool &ParseError, SMLoc &End); 891 void RewriteIntelExpression(IntelExprStateMachine &SM, SMLoc Start, 892 SMLoc End); 893 bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End); 894 bool ParseIntelInlineAsmIdentifier(const MCExpr *&Val, StringRef &Identifier, 895 InlineAsmIdentifierInfo &Info, 896 bool IsUnevaluatedOperand, SMLoc &End, 897 bool IsParsingOffsetOperator = false); 898 899 std::unique_ptr<X86Operand> ParseMemOperand(unsigned SegReg, 900 const MCExpr *&Disp, 901 const SMLoc &StartLoc, 902 SMLoc &EndLoc); 903 904 X86::CondCode ParseConditionCode(StringRef CCode); 905 906 bool ParseIntelMemoryOperandSize(unsigned &Size); 907 std::unique_ptr<X86Operand> 908 CreateMemForMSInlineAsm(unsigned SegReg, const MCExpr *Disp, unsigned BaseReg, 909 unsigned IndexReg, unsigned Scale, SMLoc Start, 910 SMLoc End, unsigned Size, StringRef Identifier, 911 const InlineAsmIdentifierInfo &Info); 912 913 bool parseDirectiveEven(SMLoc L); 914 bool ParseDirectiveCode(StringRef IDVal, SMLoc L); 915 916 /// CodeView FPO data directives. 917 bool parseDirectiveFPOProc(SMLoc L); 918 bool parseDirectiveFPOSetFrame(SMLoc L); 919 bool parseDirectiveFPOPushReg(SMLoc L); 920 bool parseDirectiveFPOStackAlloc(SMLoc L); 921 bool parseDirectiveFPOStackAlign(SMLoc L); 922 bool parseDirectiveFPOEndPrologue(SMLoc L); 923 bool parseDirectiveFPOEndProc(SMLoc L); 924 bool parseDirectiveFPOData(SMLoc L); 925 926 /// SEH directives. 927 bool parseSEHRegisterNumber(unsigned RegClassID, unsigned &RegNo); 928 bool parseDirectiveSEHPushReg(SMLoc); 929 bool parseDirectiveSEHSetFrame(SMLoc); 930 bool parseDirectiveSEHSaveReg(SMLoc); 931 bool parseDirectiveSEHSaveXMM(SMLoc); 932 bool parseDirectiveSEHPushFrame(SMLoc); 933 934 unsigned checkTargetMatchPredicate(MCInst &Inst) override; 935 936 bool validateInstruction(MCInst &Inst, const OperandVector &Ops); 937 bool processInstruction(MCInst &Inst, const OperandVector &Ops); 938 939 // Load Value Injection (LVI) Mitigations for machine code 940 void emitWarningForSpecialLVIInstruction(SMLoc Loc); 941 bool applyLVICFIMitigation(MCInst &Inst); 942 bool applyLVILoadHardeningMitigation(MCInst &Inst, MCStreamer &Out); 943 944 /// Wrapper around MCStreamer::emitInstruction(). Possibly adds 945 /// instrumentation around Inst. 946 void emitInstruction(MCInst &Inst, OperandVector &Operands, MCStreamer &Out); 947 948 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, 949 OperandVector &Operands, MCStreamer &Out, 950 uint64_t &ErrorInfo, 951 bool MatchingInlineAsm) override; 952 953 void MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op, OperandVector &Operands, 954 MCStreamer &Out, bool MatchingInlineAsm); 955 956 bool ErrorMissingFeature(SMLoc IDLoc, const FeatureBitset &MissingFeatures, 957 bool MatchingInlineAsm); 958 959 bool MatchAndEmitATTInstruction(SMLoc IDLoc, unsigned &Opcode, 960 OperandVector &Operands, MCStreamer &Out, 961 uint64_t &ErrorInfo, 962 bool MatchingInlineAsm); 963 964 bool MatchAndEmitIntelInstruction(SMLoc IDLoc, unsigned &Opcode, 965 OperandVector &Operands, MCStreamer &Out, 966 uint64_t &ErrorInfo, 967 bool MatchingInlineAsm); 968 969 bool OmitRegisterFromClobberLists(unsigned RegNo) override; 970 971 /// Parses AVX512 specific operand primitives: masked registers ({%k<NUM>}, {z}) 972 /// and memory broadcasting ({1to<NUM>}) primitives, updating Operands vector if required. 973 /// return false if no parsing errors occurred, true otherwise. 974 bool HandleAVX512Operand(OperandVector &Operands, 975 const MCParsedAsmOperand &Op); 976 977 bool ParseZ(std::unique_ptr<X86Operand> &Z, const SMLoc &StartLoc); 978 979 bool is64BitMode() const { 980 // FIXME: Can tablegen auto-generate this? 981 return getSTI().getFeatureBits()[X86::Mode64Bit]; 982 } 983 bool is32BitMode() const { 984 // FIXME: Can tablegen auto-generate this? 985 return getSTI().getFeatureBits()[X86::Mode32Bit]; 986 } 987 bool is16BitMode() const { 988 // FIXME: Can tablegen auto-generate this? 989 return getSTI().getFeatureBits()[X86::Mode16Bit]; 990 } 991 void SwitchMode(unsigned mode) { 992 MCSubtargetInfo &STI = copySTI(); 993 FeatureBitset AllModes({X86::Mode64Bit, X86::Mode32Bit, X86::Mode16Bit}); 994 FeatureBitset OldMode = STI.getFeatureBits() & AllModes; 995 FeatureBitset FB = ComputeAvailableFeatures( 996 STI.ToggleFeature(OldMode.flip(mode))); 997 setAvailableFeatures(FB); 998 999 assert(FeatureBitset({mode}) == (STI.getFeatureBits() & AllModes)); 1000 } 1001 1002 unsigned getPointerWidth() { 1003 if (is16BitMode()) return 16; 1004 if (is32BitMode()) return 32; 1005 if (is64BitMode()) return 64; 1006 llvm_unreachable("invalid mode"); 1007 } 1008 1009 bool isParsingIntelSyntax() { 1010 return getParser().getAssemblerDialect(); 1011 } 1012 1013 /// @name Auto-generated Matcher Functions 1014 /// { 1015 1016 #define GET_ASSEMBLER_HEADER 1017 #include "X86GenAsmMatcher.inc" 1018 1019 /// } 1020 1021 public: 1022 enum X86MatchResultTy { 1023 Match_Unsupported = FIRST_TARGET_MATCH_RESULT_TY, 1024 #define GET_OPERAND_DIAGNOSTIC_TYPES 1025 #include "X86GenAsmMatcher.inc" 1026 }; 1027 1028 X86AsmParser(const MCSubtargetInfo &sti, MCAsmParser &Parser, 1029 const MCInstrInfo &mii, const MCTargetOptions &Options) 1030 : MCTargetAsmParser(Options, sti, mii), InstInfo(nullptr), 1031 Code16GCC(false) { 1032 1033 Parser.addAliasForDirective(".word", ".2byte"); 1034 1035 // Initialize the set of available features. 1036 setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits())); 1037 } 1038 1039 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override; 1040 OperandMatchResultTy tryParseRegister(unsigned &RegNo, SMLoc &StartLoc, 1041 SMLoc &EndLoc) override; 1042 1043 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override; 1044 1045 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name, 1046 SMLoc NameLoc, OperandVector &Operands) override; 1047 1048 bool ParseDirective(AsmToken DirectiveID) override; 1049 }; 1050 } // end anonymous namespace 1051 1052 /// @name Auto-generated Match Functions 1053 /// { 1054 1055 static unsigned MatchRegisterName(StringRef Name); 1056 1057 /// } 1058 1059 static bool CheckBaseRegAndIndexRegAndScale(unsigned BaseReg, unsigned IndexReg, 1060 unsigned Scale, bool Is64BitMode, 1061 StringRef &ErrMsg) { 1062 // If we have both a base register and an index register make sure they are 1063 // both 64-bit or 32-bit registers. 1064 // To support VSIB, IndexReg can be 128-bit or 256-bit registers. 1065 1066 if (BaseReg != 0 && 1067 !(BaseReg == X86::RIP || BaseReg == X86::EIP || 1068 X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) || 1069 X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) || 1070 X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg))) { 1071 ErrMsg = "invalid base+index expression"; 1072 return true; 1073 } 1074 1075 if (IndexReg != 0 && 1076 !(IndexReg == X86::EIZ || IndexReg == X86::RIZ || 1077 X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) || 1078 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) || 1079 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg) || 1080 X86MCRegisterClasses[X86::VR128XRegClassID].contains(IndexReg) || 1081 X86MCRegisterClasses[X86::VR256XRegClassID].contains(IndexReg) || 1082 X86MCRegisterClasses[X86::VR512RegClassID].contains(IndexReg))) { 1083 ErrMsg = "invalid base+index expression"; 1084 return true; 1085 } 1086 1087 if (((BaseReg == X86::RIP || BaseReg == X86::EIP) && IndexReg != 0) || 1088 IndexReg == X86::EIP || IndexReg == X86::RIP || 1089 IndexReg == X86::ESP || IndexReg == X86::RSP) { 1090 ErrMsg = "invalid base+index expression"; 1091 return true; 1092 } 1093 1094 // Check for use of invalid 16-bit registers. Only BX/BP/SI/DI are allowed, 1095 // and then only in non-64-bit modes. 1096 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) && 1097 (Is64BitMode || (BaseReg != X86::BX && BaseReg != X86::BP && 1098 BaseReg != X86::SI && BaseReg != X86::DI))) { 1099 ErrMsg = "invalid 16-bit base register"; 1100 return true; 1101 } 1102 1103 if (BaseReg == 0 && 1104 X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)) { 1105 ErrMsg = "16-bit memory operand may not include only index register"; 1106 return true; 1107 } 1108 1109 if (BaseReg != 0 && IndexReg != 0) { 1110 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) && 1111 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) || 1112 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) || 1113 IndexReg == X86::EIZ)) { 1114 ErrMsg = "base register is 64-bit, but index register is not"; 1115 return true; 1116 } 1117 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) && 1118 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) || 1119 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg) || 1120 IndexReg == X86::RIZ)) { 1121 ErrMsg = "base register is 32-bit, but index register is not"; 1122 return true; 1123 } 1124 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg)) { 1125 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) || 1126 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) { 1127 ErrMsg = "base register is 16-bit, but index register is not"; 1128 return true; 1129 } 1130 if ((BaseReg != X86::BX && BaseReg != X86::BP) || 1131 (IndexReg != X86::SI && IndexReg != X86::DI)) { 1132 ErrMsg = "invalid 16-bit base/index register combination"; 1133 return true; 1134 } 1135 } 1136 } 1137 1138 // RIP/EIP-relative addressing is only supported in 64-bit mode. 1139 if (!Is64BitMode && BaseReg != 0 && 1140 (BaseReg == X86::RIP || BaseReg == X86::EIP)) { 1141 ErrMsg = "IP-relative addressing requires 64-bit mode"; 1142 return true; 1143 } 1144 1145 return checkScale(Scale, ErrMsg); 1146 } 1147 1148 bool X86AsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc, 1149 SMLoc &EndLoc, bool RestoreOnFailure) { 1150 MCAsmParser &Parser = getParser(); 1151 MCAsmLexer &Lexer = getLexer(); 1152 RegNo = 0; 1153 1154 SmallVector<AsmToken, 5> Tokens; 1155 auto OnFailure = [RestoreOnFailure, &Lexer, &Tokens]() { 1156 if (RestoreOnFailure) { 1157 while (!Tokens.empty()) { 1158 Lexer.UnLex(Tokens.pop_back_val()); 1159 } 1160 } 1161 }; 1162 1163 const AsmToken &PercentTok = Parser.getTok(); 1164 StartLoc = PercentTok.getLoc(); 1165 1166 // If we encounter a %, ignore it. This code handles registers with and 1167 // without the prefix, unprefixed registers can occur in cfi directives. 1168 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent)) { 1169 Tokens.push_back(PercentTok); 1170 Parser.Lex(); // Eat percent token. 1171 } 1172 1173 const AsmToken &Tok = Parser.getTok(); 1174 EndLoc = Tok.getEndLoc(); 1175 1176 if (Tok.isNot(AsmToken::Identifier)) { 1177 OnFailure(); 1178 if (isParsingIntelSyntax()) return true; 1179 return Error(StartLoc, "invalid register name", 1180 SMRange(StartLoc, EndLoc)); 1181 } 1182 1183 RegNo = MatchRegisterName(Tok.getString()); 1184 1185 // If the match failed, try the register name as lowercase. 1186 if (RegNo == 0) 1187 RegNo = MatchRegisterName(Tok.getString().lower()); 1188 1189 // The "flags" and "mxcsr" registers cannot be referenced directly. 1190 // Treat it as an identifier instead. 1191 if (isParsingMSInlineAsm() && isParsingIntelSyntax() && 1192 (RegNo == X86::EFLAGS || RegNo == X86::MXCSR)) 1193 RegNo = 0; 1194 1195 if (!is64BitMode()) { 1196 // FIXME: This should be done using Requires<Not64BitMode> and 1197 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also 1198 // checked. 1199 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a 1200 // REX prefix. 1201 if (RegNo == X86::RIZ || RegNo == X86::RIP || 1202 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) || 1203 X86II::isX86_64NonExtLowByteReg(RegNo) || 1204 X86II::isX86_64ExtendedReg(RegNo)) { 1205 StringRef RegName = Tok.getString(); 1206 OnFailure(); 1207 if (!RestoreOnFailure) { 1208 Parser.Lex(); // Eat register name. 1209 } 1210 return Error(StartLoc, 1211 "register %" + RegName + " is only available in 64-bit mode", 1212 SMRange(StartLoc, EndLoc)); 1213 } 1214 } 1215 1216 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens. 1217 if (RegNo == X86::ST0) { 1218 Tokens.push_back(Tok); 1219 Parser.Lex(); // Eat 'st' 1220 1221 // Check to see if we have '(4)' after %st. 1222 if (Lexer.isNot(AsmToken::LParen)) 1223 return false; 1224 // Lex the paren. 1225 Tokens.push_back(Parser.getTok()); 1226 Parser.Lex(); 1227 1228 const AsmToken &IntTok = Parser.getTok(); 1229 if (IntTok.isNot(AsmToken::Integer)) { 1230 OnFailure(); 1231 return Error(IntTok.getLoc(), "expected stack index"); 1232 } 1233 switch (IntTok.getIntVal()) { 1234 case 0: RegNo = X86::ST0; break; 1235 case 1: RegNo = X86::ST1; break; 1236 case 2: RegNo = X86::ST2; break; 1237 case 3: RegNo = X86::ST3; break; 1238 case 4: RegNo = X86::ST4; break; 1239 case 5: RegNo = X86::ST5; break; 1240 case 6: RegNo = X86::ST6; break; 1241 case 7: RegNo = X86::ST7; break; 1242 default: 1243 OnFailure(); 1244 return Error(IntTok.getLoc(), "invalid stack index"); 1245 } 1246 1247 // Lex IntTok 1248 Tokens.push_back(IntTok); 1249 Parser.Lex(); 1250 if (Lexer.isNot(AsmToken::RParen)) { 1251 OnFailure(); 1252 return Error(Parser.getTok().getLoc(), "expected ')'"); 1253 } 1254 1255 EndLoc = Parser.getTok().getEndLoc(); 1256 Parser.Lex(); // Eat ')' 1257 return false; 1258 } 1259 1260 EndLoc = Parser.getTok().getEndLoc(); 1261 1262 // If this is "db[0-15]", match it as an alias 1263 // for dr[0-15]. 1264 if (RegNo == 0 && Tok.getString().startswith("db")) { 1265 if (Tok.getString().size() == 3) { 1266 switch (Tok.getString()[2]) { 1267 case '0': RegNo = X86::DR0; break; 1268 case '1': RegNo = X86::DR1; break; 1269 case '2': RegNo = X86::DR2; break; 1270 case '3': RegNo = X86::DR3; break; 1271 case '4': RegNo = X86::DR4; break; 1272 case '5': RegNo = X86::DR5; break; 1273 case '6': RegNo = X86::DR6; break; 1274 case '7': RegNo = X86::DR7; break; 1275 case '8': RegNo = X86::DR8; break; 1276 case '9': RegNo = X86::DR9; break; 1277 } 1278 } else if (Tok.getString().size() == 4 && Tok.getString()[2] == '1') { 1279 switch (Tok.getString()[3]) { 1280 case '0': RegNo = X86::DR10; break; 1281 case '1': RegNo = X86::DR11; break; 1282 case '2': RegNo = X86::DR12; break; 1283 case '3': RegNo = X86::DR13; break; 1284 case '4': RegNo = X86::DR14; break; 1285 case '5': RegNo = X86::DR15; break; 1286 } 1287 } 1288 1289 if (RegNo != 0) { 1290 EndLoc = Parser.getTok().getEndLoc(); 1291 Parser.Lex(); // Eat it. 1292 return false; 1293 } 1294 } 1295 1296 if (RegNo == 0) { 1297 OnFailure(); 1298 if (isParsingIntelSyntax()) return true; 1299 return Error(StartLoc, "invalid register name", 1300 SMRange(StartLoc, EndLoc)); 1301 } 1302 1303 Parser.Lex(); // Eat identifier token. 1304 return false; 1305 } 1306 1307 bool X86AsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc, 1308 SMLoc &EndLoc) { 1309 return ParseRegister(RegNo, StartLoc, EndLoc, /*RestoreOnFailure=*/false); 1310 } 1311 1312 OperandMatchResultTy X86AsmParser::tryParseRegister(unsigned &RegNo, 1313 SMLoc &StartLoc, 1314 SMLoc &EndLoc) { 1315 bool Result = 1316 ParseRegister(RegNo, StartLoc, EndLoc, /*RestoreOnFailure=*/true); 1317 bool PendingErrors = getParser().hasPendingError(); 1318 getParser().clearPendingErrors(); 1319 if (PendingErrors) 1320 return MatchOperand_ParseFail; 1321 if (Result) 1322 return MatchOperand_NoMatch; 1323 return MatchOperand_Success; 1324 } 1325 1326 std::unique_ptr<X86Operand> X86AsmParser::DefaultMemSIOperand(SMLoc Loc) { 1327 bool Parse32 = is32BitMode() || Code16GCC; 1328 unsigned Basereg = is64BitMode() ? X86::RSI : (Parse32 ? X86::ESI : X86::SI); 1329 const MCExpr *Disp = MCConstantExpr::create(0, getContext()); 1330 return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp, 1331 /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1, 1332 Loc, Loc, 0); 1333 } 1334 1335 std::unique_ptr<X86Operand> X86AsmParser::DefaultMemDIOperand(SMLoc Loc) { 1336 bool Parse32 = is32BitMode() || Code16GCC; 1337 unsigned Basereg = is64BitMode() ? X86::RDI : (Parse32 ? X86::EDI : X86::DI); 1338 const MCExpr *Disp = MCConstantExpr::create(0, getContext()); 1339 return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp, 1340 /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1, 1341 Loc, Loc, 0); 1342 } 1343 1344 bool X86AsmParser::IsSIReg(unsigned Reg) { 1345 switch (Reg) { 1346 default: llvm_unreachable("Only (R|E)SI and (R|E)DI are expected!"); 1347 case X86::RSI: 1348 case X86::ESI: 1349 case X86::SI: 1350 return true; 1351 case X86::RDI: 1352 case X86::EDI: 1353 case X86::DI: 1354 return false; 1355 } 1356 } 1357 1358 unsigned X86AsmParser::GetSIDIForRegClass(unsigned RegClassID, unsigned Reg, 1359 bool IsSIReg) { 1360 switch (RegClassID) { 1361 default: llvm_unreachable("Unexpected register class"); 1362 case X86::GR64RegClassID: 1363 return IsSIReg ? X86::RSI : X86::RDI; 1364 case X86::GR32RegClassID: 1365 return IsSIReg ? X86::ESI : X86::EDI; 1366 case X86::GR16RegClassID: 1367 return IsSIReg ? X86::SI : X86::DI; 1368 } 1369 } 1370 1371 void X86AsmParser::AddDefaultSrcDestOperands( 1372 OperandVector& Operands, std::unique_ptr<llvm::MCParsedAsmOperand> &&Src, 1373 std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst) { 1374 if (isParsingIntelSyntax()) { 1375 Operands.push_back(std::move(Dst)); 1376 Operands.push_back(std::move(Src)); 1377 } 1378 else { 1379 Operands.push_back(std::move(Src)); 1380 Operands.push_back(std::move(Dst)); 1381 } 1382 } 1383 1384 bool X86AsmParser::VerifyAndAdjustOperands(OperandVector &OrigOperands, 1385 OperandVector &FinalOperands) { 1386 1387 if (OrigOperands.size() > 1) { 1388 // Check if sizes match, OrigOperands also contains the instruction name 1389 assert(OrigOperands.size() == FinalOperands.size() + 1 && 1390 "Operand size mismatch"); 1391 1392 SmallVector<std::pair<SMLoc, std::string>, 2> Warnings; 1393 // Verify types match 1394 int RegClassID = -1; 1395 for (unsigned int i = 0; i < FinalOperands.size(); ++i) { 1396 X86Operand &OrigOp = static_cast<X86Operand &>(*OrigOperands[i + 1]); 1397 X86Operand &FinalOp = static_cast<X86Operand &>(*FinalOperands[i]); 1398 1399 if (FinalOp.isReg() && 1400 (!OrigOp.isReg() || FinalOp.getReg() != OrigOp.getReg())) 1401 // Return false and let a normal complaint about bogus operands happen 1402 return false; 1403 1404 if (FinalOp.isMem()) { 1405 1406 if (!OrigOp.isMem()) 1407 // Return false and let a normal complaint about bogus operands happen 1408 return false; 1409 1410 unsigned OrigReg = OrigOp.Mem.BaseReg; 1411 unsigned FinalReg = FinalOp.Mem.BaseReg; 1412 1413 // If we've already encounterd a register class, make sure all register 1414 // bases are of the same register class 1415 if (RegClassID != -1 && 1416 !X86MCRegisterClasses[RegClassID].contains(OrigReg)) { 1417 return Error(OrigOp.getStartLoc(), 1418 "mismatching source and destination index registers"); 1419 } 1420 1421 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(OrigReg)) 1422 RegClassID = X86::GR64RegClassID; 1423 else if (X86MCRegisterClasses[X86::GR32RegClassID].contains(OrigReg)) 1424 RegClassID = X86::GR32RegClassID; 1425 else if (X86MCRegisterClasses[X86::GR16RegClassID].contains(OrigReg)) 1426 RegClassID = X86::GR16RegClassID; 1427 else 1428 // Unexpected register class type 1429 // Return false and let a normal complaint about bogus operands happen 1430 return false; 1431 1432 bool IsSI = IsSIReg(FinalReg); 1433 FinalReg = GetSIDIForRegClass(RegClassID, FinalReg, IsSI); 1434 1435 if (FinalReg != OrigReg) { 1436 std::string RegName = IsSI ? "ES:(R|E)SI" : "ES:(R|E)DI"; 1437 Warnings.push_back(std::make_pair( 1438 OrigOp.getStartLoc(), 1439 "memory operand is only for determining the size, " + RegName + 1440 " will be used for the location")); 1441 } 1442 1443 FinalOp.Mem.Size = OrigOp.Mem.Size; 1444 FinalOp.Mem.SegReg = OrigOp.Mem.SegReg; 1445 FinalOp.Mem.BaseReg = FinalReg; 1446 } 1447 } 1448 1449 // Produce warnings only if all the operands passed the adjustment - prevent 1450 // legal cases like "movsd (%rax), %xmm0" mistakenly produce warnings 1451 for (auto &WarningMsg : Warnings) { 1452 Warning(WarningMsg.first, WarningMsg.second); 1453 } 1454 1455 // Remove old operands 1456 for (unsigned int i = 0; i < FinalOperands.size(); ++i) 1457 OrigOperands.pop_back(); 1458 } 1459 // OrigOperands.append(FinalOperands.begin(), FinalOperands.end()); 1460 for (unsigned int i = 0; i < FinalOperands.size(); ++i) 1461 OrigOperands.push_back(std::move(FinalOperands[i])); 1462 1463 return false; 1464 } 1465 1466 std::unique_ptr<X86Operand> X86AsmParser::ParseOperand() { 1467 if (isParsingIntelSyntax()) 1468 return ParseIntelOperand(); 1469 return ParseATTOperand(); 1470 } 1471 1472 std::unique_ptr<X86Operand> X86AsmParser::CreateMemForMSInlineAsm( 1473 unsigned SegReg, const MCExpr *Disp, unsigned BaseReg, unsigned IndexReg, 1474 unsigned Scale, SMLoc Start, SMLoc End, unsigned Size, StringRef Identifier, 1475 const InlineAsmIdentifierInfo &Info) { 1476 // If we found a decl other than a VarDecl, then assume it is a FuncDecl or 1477 // some other label reference. 1478 if (Info.isKind(InlineAsmIdentifierInfo::IK_Label)) { 1479 // Insert an explicit size if the user didn't have one. 1480 if (!Size) { 1481 Size = getPointerWidth(); 1482 InstInfo->AsmRewrites->emplace_back(AOK_SizeDirective, Start, 1483 /*Len=*/0, Size); 1484 } 1485 // Create an absolute memory reference in order to match against 1486 // instructions taking a PC relative operand. 1487 return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End, Size, 1488 Identifier, Info.Label.Decl); 1489 } 1490 // We either have a direct symbol reference, or an offset from a symbol. The 1491 // parser always puts the symbol on the LHS, so look there for size 1492 // calculation purposes. 1493 unsigned FrontendSize = 0; 1494 void *Decl = nullptr; 1495 bool IsGlobalLV = false; 1496 if (Info.isKind(InlineAsmIdentifierInfo::IK_Var)) { 1497 // Size is in terms of bits in this context. 1498 FrontendSize = Info.Var.Type * 8; 1499 Decl = Info.Var.Decl; 1500 IsGlobalLV = Info.Var.IsGlobalLV; 1501 } 1502 // It is widely common for MS InlineAsm to use a global variable and one/two 1503 // registers in a mmory expression, and though unaccessible via rip/eip. 1504 if (IsGlobalLV && (BaseReg || IndexReg)) { 1505 return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End); 1506 // Otherwise, we set the base register to a non-zero value 1507 // if we don't know the actual value at this time. This is necessary to 1508 // get the matching correct in some cases. 1509 } else { 1510 BaseReg = BaseReg ? BaseReg : 1; 1511 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg, 1512 IndexReg, Scale, Start, End, Size, Identifier, 1513 Decl, FrontendSize); 1514 } 1515 } 1516 1517 // Some binary bitwise operators have a named synonymous 1518 // Query a candidate string for being such a named operator 1519 // and if so - invoke the appropriate handler 1520 bool X86AsmParser::ParseIntelNamedOperator(StringRef Name, 1521 IntelExprStateMachine &SM, 1522 bool &ParseError, SMLoc &End) { 1523 // A named operator should be either lower or upper case, but not a mix 1524 if (Name.compare(Name.lower()) && Name.compare(Name.upper())) 1525 return false; 1526 if (Name.equals_lower("not")) { 1527 SM.onNot(); 1528 } else if (Name.equals_lower("or")) { 1529 SM.onOr(); 1530 } else if (Name.equals_lower("shl")) { 1531 SM.onLShift(); 1532 } else if (Name.equals_lower("shr")) { 1533 SM.onRShift(); 1534 } else if (Name.equals_lower("xor")) { 1535 SM.onXor(); 1536 } else if (Name.equals_lower("and")) { 1537 SM.onAnd(); 1538 } else if (Name.equals_lower("mod")) { 1539 SM.onMod(); 1540 } else if (Name.equals_lower("offset")) { 1541 SMLoc OffsetLoc = getTok().getLoc(); 1542 const MCExpr *Val = nullptr; 1543 StringRef ID; 1544 InlineAsmIdentifierInfo Info; 1545 ParseError = ParseIntelOffsetOperator(Val, ID, Info, End); 1546 if (ParseError) 1547 return true; 1548 StringRef ErrMsg; 1549 ParseError = 1550 SM.onOffset(Val, OffsetLoc, ID, Info, isParsingMSInlineAsm(), ErrMsg); 1551 if (ParseError) 1552 return Error(SMLoc::getFromPointer(Name.data()), ErrMsg); 1553 } else { 1554 return false; 1555 } 1556 if (!Name.equals_lower("offset")) 1557 End = consumeToken(); 1558 return true; 1559 } 1560 1561 bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) { 1562 MCAsmParser &Parser = getParser(); 1563 const AsmToken &Tok = Parser.getTok(); 1564 StringRef ErrMsg; 1565 1566 AsmToken::TokenKind PrevTK = AsmToken::Error; 1567 bool Done = false; 1568 while (!Done) { 1569 bool UpdateLocLex = true; 1570 AsmToken::TokenKind TK = getLexer().getKind(); 1571 1572 switch (TK) { 1573 default: 1574 if ((Done = SM.isValidEndState())) 1575 break; 1576 return Error(Tok.getLoc(), "unknown token in expression"); 1577 case AsmToken::EndOfStatement: 1578 Done = true; 1579 break; 1580 case AsmToken::Real: 1581 // DotOperator: [ebx].0 1582 UpdateLocLex = false; 1583 if (ParseIntelDotOperator(SM, End)) 1584 return true; 1585 break; 1586 case AsmToken::At: 1587 case AsmToken::String: 1588 case AsmToken::Identifier: { 1589 SMLoc IdentLoc = Tok.getLoc(); 1590 StringRef Identifier = Tok.getString(); 1591 UpdateLocLex = false; 1592 // Register 1593 unsigned Reg; 1594 if (Tok.is(AsmToken::Identifier) && !ParseRegister(Reg, IdentLoc, End)) { 1595 if (SM.onRegister(Reg, ErrMsg)) 1596 return Error(Tok.getLoc(), ErrMsg); 1597 break; 1598 } 1599 // Operator synonymous ("not", "or" etc.) 1600 bool ParseError = false; 1601 if (ParseIntelNamedOperator(Identifier, SM, ParseError, End)) { 1602 if (ParseError) 1603 return true; 1604 break; 1605 } 1606 // Symbol reference, when parsing assembly content 1607 InlineAsmIdentifierInfo Info; 1608 const MCExpr *Val; 1609 if (!isParsingMSInlineAsm()) { 1610 if (getParser().parsePrimaryExpr(Val, End)) { 1611 return Error(Tok.getLoc(), "Unexpected identifier!"); 1612 } else if (SM.onIdentifierExpr(Val, Identifier, Info, false, ErrMsg)) { 1613 return Error(IdentLoc, ErrMsg); 1614 } else 1615 break; 1616 } 1617 // MS InlineAsm operators (TYPE/LENGTH/SIZE) 1618 if (unsigned OpKind = IdentifyIntelInlineAsmOperator(Identifier)) { 1619 if (int64_t Val = ParseIntelInlineAsmOperator(OpKind)) { 1620 if (SM.onInteger(Val, ErrMsg)) 1621 return Error(IdentLoc, ErrMsg); 1622 } else 1623 return true; 1624 break; 1625 } 1626 // MS Dot Operator expression 1627 if (Identifier.count('.') && PrevTK == AsmToken::RBrac) { 1628 if (ParseIntelDotOperator(SM, End)) 1629 return true; 1630 break; 1631 } 1632 // MS InlineAsm identifier 1633 // Call parseIdentifier() to combine @ with the identifier behind it. 1634 if (TK == AsmToken::At && Parser.parseIdentifier(Identifier)) 1635 return Error(IdentLoc, "expected identifier"); 1636 if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info, false, End)) 1637 return true; 1638 else if (SM.onIdentifierExpr(Val, Identifier, Info, true, ErrMsg)) 1639 return Error(IdentLoc, ErrMsg); 1640 break; 1641 } 1642 case AsmToken::Integer: { 1643 // Look for 'b' or 'f' following an Integer as a directional label 1644 SMLoc Loc = getTok().getLoc(); 1645 int64_t IntVal = getTok().getIntVal(); 1646 End = consumeToken(); 1647 UpdateLocLex = false; 1648 if (getLexer().getKind() == AsmToken::Identifier) { 1649 StringRef IDVal = getTok().getString(); 1650 if (IDVal == "f" || IDVal == "b") { 1651 MCSymbol *Sym = 1652 getContext().getDirectionalLocalSymbol(IntVal, IDVal == "b"); 1653 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1654 const MCExpr *Val = 1655 MCSymbolRefExpr::create(Sym, Variant, getContext()); 1656 if (IDVal == "b" && Sym->isUndefined()) 1657 return Error(Loc, "invalid reference to undefined symbol"); 1658 StringRef Identifier = Sym->getName(); 1659 InlineAsmIdentifierInfo Info; 1660 if (SM.onIdentifierExpr(Val, Identifier, Info, isParsingMSInlineAsm(), 1661 ErrMsg)) 1662 return Error(Loc, ErrMsg); 1663 End = consumeToken(); 1664 } else { 1665 if (SM.onInteger(IntVal, ErrMsg)) 1666 return Error(Loc, ErrMsg); 1667 } 1668 } else { 1669 if (SM.onInteger(IntVal, ErrMsg)) 1670 return Error(Loc, ErrMsg); 1671 } 1672 break; 1673 } 1674 case AsmToken::Plus: 1675 if (SM.onPlus(ErrMsg)) 1676 return Error(getTok().getLoc(), ErrMsg); 1677 break; 1678 case AsmToken::Minus: 1679 if (SM.onMinus(ErrMsg)) 1680 return Error(getTok().getLoc(), ErrMsg); 1681 break; 1682 case AsmToken::Tilde: SM.onNot(); break; 1683 case AsmToken::Star: SM.onStar(); break; 1684 case AsmToken::Slash: SM.onDivide(); break; 1685 case AsmToken::Percent: SM.onMod(); break; 1686 case AsmToken::Pipe: SM.onOr(); break; 1687 case AsmToken::Caret: SM.onXor(); break; 1688 case AsmToken::Amp: SM.onAnd(); break; 1689 case AsmToken::LessLess: 1690 SM.onLShift(); break; 1691 case AsmToken::GreaterGreater: 1692 SM.onRShift(); break; 1693 case AsmToken::LBrac: 1694 if (SM.onLBrac()) 1695 return Error(Tok.getLoc(), "unexpected bracket encountered"); 1696 break; 1697 case AsmToken::RBrac: 1698 if (SM.onRBrac()) 1699 return Error(Tok.getLoc(), "unexpected bracket encountered"); 1700 break; 1701 case AsmToken::LParen: SM.onLParen(); break; 1702 case AsmToken::RParen: SM.onRParen(); break; 1703 } 1704 if (SM.hadError()) 1705 return Error(Tok.getLoc(), "unknown token in expression"); 1706 1707 if (!Done && UpdateLocLex) 1708 End = consumeToken(); 1709 1710 PrevTK = TK; 1711 } 1712 return false; 1713 } 1714 1715 void X86AsmParser::RewriteIntelExpression(IntelExprStateMachine &SM, 1716 SMLoc Start, SMLoc End) { 1717 SMLoc Loc = Start; 1718 unsigned ExprLen = End.getPointer() - Start.getPointer(); 1719 // Skip everything before a symbol displacement (if we have one) 1720 if (SM.getSym() && !SM.isOffsetOperator()) { 1721 StringRef SymName = SM.getSymName(); 1722 if (unsigned Len = SymName.data() - Start.getPointer()) 1723 InstInfo->AsmRewrites->emplace_back(AOK_Skip, Start, Len); 1724 Loc = SMLoc::getFromPointer(SymName.data() + SymName.size()); 1725 ExprLen = End.getPointer() - (SymName.data() + SymName.size()); 1726 // If we have only a symbol than there's no need for complex rewrite, 1727 // simply skip everything after it 1728 if (!(SM.getBaseReg() || SM.getIndexReg() || SM.getImm())) { 1729 if (ExprLen) 1730 InstInfo->AsmRewrites->emplace_back(AOK_Skip, Loc, ExprLen); 1731 return; 1732 } 1733 } 1734 // Build an Intel Expression rewrite 1735 StringRef BaseRegStr; 1736 StringRef IndexRegStr; 1737 StringRef OffsetNameStr; 1738 if (SM.getBaseReg()) 1739 BaseRegStr = X86IntelInstPrinter::getRegisterName(SM.getBaseReg()); 1740 if (SM.getIndexReg()) 1741 IndexRegStr = X86IntelInstPrinter::getRegisterName(SM.getIndexReg()); 1742 if (SM.isOffsetOperator()) 1743 OffsetNameStr = SM.getSymName(); 1744 // Emit it 1745 IntelExpr Expr(BaseRegStr, IndexRegStr, SM.getScale(), OffsetNameStr, 1746 SM.getImm(), SM.isMemExpr()); 1747 InstInfo->AsmRewrites->emplace_back(Loc, ExprLen, Expr); 1748 } 1749 1750 // Inline assembly may use variable names with namespace alias qualifiers. 1751 bool X86AsmParser::ParseIntelInlineAsmIdentifier( 1752 const MCExpr *&Val, StringRef &Identifier, InlineAsmIdentifierInfo &Info, 1753 bool IsUnevaluatedOperand, SMLoc &End, bool IsParsingOffsetOperator) { 1754 MCAsmParser &Parser = getParser(); 1755 assert(isParsingMSInlineAsm() && "Expected to be parsing inline assembly."); 1756 Val = nullptr; 1757 1758 StringRef LineBuf(Identifier.data()); 1759 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand); 1760 1761 const AsmToken &Tok = Parser.getTok(); 1762 SMLoc Loc = Tok.getLoc(); 1763 1764 // Advance the token stream until the end of the current token is 1765 // after the end of what the frontend claimed. 1766 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size(); 1767 do { 1768 End = Tok.getEndLoc(); 1769 getLexer().Lex(); 1770 } while (End.getPointer() < EndPtr); 1771 Identifier = LineBuf; 1772 1773 // The frontend should end parsing on an assembler token boundary, unless it 1774 // failed parsing. 1775 assert((End.getPointer() == EndPtr || 1776 Info.isKind(InlineAsmIdentifierInfo::IK_Invalid)) && 1777 "frontend claimed part of a token?"); 1778 1779 // If the identifier lookup was unsuccessful, assume that we are dealing with 1780 // a label. 1781 if (Info.isKind(InlineAsmIdentifierInfo::IK_Invalid)) { 1782 StringRef InternalName = 1783 SemaCallback->LookupInlineAsmLabel(Identifier, getSourceManager(), 1784 Loc, false); 1785 assert(InternalName.size() && "We should have an internal name here."); 1786 // Push a rewrite for replacing the identifier name with the internal name, 1787 // unless we are parsing the operand of an offset operator 1788 if (!IsParsingOffsetOperator) 1789 InstInfo->AsmRewrites->emplace_back(AOK_Label, Loc, Identifier.size(), 1790 InternalName); 1791 else 1792 Identifier = InternalName; 1793 } else if (Info.isKind(InlineAsmIdentifierInfo::IK_EnumVal)) 1794 return false; 1795 // Create the symbol reference. 1796 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier); 1797 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None; 1798 Val = MCSymbolRefExpr::create(Sym, Variant, getParser().getContext()); 1799 return false; 1800 } 1801 1802 //ParseRoundingModeOp - Parse AVX-512 rounding mode operand 1803 std::unique_ptr<X86Operand> 1804 X86AsmParser::ParseRoundingModeOp(SMLoc Start) { 1805 MCAsmParser &Parser = getParser(); 1806 const AsmToken &Tok = Parser.getTok(); 1807 // Eat "{" and mark the current place. 1808 const SMLoc consumedToken = consumeToken(); 1809 if (Tok.isNot(AsmToken::Identifier)) 1810 return ErrorOperand(Tok.getLoc(), "Expected an identifier after {"); 1811 if (Tok.getIdentifier().startswith("r")){ 1812 int rndMode = StringSwitch<int>(Tok.getIdentifier()) 1813 .Case("rn", X86::STATIC_ROUNDING::TO_NEAREST_INT) 1814 .Case("rd", X86::STATIC_ROUNDING::TO_NEG_INF) 1815 .Case("ru", X86::STATIC_ROUNDING::TO_POS_INF) 1816 .Case("rz", X86::STATIC_ROUNDING::TO_ZERO) 1817 .Default(-1); 1818 if (-1 == rndMode) 1819 return ErrorOperand(Tok.getLoc(), "Invalid rounding mode."); 1820 Parser.Lex(); // Eat "r*" of r*-sae 1821 if (!getLexer().is(AsmToken::Minus)) 1822 return ErrorOperand(Tok.getLoc(), "Expected - at this point"); 1823 Parser.Lex(); // Eat "-" 1824 Parser.Lex(); // Eat the sae 1825 if (!getLexer().is(AsmToken::RCurly)) 1826 return ErrorOperand(Tok.getLoc(), "Expected } at this point"); 1827 SMLoc End = Tok.getEndLoc(); 1828 Parser.Lex(); // Eat "}" 1829 const MCExpr *RndModeOp = 1830 MCConstantExpr::create(rndMode, Parser.getContext()); 1831 return X86Operand::CreateImm(RndModeOp, Start, End); 1832 } 1833 if(Tok.getIdentifier().equals("sae")){ 1834 Parser.Lex(); // Eat the sae 1835 if (!getLexer().is(AsmToken::RCurly)) 1836 return ErrorOperand(Tok.getLoc(), "Expected } at this point"); 1837 Parser.Lex(); // Eat "}" 1838 return X86Operand::CreateToken("{sae}", consumedToken); 1839 } 1840 return ErrorOperand(Tok.getLoc(), "unknown token in expression"); 1841 } 1842 1843 /// Parse the '.' operator. 1844 bool X86AsmParser::ParseIntelDotOperator(IntelExprStateMachine &SM, SMLoc &End) { 1845 const AsmToken &Tok = getTok(); 1846 unsigned Offset; 1847 1848 // Drop the optional '.'. 1849 StringRef DotDispStr = Tok.getString(); 1850 if (DotDispStr.startswith(".")) 1851 DotDispStr = DotDispStr.drop_front(1); 1852 1853 // .Imm gets lexed as a real. 1854 if (Tok.is(AsmToken::Real)) { 1855 APInt DotDisp; 1856 DotDispStr.getAsInteger(10, DotDisp); 1857 Offset = DotDisp.getZExtValue(); 1858 } else if (isParsingMSInlineAsm() && Tok.is(AsmToken::Identifier)) { 1859 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.'); 1860 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second, 1861 Offset)) 1862 return Error(Tok.getLoc(), "Unable to lookup field reference!"); 1863 } else 1864 return Error(Tok.getLoc(), "Unexpected token type!"); 1865 1866 // Eat the DotExpression and update End 1867 End = SMLoc::getFromPointer(DotDispStr.data()); 1868 const char *DotExprEndLoc = DotDispStr.data() + DotDispStr.size(); 1869 while (Tok.getLoc().getPointer() < DotExprEndLoc) 1870 Lex(); 1871 SM.addImm(Offset); 1872 return false; 1873 } 1874 1875 /// Parse the 'offset' operator. 1876 /// This operator is used to specify the location of a given operand 1877 bool X86AsmParser::ParseIntelOffsetOperator(const MCExpr *&Val, StringRef &ID, 1878 InlineAsmIdentifierInfo &Info, 1879 SMLoc &End) { 1880 // Eat offset, mark start of identifier. 1881 SMLoc Start = Lex().getLoc(); 1882 ID = getTok().getString(); 1883 if (!isParsingMSInlineAsm()) { 1884 if ((getTok().isNot(AsmToken::Identifier) && 1885 getTok().isNot(AsmToken::String)) || 1886 getParser().parsePrimaryExpr(Val, End)) 1887 return Error(Start, "unexpected token!"); 1888 } else if (ParseIntelInlineAsmIdentifier(Val, ID, Info, false, End, true)) { 1889 return Error(Start, "unable to lookup expression"); 1890 } else if (Info.isKind(InlineAsmIdentifierInfo::IK_EnumVal)) { 1891 return Error(Start, "offset operator cannot yet handle constants"); 1892 } 1893 return false; 1894 } 1895 1896 // Query a candidate string for being an Intel assembly operator 1897 // Report back its kind, or IOK_INVALID if does not evaluated as a known one 1898 unsigned X86AsmParser::IdentifyIntelInlineAsmOperator(StringRef Name) { 1899 return StringSwitch<unsigned>(Name) 1900 .Cases("TYPE","type",IOK_TYPE) 1901 .Cases("SIZE","size",IOK_SIZE) 1902 .Cases("LENGTH","length",IOK_LENGTH) 1903 .Default(IOK_INVALID); 1904 } 1905 1906 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator 1907 /// returns the number of elements in an array. It returns the value 1 for 1908 /// non-array variables. The SIZE operator returns the size of a C or C++ 1909 /// variable. A variable's size is the product of its LENGTH and TYPE. The 1910 /// TYPE operator returns the size of a C or C++ type or variable. If the 1911 /// variable is an array, TYPE returns the size of a single element. 1912 unsigned X86AsmParser::ParseIntelInlineAsmOperator(unsigned OpKind) { 1913 MCAsmParser &Parser = getParser(); 1914 const AsmToken &Tok = Parser.getTok(); 1915 Parser.Lex(); // Eat operator. 1916 1917 const MCExpr *Val = nullptr; 1918 InlineAsmIdentifierInfo Info; 1919 SMLoc Start = Tok.getLoc(), End; 1920 StringRef Identifier = Tok.getString(); 1921 if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info, 1922 /*Unevaluated=*/true, End)) 1923 return 0; 1924 1925 if (!Info.isKind(InlineAsmIdentifierInfo::IK_Var)) { 1926 Error(Start, "unable to lookup expression"); 1927 return 0; 1928 } 1929 1930 unsigned CVal = 0; 1931 switch(OpKind) { 1932 default: llvm_unreachable("Unexpected operand kind!"); 1933 case IOK_LENGTH: CVal = Info.Var.Length; break; 1934 case IOK_SIZE: CVal = Info.Var.Size; break; 1935 case IOK_TYPE: CVal = Info.Var.Type; break; 1936 } 1937 1938 return CVal; 1939 } 1940 1941 bool X86AsmParser::ParseIntelMemoryOperandSize(unsigned &Size) { 1942 Size = StringSwitch<unsigned>(getTok().getString()) 1943 .Cases("BYTE", "byte", 8) 1944 .Cases("WORD", "word", 16) 1945 .Cases("DWORD", "dword", 32) 1946 .Cases("FLOAT", "float", 32) 1947 .Cases("LONG", "long", 32) 1948 .Cases("FWORD", "fword", 48) 1949 .Cases("DOUBLE", "double", 64) 1950 .Cases("QWORD", "qword", 64) 1951 .Cases("MMWORD","mmword", 64) 1952 .Cases("XWORD", "xword", 80) 1953 .Cases("TBYTE", "tbyte", 80) 1954 .Cases("XMMWORD", "xmmword", 128) 1955 .Cases("YMMWORD", "ymmword", 256) 1956 .Cases("ZMMWORD", "zmmword", 512) 1957 .Default(0); 1958 if (Size) { 1959 const AsmToken &Tok = Lex(); // Eat operand size (e.g., byte, word). 1960 if (!(Tok.getString().equals("PTR") || Tok.getString().equals("ptr"))) 1961 return Error(Tok.getLoc(), "Expected 'PTR' or 'ptr' token!"); 1962 Lex(); // Eat ptr. 1963 } 1964 return false; 1965 } 1966 1967 std::unique_ptr<X86Operand> X86AsmParser::ParseIntelOperand() { 1968 MCAsmParser &Parser = getParser(); 1969 const AsmToken &Tok = Parser.getTok(); 1970 SMLoc Start, End; 1971 1972 // Parse optional Size directive. 1973 unsigned Size; 1974 if (ParseIntelMemoryOperandSize(Size)) 1975 return nullptr; 1976 bool PtrInOperand = bool(Size); 1977 1978 Start = Tok.getLoc(); 1979 1980 // Rounding mode operand. 1981 if (getLexer().is(AsmToken::LCurly)) 1982 return ParseRoundingModeOp(Start); 1983 1984 // Register operand. 1985 unsigned RegNo = 0; 1986 if (Tok.is(AsmToken::Identifier) && !ParseRegister(RegNo, Start, End)) { 1987 if (RegNo == X86::RIP) 1988 return ErrorOperand(Start, "rip can only be used as a base register"); 1989 // A Register followed by ':' is considered a segment override 1990 if (Tok.isNot(AsmToken::Colon)) 1991 return !PtrInOperand ? X86Operand::CreateReg(RegNo, Start, End) : 1992 ErrorOperand(Start, "expected memory operand after 'ptr', " 1993 "found register operand instead"); 1994 // An alleged segment override. check if we have a valid segment register 1995 if (!X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo)) 1996 return ErrorOperand(Start, "invalid segment register"); 1997 // Eat ':' and update Start location 1998 Start = Lex().getLoc(); 1999 } 2000 2001 // Immediates and Memory 2002 IntelExprStateMachine SM; 2003 if (ParseIntelExpression(SM, End)) 2004 return nullptr; 2005 2006 if (isParsingMSInlineAsm()) 2007 RewriteIntelExpression(SM, Start, Tok.getLoc()); 2008 2009 int64_t Imm = SM.getImm(); 2010 const MCExpr *Disp = SM.getSym(); 2011 const MCExpr *ImmDisp = MCConstantExpr::create(Imm, getContext()); 2012 if (Disp && Imm) 2013 Disp = MCBinaryExpr::createAdd(Disp, ImmDisp, getContext()); 2014 if (!Disp) 2015 Disp = ImmDisp; 2016 2017 // RegNo != 0 specifies a valid segment register, 2018 // and we are parsing a segment override 2019 if (!SM.isMemExpr() && !RegNo) { 2020 if (isParsingMSInlineAsm() && SM.isOffsetOperator()) { 2021 const InlineAsmIdentifierInfo Info = SM.getIdentifierInfo(); 2022 if (Info.isKind(InlineAsmIdentifierInfo::IK_Var)) { 2023 // Disp includes the address of a variable; make sure this is recorded 2024 // for later handling. 2025 return X86Operand::CreateImm(Disp, Start, End, SM.getSymName(), 2026 Info.Var.Decl, Info.Var.IsGlobalLV); 2027 } 2028 } 2029 2030 return X86Operand::CreateImm(Disp, Start, End); 2031 } 2032 2033 StringRef ErrMsg; 2034 unsigned BaseReg = SM.getBaseReg(); 2035 unsigned IndexReg = SM.getIndexReg(); 2036 unsigned Scale = SM.getScale(); 2037 2038 if (Scale == 0 && BaseReg != X86::ESP && BaseReg != X86::RSP && 2039 (IndexReg == X86::ESP || IndexReg == X86::RSP)) 2040 std::swap(BaseReg, IndexReg); 2041 2042 // If BaseReg is a vector register and IndexReg is not, swap them unless 2043 // Scale was specified in which case it would be an error. 2044 if (Scale == 0 && 2045 !(X86MCRegisterClasses[X86::VR128XRegClassID].contains(IndexReg) || 2046 X86MCRegisterClasses[X86::VR256XRegClassID].contains(IndexReg) || 2047 X86MCRegisterClasses[X86::VR512RegClassID].contains(IndexReg)) && 2048 (X86MCRegisterClasses[X86::VR128XRegClassID].contains(BaseReg) || 2049 X86MCRegisterClasses[X86::VR256XRegClassID].contains(BaseReg) || 2050 X86MCRegisterClasses[X86::VR512RegClassID].contains(BaseReg))) 2051 std::swap(BaseReg, IndexReg); 2052 2053 if (Scale != 0 && 2054 X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)) 2055 return ErrorOperand(Start, "16-bit addresses cannot have a scale"); 2056 2057 // If there was no explicit scale specified, change it to 1. 2058 if (Scale == 0) 2059 Scale = 1; 2060 2061 // If this is a 16-bit addressing mode with the base and index in the wrong 2062 // order, swap them so CheckBaseRegAndIndexRegAndScale doesn't fail. It is 2063 // shared with att syntax where order matters. 2064 if ((BaseReg == X86::SI || BaseReg == X86::DI) && 2065 (IndexReg == X86::BX || IndexReg == X86::BP)) 2066 std::swap(BaseReg, IndexReg); 2067 2068 if ((BaseReg || IndexReg) && 2069 CheckBaseRegAndIndexRegAndScale(BaseReg, IndexReg, Scale, is64BitMode(), 2070 ErrMsg)) 2071 return ErrorOperand(Start, ErrMsg); 2072 if (isParsingMSInlineAsm()) 2073 return CreateMemForMSInlineAsm(RegNo, Disp, BaseReg, IndexReg, Scale, Start, 2074 End, Size, SM.getSymName(), 2075 SM.getIdentifierInfo()); 2076 if (!(BaseReg || IndexReg || RegNo)) 2077 return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End, Size); 2078 return X86Operand::CreateMem(getPointerWidth(), RegNo, Disp, 2079 BaseReg, IndexReg, Scale, Start, End, Size); 2080 } 2081 2082 std::unique_ptr<X86Operand> X86AsmParser::ParseATTOperand() { 2083 MCAsmParser &Parser = getParser(); 2084 switch (getLexer().getKind()) { 2085 case AsmToken::Dollar: { 2086 // $42 or $ID -> immediate. 2087 SMLoc Start = Parser.getTok().getLoc(), End; 2088 Parser.Lex(); 2089 const MCExpr *Val; 2090 // This is an immediate, so we should not parse a register. Do a precheck 2091 // for '%' to supercede intra-register parse errors. 2092 SMLoc L = Parser.getTok().getLoc(); 2093 if (check(getLexer().is(AsmToken::Percent), L, 2094 "expected immediate expression") || 2095 getParser().parseExpression(Val, End) || 2096 check(isa<X86MCExpr>(Val), L, "expected immediate expression")) 2097 return nullptr; 2098 return X86Operand::CreateImm(Val, Start, End); 2099 } 2100 case AsmToken::LCurly: { 2101 SMLoc Start = Parser.getTok().getLoc(); 2102 return ParseRoundingModeOp(Start); 2103 } 2104 default: { 2105 // This a memory operand or a register. We have some parsing complications 2106 // as a '(' may be part of an immediate expression or the addressing mode 2107 // block. This is complicated by the fact that an assembler-level variable 2108 // may refer either to a register or an immediate expression. 2109 2110 SMLoc Loc = Parser.getTok().getLoc(), EndLoc; 2111 const MCExpr *Expr = nullptr; 2112 unsigned Reg = 0; 2113 if (getLexer().isNot(AsmToken::LParen)) { 2114 // No '(' so this is either a displacement expression or a register. 2115 if (Parser.parseExpression(Expr, EndLoc)) 2116 return nullptr; 2117 if (auto *RE = dyn_cast<X86MCExpr>(Expr)) { 2118 // Segment Register. Reset Expr and copy value to register. 2119 Expr = nullptr; 2120 Reg = RE->getRegNo(); 2121 2122 // Sanity check register. 2123 if (Reg == X86::EIZ || Reg == X86::RIZ) 2124 return ErrorOperand( 2125 Loc, "%eiz and %riz can only be used as index registers", 2126 SMRange(Loc, EndLoc)); 2127 if (Reg == X86::RIP) 2128 return ErrorOperand(Loc, "%rip can only be used as a base register", 2129 SMRange(Loc, EndLoc)); 2130 // Return register that are not segment prefixes immediately. 2131 if (!Parser.parseOptionalToken(AsmToken::Colon)) 2132 return X86Operand::CreateReg(Reg, Loc, EndLoc); 2133 if (!X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(Reg)) 2134 return ErrorOperand(Loc, "invalid segment register"); 2135 } 2136 } 2137 // This is a Memory operand. 2138 return ParseMemOperand(Reg, Expr, Loc, EndLoc); 2139 } 2140 } 2141 } 2142 2143 // X86::COND_INVALID if not a recognized condition code or alternate mnemonic, 2144 // otherwise the EFLAGS Condition Code enumerator. 2145 X86::CondCode X86AsmParser::ParseConditionCode(StringRef CC) { 2146 return StringSwitch<X86::CondCode>(CC) 2147 .Case("o", X86::COND_O) // Overflow 2148 .Case("no", X86::COND_NO) // No Overflow 2149 .Cases("b", "nae", X86::COND_B) // Below/Neither Above nor Equal 2150 .Cases("ae", "nb", X86::COND_AE) // Above or Equal/Not Below 2151 .Cases("e", "z", X86::COND_E) // Equal/Zero 2152 .Cases("ne", "nz", X86::COND_NE) // Not Equal/Not Zero 2153 .Cases("be", "na", X86::COND_BE) // Below or Equal/Not Above 2154 .Cases("a", "nbe", X86::COND_A) // Above/Neither Below nor Equal 2155 .Case("s", X86::COND_S) // Sign 2156 .Case("ns", X86::COND_NS) // No Sign 2157 .Cases("p", "pe", X86::COND_P) // Parity/Parity Even 2158 .Cases("np", "po", X86::COND_NP) // No Parity/Parity Odd 2159 .Cases("l", "nge", X86::COND_L) // Less/Neither Greater nor Equal 2160 .Cases("ge", "nl", X86::COND_GE) // Greater or Equal/Not Less 2161 .Cases("le", "ng", X86::COND_LE) // Less or Equal/Not Greater 2162 .Cases("g", "nle", X86::COND_G) // Greater/Neither Less nor Equal 2163 .Default(X86::COND_INVALID); 2164 } 2165 2166 // true on failure, false otherwise 2167 // If no {z} mark was found - Parser doesn't advance 2168 bool X86AsmParser::ParseZ(std::unique_ptr<X86Operand> &Z, 2169 const SMLoc &StartLoc) { 2170 MCAsmParser &Parser = getParser(); 2171 // Assuming we are just pass the '{' mark, quering the next token 2172 // Searched for {z}, but none was found. Return false, as no parsing error was 2173 // encountered 2174 if (!(getLexer().is(AsmToken::Identifier) && 2175 (getLexer().getTok().getIdentifier() == "z"))) 2176 return false; 2177 Parser.Lex(); // Eat z 2178 // Query and eat the '}' mark 2179 if (!getLexer().is(AsmToken::RCurly)) 2180 return Error(getLexer().getLoc(), "Expected } at this point"); 2181 Parser.Lex(); // Eat '}' 2182 // Assign Z with the {z} mark opernad 2183 Z = X86Operand::CreateToken("{z}", StartLoc); 2184 return false; 2185 } 2186 2187 // true on failure, false otherwise 2188 bool X86AsmParser::HandleAVX512Operand(OperandVector &Operands, 2189 const MCParsedAsmOperand &Op) { 2190 MCAsmParser &Parser = getParser(); 2191 if (getLexer().is(AsmToken::LCurly)) { 2192 // Eat "{" and mark the current place. 2193 const SMLoc consumedToken = consumeToken(); 2194 // Distinguish {1to<NUM>} from {%k<NUM>}. 2195 if(getLexer().is(AsmToken::Integer)) { 2196 // Parse memory broadcasting ({1to<NUM>}). 2197 if (getLexer().getTok().getIntVal() != 1) 2198 return TokError("Expected 1to<NUM> at this point"); 2199 Parser.Lex(); // Eat "1" of 1to8 2200 if (!getLexer().is(AsmToken::Identifier) || 2201 !getLexer().getTok().getIdentifier().startswith("to")) 2202 return TokError("Expected 1to<NUM> at this point"); 2203 // Recognize only reasonable suffixes. 2204 const char *BroadcastPrimitive = 2205 StringSwitch<const char*>(getLexer().getTok().getIdentifier()) 2206 .Case("to2", "{1to2}") 2207 .Case("to4", "{1to4}") 2208 .Case("to8", "{1to8}") 2209 .Case("to16", "{1to16}") 2210 .Default(nullptr); 2211 if (!BroadcastPrimitive) 2212 return TokError("Invalid memory broadcast primitive."); 2213 Parser.Lex(); // Eat "toN" of 1toN 2214 if (!getLexer().is(AsmToken::RCurly)) 2215 return TokError("Expected } at this point"); 2216 Parser.Lex(); // Eat "}" 2217 Operands.push_back(X86Operand::CreateToken(BroadcastPrimitive, 2218 consumedToken)); 2219 // No AVX512 specific primitives can pass 2220 // after memory broadcasting, so return. 2221 return false; 2222 } else { 2223 // Parse either {k}{z}, {z}{k}, {k} or {z} 2224 // last one have no meaning, but GCC accepts it 2225 // Currently, we're just pass a '{' mark 2226 std::unique_ptr<X86Operand> Z; 2227 if (ParseZ(Z, consumedToken)) 2228 return true; 2229 // Reaching here means that parsing of the allegadly '{z}' mark yielded 2230 // no errors. 2231 // Query for the need of further parsing for a {%k<NUM>} mark 2232 if (!Z || getLexer().is(AsmToken::LCurly)) { 2233 SMLoc StartLoc = Z ? consumeToken() : consumedToken; 2234 // Parse an op-mask register mark ({%k<NUM>}), which is now to be 2235 // expected 2236 unsigned RegNo; 2237 SMLoc RegLoc; 2238 if (!ParseRegister(RegNo, RegLoc, StartLoc) && 2239 X86MCRegisterClasses[X86::VK1RegClassID].contains(RegNo)) { 2240 if (RegNo == X86::K0) 2241 return Error(RegLoc, "Register k0 can't be used as write mask"); 2242 if (!getLexer().is(AsmToken::RCurly)) 2243 return Error(getLexer().getLoc(), "Expected } at this point"); 2244 Operands.push_back(X86Operand::CreateToken("{", StartLoc)); 2245 Operands.push_back( 2246 X86Operand::CreateReg(RegNo, StartLoc, StartLoc)); 2247 Operands.push_back(X86Operand::CreateToken("}", consumeToken())); 2248 } else 2249 return Error(getLexer().getLoc(), 2250 "Expected an op-mask register at this point"); 2251 // {%k<NUM>} mark is found, inquire for {z} 2252 if (getLexer().is(AsmToken::LCurly) && !Z) { 2253 // Have we've found a parsing error, or found no (expected) {z} mark 2254 // - report an error 2255 if (ParseZ(Z, consumeToken()) || !Z) 2256 return Error(getLexer().getLoc(), 2257 "Expected a {z} mark at this point"); 2258 2259 } 2260 // '{z}' on its own is meaningless, hence should be ignored. 2261 // on the contrary - have it been accompanied by a K register, 2262 // allow it. 2263 if (Z) 2264 Operands.push_back(std::move(Z)); 2265 } 2266 } 2267 } 2268 return false; 2269 } 2270 2271 /// ParseMemOperand: 'seg : disp(basereg, indexreg, scale)'. The '%ds:' prefix 2272 /// has already been parsed if present. disp may be provided as well. 2273 std::unique_ptr<X86Operand> X86AsmParser::ParseMemOperand(unsigned SegReg, 2274 const MCExpr *&Disp, 2275 const SMLoc &StartLoc, 2276 SMLoc &EndLoc) { 2277 MCAsmParser &Parser = getParser(); 2278 SMLoc Loc; 2279 // Based on the initial passed values, we may be in any of these cases, we are 2280 // in one of these cases (with current position (*)): 2281 2282 // 1. seg : * disp (base-index-scale-expr) 2283 // 2. seg : *(disp) (base-index-scale-expr) 2284 // 3. seg : *(base-index-scale-expr) 2285 // 4. disp *(base-index-scale-expr) 2286 // 5. *(disp) (base-index-scale-expr) 2287 // 6. *(base-index-scale-expr) 2288 // 7. disp * 2289 // 8. *(disp) 2290 2291 // If we do not have an displacement yet, check if we're in cases 4 or 6 by 2292 // checking if the first object after the parenthesis is a register (or an 2293 // identifier referring to a register) and parse the displacement or default 2294 // to 0 as appropriate. 2295 auto isAtMemOperand = [this]() { 2296 if (this->getLexer().isNot(AsmToken::LParen)) 2297 return false; 2298 AsmToken Buf[2]; 2299 StringRef Id; 2300 auto TokCount = this->getLexer().peekTokens(Buf, true); 2301 if (TokCount == 0) 2302 return false; 2303 switch (Buf[0].getKind()) { 2304 case AsmToken::Percent: 2305 case AsmToken::Comma: 2306 return true; 2307 // These lower cases are doing a peekIdentifier. 2308 case AsmToken::At: 2309 case AsmToken::Dollar: 2310 if ((TokCount > 1) && 2311 (Buf[1].is(AsmToken::Identifier) || Buf[1].is(AsmToken::String)) && 2312 (Buf[0].getLoc().getPointer() + 1 == Buf[1].getLoc().getPointer())) 2313 Id = StringRef(Buf[0].getLoc().getPointer(), 2314 Buf[1].getIdentifier().size() + 1); 2315 break; 2316 case AsmToken::Identifier: 2317 case AsmToken::String: 2318 Id = Buf[0].getIdentifier(); 2319 break; 2320 default: 2321 return false; 2322 } 2323 // We have an ID. Check if it is bound to a register. 2324 if (!Id.empty()) { 2325 MCSymbol *Sym = this->getContext().getOrCreateSymbol(Id); 2326 if (Sym->isVariable()) { 2327 auto V = Sym->getVariableValue(/*SetUsed*/ false); 2328 return isa<X86MCExpr>(V); 2329 } 2330 } 2331 return false; 2332 }; 2333 2334 if (!Disp) { 2335 // Parse immediate if we're not at a mem operand yet. 2336 if (!isAtMemOperand()) { 2337 if (Parser.parseTokenLoc(Loc) || Parser.parseExpression(Disp, EndLoc)) 2338 return nullptr; 2339 assert(!isa<X86MCExpr>(Disp) && "Expected non-register here."); 2340 } else { 2341 // Disp is implicitly zero if we haven't parsed it yet. 2342 Disp = MCConstantExpr::create(0, Parser.getContext()); 2343 } 2344 } 2345 2346 // We are now either at the end of the operand or at the '(' at the start of a 2347 // base-index-scale-expr. 2348 2349 if (!parseOptionalToken(AsmToken::LParen)) { 2350 if (SegReg == 0) 2351 return X86Operand::CreateMem(getPointerWidth(), Disp, StartLoc, EndLoc); 2352 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, 0, 0, 1, 2353 StartLoc, EndLoc); 2354 } 2355 2356 // If we reached here, then eat the '(' and Process 2357 // the rest of the memory operand. 2358 unsigned BaseReg = 0, IndexReg = 0, Scale = 1; 2359 SMLoc BaseLoc = getLexer().getLoc(); 2360 const MCExpr *E; 2361 StringRef ErrMsg; 2362 2363 // Parse BaseReg if one is provided. 2364 if (getLexer().isNot(AsmToken::Comma) && getLexer().isNot(AsmToken::RParen)) { 2365 if (Parser.parseExpression(E, EndLoc) || 2366 check(!isa<X86MCExpr>(E), BaseLoc, "expected register here")) 2367 return nullptr; 2368 2369 // Sanity check register. 2370 BaseReg = cast<X86MCExpr>(E)->getRegNo(); 2371 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) 2372 return ErrorOperand(BaseLoc, 2373 "eiz and riz can only be used as index registers", 2374 SMRange(BaseLoc, EndLoc)); 2375 } 2376 2377 if (parseOptionalToken(AsmToken::Comma)) { 2378 // Following the comma we should have either an index register, or a scale 2379 // value. We don't support the later form, but we want to parse it 2380 // correctly. 2381 // 2382 // Even though it would be completely consistent to support syntax like 2383 // "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this. 2384 if (getLexer().isNot(AsmToken::RParen)) { 2385 if (Parser.parseTokenLoc(Loc) || Parser.parseExpression(E, EndLoc)) 2386 return nullptr; 2387 2388 if (!isa<X86MCExpr>(E)) { 2389 // We've parsed an unexpected Scale Value instead of an index 2390 // register. Interpret it as an absolute. 2391 int64_t ScaleVal; 2392 if (!E->evaluateAsAbsolute(ScaleVal, getStreamer().getAssemblerPtr())) 2393 return ErrorOperand(Loc, "expected absolute expression"); 2394 if (ScaleVal != 1) 2395 Warning(Loc, "scale factor without index register is ignored"); 2396 Scale = 1; 2397 } else { // IndexReg Found. 2398 IndexReg = cast<X86MCExpr>(E)->getRegNo(); 2399 2400 if (BaseReg == X86::RIP) 2401 return ErrorOperand( 2402 Loc, "%rip as base register can not have an index register"); 2403 if (IndexReg == X86::RIP) 2404 return ErrorOperand(Loc, "%rip is not allowed as an index register"); 2405 2406 if (parseOptionalToken(AsmToken::Comma)) { 2407 // Parse the scale amount: 2408 // ::= ',' [scale-expression] 2409 2410 // A scale amount without an index is ignored. 2411 if (getLexer().isNot(AsmToken::RParen)) { 2412 int64_t ScaleVal; 2413 if (Parser.parseTokenLoc(Loc) || 2414 Parser.parseAbsoluteExpression(ScaleVal)) 2415 return ErrorOperand(Loc, "expected scale expression"); 2416 Scale = (unsigned)ScaleVal; 2417 // Validate the scale amount. 2418 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) && 2419 Scale != 1) 2420 return ErrorOperand(Loc, 2421 "scale factor in 16-bit address must be 1"); 2422 if (checkScale(Scale, ErrMsg)) 2423 return ErrorOperand(Loc, ErrMsg); 2424 } 2425 } 2426 } 2427 } 2428 } 2429 2430 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too. 2431 if (parseToken(AsmToken::RParen, "unexpected token in memory operand")) 2432 return nullptr; 2433 2434 // This is to support otherwise illegal operand (%dx) found in various 2435 // unofficial manuals examples (e.g. "out[s]?[bwl]? %al, (%dx)") and must now 2436 // be supported. Mark such DX variants separately fix only in special cases. 2437 if (BaseReg == X86::DX && IndexReg == 0 && Scale == 1 && SegReg == 0 && 2438 isa<MCConstantExpr>(Disp) && cast<MCConstantExpr>(Disp)->getValue() == 0) 2439 return X86Operand::CreateDXReg(BaseLoc, BaseLoc); 2440 2441 if (CheckBaseRegAndIndexRegAndScale(BaseReg, IndexReg, Scale, is64BitMode(), 2442 ErrMsg)) 2443 return ErrorOperand(BaseLoc, ErrMsg); 2444 2445 if (SegReg || BaseReg || IndexReg) 2446 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg, 2447 IndexReg, Scale, StartLoc, EndLoc); 2448 return X86Operand::CreateMem(getPointerWidth(), Disp, StartLoc, EndLoc); 2449 } 2450 2451 // Parse either a standard primary expression or a register. 2452 bool X86AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) { 2453 MCAsmParser &Parser = getParser(); 2454 // See if this is a register first. 2455 if (getTok().is(AsmToken::Percent) || 2456 (isParsingIntelSyntax() && getTok().is(AsmToken::Identifier) && 2457 MatchRegisterName(Parser.getTok().getString()))) { 2458 SMLoc StartLoc = Parser.getTok().getLoc(); 2459 unsigned RegNo; 2460 if (ParseRegister(RegNo, StartLoc, EndLoc)) 2461 return true; 2462 Res = X86MCExpr::create(RegNo, Parser.getContext()); 2463 return false; 2464 } 2465 return Parser.parsePrimaryExpr(Res, EndLoc); 2466 } 2467 2468 bool X86AsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name, 2469 SMLoc NameLoc, OperandVector &Operands) { 2470 MCAsmParser &Parser = getParser(); 2471 InstInfo = &Info; 2472 2473 // Reset the forced VEX encoding. 2474 ForcedVEXEncoding = VEXEncoding_Default; 2475 2476 // Parse pseudo prefixes. 2477 while (1) { 2478 if (Name == "{") { 2479 if (getLexer().isNot(AsmToken::Identifier)) 2480 return Error(Parser.getTok().getLoc(), "Unexpected token after '{'"); 2481 std::string Prefix = Parser.getTok().getString().lower(); 2482 Parser.Lex(); // Eat identifier. 2483 if (getLexer().isNot(AsmToken::RCurly)) 2484 return Error(Parser.getTok().getLoc(), "Expected '}'"); 2485 Parser.Lex(); // Eat curly. 2486 2487 if (Prefix == "vex" || Prefix == "vex2") 2488 ForcedVEXEncoding = VEXEncoding_VEX; 2489 else if (Prefix == "vex3") 2490 ForcedVEXEncoding = VEXEncoding_VEX3; 2491 else if (Prefix == "evex") 2492 ForcedVEXEncoding = VEXEncoding_EVEX; 2493 else 2494 return Error(NameLoc, "unknown prefix"); 2495 2496 NameLoc = Parser.getTok().getLoc(); 2497 if (getLexer().is(AsmToken::LCurly)) { 2498 Parser.Lex(); 2499 Name = "{"; 2500 } else { 2501 if (getLexer().isNot(AsmToken::Identifier)) 2502 return Error(Parser.getTok().getLoc(), "Expected identifier"); 2503 // FIXME: The mnemonic won't match correctly if its not in lower case. 2504 Name = Parser.getTok().getString(); 2505 Parser.Lex(); 2506 } 2507 continue; 2508 } 2509 2510 break; 2511 } 2512 2513 StringRef PatchedName = Name; 2514 2515 // Hack to skip "short" following Jcc. 2516 if (isParsingIntelSyntax() && 2517 (PatchedName == "jmp" || PatchedName == "jc" || PatchedName == "jnc" || 2518 PatchedName == "jcxz" || PatchedName == "jexcz" || 2519 (PatchedName.startswith("j") && 2520 ParseConditionCode(PatchedName.substr(1)) != X86::COND_INVALID))) { 2521 StringRef NextTok = Parser.getTok().getString(); 2522 if (NextTok == "short") { 2523 SMLoc NameEndLoc = 2524 NameLoc.getFromPointer(NameLoc.getPointer() + Name.size()); 2525 // Eat the short keyword. 2526 Parser.Lex(); 2527 // MS and GAS ignore the short keyword; they both determine the jmp type 2528 // based on the distance of the label. (NASM does emit different code with 2529 // and without "short," though.) 2530 InstInfo->AsmRewrites->emplace_back(AOK_Skip, NameEndLoc, 2531 NextTok.size() + 1); 2532 } 2533 } 2534 2535 // FIXME: Hack to recognize setneb as setne. 2536 if (PatchedName.startswith("set") && PatchedName.endswith("b") && 2537 PatchedName != "setb" && PatchedName != "setnb") 2538 PatchedName = PatchedName.substr(0, Name.size()-1); 2539 2540 unsigned ComparisonPredicate = ~0U; 2541 2542 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}. 2543 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) && 2544 (PatchedName.endswith("ss") || PatchedName.endswith("sd") || 2545 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) { 2546 bool IsVCMP = PatchedName[0] == 'v'; 2547 unsigned CCIdx = IsVCMP ? 4 : 3; 2548 unsigned CC = StringSwitch<unsigned>( 2549 PatchedName.slice(CCIdx, PatchedName.size() - 2)) 2550 .Case("eq", 0x00) 2551 .Case("eq_oq", 0x00) 2552 .Case("lt", 0x01) 2553 .Case("lt_os", 0x01) 2554 .Case("le", 0x02) 2555 .Case("le_os", 0x02) 2556 .Case("unord", 0x03) 2557 .Case("unord_q", 0x03) 2558 .Case("neq", 0x04) 2559 .Case("neq_uq", 0x04) 2560 .Case("nlt", 0x05) 2561 .Case("nlt_us", 0x05) 2562 .Case("nle", 0x06) 2563 .Case("nle_us", 0x06) 2564 .Case("ord", 0x07) 2565 .Case("ord_q", 0x07) 2566 /* AVX only from here */ 2567 .Case("eq_uq", 0x08) 2568 .Case("nge", 0x09) 2569 .Case("nge_us", 0x09) 2570 .Case("ngt", 0x0A) 2571 .Case("ngt_us", 0x0A) 2572 .Case("false", 0x0B) 2573 .Case("false_oq", 0x0B) 2574 .Case("neq_oq", 0x0C) 2575 .Case("ge", 0x0D) 2576 .Case("ge_os", 0x0D) 2577 .Case("gt", 0x0E) 2578 .Case("gt_os", 0x0E) 2579 .Case("true", 0x0F) 2580 .Case("true_uq", 0x0F) 2581 .Case("eq_os", 0x10) 2582 .Case("lt_oq", 0x11) 2583 .Case("le_oq", 0x12) 2584 .Case("unord_s", 0x13) 2585 .Case("neq_us", 0x14) 2586 .Case("nlt_uq", 0x15) 2587 .Case("nle_uq", 0x16) 2588 .Case("ord_s", 0x17) 2589 .Case("eq_us", 0x18) 2590 .Case("nge_uq", 0x19) 2591 .Case("ngt_uq", 0x1A) 2592 .Case("false_os", 0x1B) 2593 .Case("neq_os", 0x1C) 2594 .Case("ge_oq", 0x1D) 2595 .Case("gt_oq", 0x1E) 2596 .Case("true_us", 0x1F) 2597 .Default(~0U); 2598 if (CC != ~0U && (IsVCMP || CC < 8)) { 2599 if (PatchedName.endswith("ss")) 2600 PatchedName = IsVCMP ? "vcmpss" : "cmpss"; 2601 else if (PatchedName.endswith("sd")) 2602 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd"; 2603 else if (PatchedName.endswith("ps")) 2604 PatchedName = IsVCMP ? "vcmpps" : "cmpps"; 2605 else if (PatchedName.endswith("pd")) 2606 PatchedName = IsVCMP ? "vcmppd" : "cmppd"; 2607 else 2608 llvm_unreachable("Unexpected suffix!"); 2609 2610 ComparisonPredicate = CC; 2611 } 2612 } 2613 2614 // FIXME: Hack to recognize vpcmp<comparison code>{ub,uw,ud,uq,b,w,d,q}. 2615 if (PatchedName.startswith("vpcmp") && 2616 (PatchedName.back() == 'b' || PatchedName.back() == 'w' || 2617 PatchedName.back() == 'd' || PatchedName.back() == 'q')) { 2618 unsigned SuffixSize = PatchedName.drop_back().back() == 'u' ? 2 : 1; 2619 unsigned CC = StringSwitch<unsigned>( 2620 PatchedName.slice(5, PatchedName.size() - SuffixSize)) 2621 .Case("eq", 0x0) // Only allowed on unsigned. Checked below. 2622 .Case("lt", 0x1) 2623 .Case("le", 0x2) 2624 //.Case("false", 0x3) // Not a documented alias. 2625 .Case("neq", 0x4) 2626 .Case("nlt", 0x5) 2627 .Case("nle", 0x6) 2628 //.Case("true", 0x7) // Not a documented alias. 2629 .Default(~0U); 2630 if (CC != ~0U && (CC != 0 || SuffixSize == 2)) { 2631 switch (PatchedName.back()) { 2632 default: llvm_unreachable("Unexpected character!"); 2633 case 'b': PatchedName = SuffixSize == 2 ? "vpcmpub" : "vpcmpb"; break; 2634 case 'w': PatchedName = SuffixSize == 2 ? "vpcmpuw" : "vpcmpw"; break; 2635 case 'd': PatchedName = SuffixSize == 2 ? "vpcmpud" : "vpcmpd"; break; 2636 case 'q': PatchedName = SuffixSize == 2 ? "vpcmpuq" : "vpcmpq"; break; 2637 } 2638 // Set up the immediate to push into the operands later. 2639 ComparisonPredicate = CC; 2640 } 2641 } 2642 2643 // FIXME: Hack to recognize vpcom<comparison code>{ub,uw,ud,uq,b,w,d,q}. 2644 if (PatchedName.startswith("vpcom") && 2645 (PatchedName.back() == 'b' || PatchedName.back() == 'w' || 2646 PatchedName.back() == 'd' || PatchedName.back() == 'q')) { 2647 unsigned SuffixSize = PatchedName.drop_back().back() == 'u' ? 2 : 1; 2648 unsigned CC = StringSwitch<unsigned>( 2649 PatchedName.slice(5, PatchedName.size() - SuffixSize)) 2650 .Case("lt", 0x0) 2651 .Case("le", 0x1) 2652 .Case("gt", 0x2) 2653 .Case("ge", 0x3) 2654 .Case("eq", 0x4) 2655 .Case("neq", 0x5) 2656 .Case("false", 0x6) 2657 .Case("true", 0x7) 2658 .Default(~0U); 2659 if (CC != ~0U) { 2660 switch (PatchedName.back()) { 2661 default: llvm_unreachable("Unexpected character!"); 2662 case 'b': PatchedName = SuffixSize == 2 ? "vpcomub" : "vpcomb"; break; 2663 case 'w': PatchedName = SuffixSize == 2 ? "vpcomuw" : "vpcomw"; break; 2664 case 'd': PatchedName = SuffixSize == 2 ? "vpcomud" : "vpcomd"; break; 2665 case 'q': PatchedName = SuffixSize == 2 ? "vpcomuq" : "vpcomq"; break; 2666 } 2667 // Set up the immediate to push into the operands later. 2668 ComparisonPredicate = CC; 2669 } 2670 } 2671 2672 2673 // Determine whether this is an instruction prefix. 2674 // FIXME: 2675 // Enhance prefixes integrity robustness. for example, following forms 2676 // are currently tolerated: 2677 // repz repnz <insn> ; GAS errors for the use of two similar prefixes 2678 // lock addq %rax, %rbx ; Destination operand must be of memory type 2679 // xacquire <insn> ; xacquire must be accompanied by 'lock' 2680 bool isPrefix = StringSwitch<bool>(Name) 2681 .Cases("rex64", "data32", "data16", true) 2682 .Cases("xacquire", "xrelease", true) 2683 .Cases("acquire", "release", isParsingIntelSyntax()) 2684 .Default(false); 2685 2686 auto isLockRepeatNtPrefix = [](StringRef N) { 2687 return StringSwitch<bool>(N) 2688 .Cases("lock", "rep", "repe", "repz", "repne", "repnz", "notrack", true) 2689 .Default(false); 2690 }; 2691 2692 bool CurlyAsEndOfStatement = false; 2693 2694 unsigned Flags = X86::IP_NO_PREFIX; 2695 while (isLockRepeatNtPrefix(Name.lower())) { 2696 unsigned Prefix = 2697 StringSwitch<unsigned>(Name) 2698 .Cases("lock", "lock", X86::IP_HAS_LOCK) 2699 .Cases("rep", "repe", "repz", X86::IP_HAS_REPEAT) 2700 .Cases("repne", "repnz", X86::IP_HAS_REPEAT_NE) 2701 .Cases("notrack", "notrack", X86::IP_HAS_NOTRACK) 2702 .Default(X86::IP_NO_PREFIX); // Invalid prefix (impossible) 2703 Flags |= Prefix; 2704 if (getLexer().is(AsmToken::EndOfStatement)) { 2705 // We don't have real instr with the given prefix 2706 // let's use the prefix as the instr. 2707 // TODO: there could be several prefixes one after another 2708 Flags = X86::IP_NO_PREFIX; 2709 break; 2710 } 2711 // FIXME: The mnemonic won't match correctly if its not in lower case. 2712 Name = Parser.getTok().getString(); 2713 Parser.Lex(); // eat the prefix 2714 // Hack: we could have something like "rep # some comment" or 2715 // "lock; cmpxchg16b $1" or "lock\0A\09incl" or "lock/incl" 2716 while (Name.startswith(";") || Name.startswith("\n") || 2717 Name.startswith("#") || Name.startswith("\t") || 2718 Name.startswith("/")) { 2719 // FIXME: The mnemonic won't match correctly if its not in lower case. 2720 Name = Parser.getTok().getString(); 2721 Parser.Lex(); // go to next prefix or instr 2722 } 2723 } 2724 2725 if (Flags) 2726 PatchedName = Name; 2727 2728 // Hacks to handle 'data16' and 'data32' 2729 if (PatchedName == "data16" && is16BitMode()) { 2730 return Error(NameLoc, "redundant data16 prefix"); 2731 } 2732 if (PatchedName == "data32") { 2733 if (is32BitMode()) 2734 return Error(NameLoc, "redundant data32 prefix"); 2735 if (is64BitMode()) 2736 return Error(NameLoc, "'data32' is not supported in 64-bit mode"); 2737 // Hack to 'data16' for the table lookup. 2738 PatchedName = "data16"; 2739 } 2740 2741 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc)); 2742 2743 // Push the immediate if we extracted one from the mnemonic. 2744 if (ComparisonPredicate != ~0U && !isParsingIntelSyntax()) { 2745 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonPredicate, 2746 getParser().getContext()); 2747 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc)); 2748 } 2749 2750 // This does the actual operand parsing. Don't parse any more if we have a 2751 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we 2752 // just want to parse the "lock" as the first instruction and the "incl" as 2753 // the next one. 2754 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) { 2755 // Parse '*' modifier. 2756 if (getLexer().is(AsmToken::Star)) 2757 Operands.push_back(X86Operand::CreateToken("*", consumeToken())); 2758 2759 // Read the operands. 2760 while(1) { 2761 if (std::unique_ptr<X86Operand> Op = ParseOperand()) { 2762 Operands.push_back(std::move(Op)); 2763 if (HandleAVX512Operand(Operands, *Operands.back())) 2764 return true; 2765 } else { 2766 return true; 2767 } 2768 // check for comma and eat it 2769 if (getLexer().is(AsmToken::Comma)) 2770 Parser.Lex(); 2771 else 2772 break; 2773 } 2774 2775 // In MS inline asm curly braces mark the beginning/end of a block, 2776 // therefore they should be interepreted as end of statement 2777 CurlyAsEndOfStatement = 2778 isParsingIntelSyntax() && isParsingMSInlineAsm() && 2779 (getLexer().is(AsmToken::LCurly) || getLexer().is(AsmToken::RCurly)); 2780 if (getLexer().isNot(AsmToken::EndOfStatement) && !CurlyAsEndOfStatement) 2781 return TokError("unexpected token in argument list"); 2782 } 2783 2784 // Push the immediate if we extracted one from the mnemonic. 2785 if (ComparisonPredicate != ~0U && isParsingIntelSyntax()) { 2786 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonPredicate, 2787 getParser().getContext()); 2788 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc)); 2789 } 2790 2791 // Consume the EndOfStatement or the prefix separator Slash 2792 if (getLexer().is(AsmToken::EndOfStatement) || 2793 (isPrefix && getLexer().is(AsmToken::Slash))) 2794 Parser.Lex(); 2795 else if (CurlyAsEndOfStatement) 2796 // Add an actual EndOfStatement before the curly brace 2797 Info.AsmRewrites->emplace_back(AOK_EndOfStatement, 2798 getLexer().getTok().getLoc(), 0); 2799 2800 // This is for gas compatibility and cannot be done in td. 2801 // Adding "p" for some floating point with no argument. 2802 // For example: fsub --> fsubp 2803 bool IsFp = 2804 Name == "fsub" || Name == "fdiv" || Name == "fsubr" || Name == "fdivr"; 2805 if (IsFp && Operands.size() == 1) { 2806 const char *Repl = StringSwitch<const char *>(Name) 2807 .Case("fsub", "fsubp") 2808 .Case("fdiv", "fdivp") 2809 .Case("fsubr", "fsubrp") 2810 .Case("fdivr", "fdivrp"); 2811 static_cast<X86Operand &>(*Operands[0]).setTokenValue(Repl); 2812 } 2813 2814 if ((Name == "mov" || Name == "movw" || Name == "movl") && 2815 (Operands.size() == 3)) { 2816 X86Operand &Op1 = (X86Operand &)*Operands[1]; 2817 X86Operand &Op2 = (X86Operand &)*Operands[2]; 2818 SMLoc Loc = Op1.getEndLoc(); 2819 // Moving a 32 or 16 bit value into a segment register has the same 2820 // behavior. Modify such instructions to always take shorter form. 2821 if (Op1.isReg() && Op2.isReg() && 2822 X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains( 2823 Op2.getReg()) && 2824 (X86MCRegisterClasses[X86::GR16RegClassID].contains(Op1.getReg()) || 2825 X86MCRegisterClasses[X86::GR32RegClassID].contains(Op1.getReg()))) { 2826 // Change instruction name to match new instruction. 2827 if (Name != "mov" && Name[3] == (is16BitMode() ? 'l' : 'w')) { 2828 Name = is16BitMode() ? "movw" : "movl"; 2829 Operands[0] = X86Operand::CreateToken(Name, NameLoc); 2830 } 2831 // Select the correct equivalent 16-/32-bit source register. 2832 unsigned Reg = 2833 getX86SubSuperRegisterOrZero(Op1.getReg(), is16BitMode() ? 16 : 32); 2834 Operands[1] = X86Operand::CreateReg(Reg, Loc, Loc); 2835 } 2836 } 2837 2838 // This is a terrible hack to handle "out[s]?[bwl]? %al, (%dx)" -> 2839 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely 2840 // documented form in various unofficial manuals, so a lot of code uses it. 2841 if ((Name == "outb" || Name == "outsb" || Name == "outw" || Name == "outsw" || 2842 Name == "outl" || Name == "outsl" || Name == "out" || Name == "outs") && 2843 Operands.size() == 3) { 2844 X86Operand &Op = (X86Operand &)*Operands.back(); 2845 if (Op.isDXReg()) 2846 Operands.back() = X86Operand::CreateReg(X86::DX, Op.getStartLoc(), 2847 Op.getEndLoc()); 2848 } 2849 // Same hack for "in[s]?[bwl]? (%dx), %al" -> "inb %dx, %al". 2850 if ((Name == "inb" || Name == "insb" || Name == "inw" || Name == "insw" || 2851 Name == "inl" || Name == "insl" || Name == "in" || Name == "ins") && 2852 Operands.size() == 3) { 2853 X86Operand &Op = (X86Operand &)*Operands[1]; 2854 if (Op.isDXReg()) 2855 Operands[1] = X86Operand::CreateReg(X86::DX, Op.getStartLoc(), 2856 Op.getEndLoc()); 2857 } 2858 2859 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 2> TmpOperands; 2860 bool HadVerifyError = false; 2861 2862 // Append default arguments to "ins[bwld]" 2863 if (Name.startswith("ins") && 2864 (Operands.size() == 1 || Operands.size() == 3) && 2865 (Name == "insb" || Name == "insw" || Name == "insl" || Name == "insd" || 2866 Name == "ins")) { 2867 2868 AddDefaultSrcDestOperands(TmpOperands, 2869 X86Operand::CreateReg(X86::DX, NameLoc, NameLoc), 2870 DefaultMemDIOperand(NameLoc)); 2871 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2872 } 2873 2874 // Append default arguments to "outs[bwld]" 2875 if (Name.startswith("outs") && 2876 (Operands.size() == 1 || Operands.size() == 3) && 2877 (Name == "outsb" || Name == "outsw" || Name == "outsl" || 2878 Name == "outsd" || Name == "outs")) { 2879 AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc), 2880 X86Operand::CreateReg(X86::DX, NameLoc, NameLoc)); 2881 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2882 } 2883 2884 // Transform "lods[bwlq]" into "lods[bwlq] ($SIREG)" for appropriate 2885 // values of $SIREG according to the mode. It would be nice if this 2886 // could be achieved with InstAlias in the tables. 2887 if (Name.startswith("lods") && 2888 (Operands.size() == 1 || Operands.size() == 2) && 2889 (Name == "lods" || Name == "lodsb" || Name == "lodsw" || 2890 Name == "lodsl" || Name == "lodsd" || Name == "lodsq")) { 2891 TmpOperands.push_back(DefaultMemSIOperand(NameLoc)); 2892 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2893 } 2894 2895 // Transform "stos[bwlq]" into "stos[bwlq] ($DIREG)" for appropriate 2896 // values of $DIREG according to the mode. It would be nice if this 2897 // could be achieved with InstAlias in the tables. 2898 if (Name.startswith("stos") && 2899 (Operands.size() == 1 || Operands.size() == 2) && 2900 (Name == "stos" || Name == "stosb" || Name == "stosw" || 2901 Name == "stosl" || Name == "stosd" || Name == "stosq")) { 2902 TmpOperands.push_back(DefaultMemDIOperand(NameLoc)); 2903 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2904 } 2905 2906 // Transform "scas[bwlq]" into "scas[bwlq] ($DIREG)" for appropriate 2907 // values of $DIREG according to the mode. It would be nice if this 2908 // could be achieved with InstAlias in the tables. 2909 if (Name.startswith("scas") && 2910 (Operands.size() == 1 || Operands.size() == 2) && 2911 (Name == "scas" || Name == "scasb" || Name == "scasw" || 2912 Name == "scasl" || Name == "scasd" || Name == "scasq")) { 2913 TmpOperands.push_back(DefaultMemDIOperand(NameLoc)); 2914 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2915 } 2916 2917 // Add default SI and DI operands to "cmps[bwlq]". 2918 if (Name.startswith("cmps") && 2919 (Operands.size() == 1 || Operands.size() == 3) && 2920 (Name == "cmps" || Name == "cmpsb" || Name == "cmpsw" || 2921 Name == "cmpsl" || Name == "cmpsd" || Name == "cmpsq")) { 2922 AddDefaultSrcDestOperands(TmpOperands, DefaultMemDIOperand(NameLoc), 2923 DefaultMemSIOperand(NameLoc)); 2924 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2925 } 2926 2927 // Add default SI and DI operands to "movs[bwlq]". 2928 if (((Name.startswith("movs") && 2929 (Name == "movs" || Name == "movsb" || Name == "movsw" || 2930 Name == "movsl" || Name == "movsd" || Name == "movsq")) || 2931 (Name.startswith("smov") && 2932 (Name == "smov" || Name == "smovb" || Name == "smovw" || 2933 Name == "smovl" || Name == "smovd" || Name == "smovq"))) && 2934 (Operands.size() == 1 || Operands.size() == 3)) { 2935 if (Name == "movsd" && Operands.size() == 1 && !isParsingIntelSyntax()) 2936 Operands.back() = X86Operand::CreateToken("movsl", NameLoc); 2937 AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc), 2938 DefaultMemDIOperand(NameLoc)); 2939 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands); 2940 } 2941 2942 // Check if we encountered an error for one the string insturctions 2943 if (HadVerifyError) { 2944 return HadVerifyError; 2945 } 2946 2947 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to 2948 // "shift <op>". 2949 if ((Name.startswith("shr") || Name.startswith("sar") || 2950 Name.startswith("shl") || Name.startswith("sal") || 2951 Name.startswith("rcl") || Name.startswith("rcr") || 2952 Name.startswith("rol") || Name.startswith("ror")) && 2953 Operands.size() == 3) { 2954 if (isParsingIntelSyntax()) { 2955 // Intel syntax 2956 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[2]); 2957 if (Op1.isImm() && isa<MCConstantExpr>(Op1.getImm()) && 2958 cast<MCConstantExpr>(Op1.getImm())->getValue() == 1) 2959 Operands.pop_back(); 2960 } else { 2961 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]); 2962 if (Op1.isImm() && isa<MCConstantExpr>(Op1.getImm()) && 2963 cast<MCConstantExpr>(Op1.getImm())->getValue() == 1) 2964 Operands.erase(Operands.begin() + 1); 2965 } 2966 } 2967 2968 // Transforms "int $3" into "int3" as a size optimization. We can't write an 2969 // instalias with an immediate operand yet. 2970 if (Name == "int" && Operands.size() == 2) { 2971 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]); 2972 if (Op1.isImm()) 2973 if (auto *CE = dyn_cast<MCConstantExpr>(Op1.getImm())) 2974 if (CE->getValue() == 3) { 2975 Operands.erase(Operands.begin() + 1); 2976 static_cast<X86Operand &>(*Operands[0]).setTokenValue("int3"); 2977 } 2978 } 2979 2980 // Transforms "xlat mem8" into "xlatb" 2981 if ((Name == "xlat" || Name == "xlatb") && Operands.size() == 2) { 2982 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]); 2983 if (Op1.isMem8()) { 2984 Warning(Op1.getStartLoc(), "memory operand is only for determining the " 2985 "size, (R|E)BX will be used for the location"); 2986 Operands.pop_back(); 2987 static_cast<X86Operand &>(*Operands[0]).setTokenValue("xlatb"); 2988 } 2989 } 2990 2991 if (Flags) 2992 Operands.push_back(X86Operand::CreatePrefix(Flags, NameLoc, NameLoc)); 2993 return false; 2994 } 2995 2996 bool X86AsmParser::processInstruction(MCInst &Inst, const OperandVector &Ops) { 2997 const MCRegisterInfo *MRI = getContext().getRegisterInfo(); 2998 2999 switch (Inst.getOpcode()) { 3000 default: return false; 3001 case X86::VMOVZPQILo2PQIrr: 3002 case X86::VMOVAPDrr: 3003 case X86::VMOVAPDYrr: 3004 case X86::VMOVAPSrr: 3005 case X86::VMOVAPSYrr: 3006 case X86::VMOVDQArr: 3007 case X86::VMOVDQAYrr: 3008 case X86::VMOVDQUrr: 3009 case X86::VMOVDQUYrr: 3010 case X86::VMOVUPDrr: 3011 case X86::VMOVUPDYrr: 3012 case X86::VMOVUPSrr: 3013 case X86::VMOVUPSYrr: { 3014 // We can get a smaller encoding by using VEX.R instead of VEX.B if one of 3015 // the registers is extended, but other isn't. 3016 if (ForcedVEXEncoding == VEXEncoding_VEX3 || 3017 MRI->getEncodingValue(Inst.getOperand(0).getReg()) >= 8 || 3018 MRI->getEncodingValue(Inst.getOperand(1).getReg()) < 8) 3019 return false; 3020 3021 unsigned NewOpc; 3022 switch (Inst.getOpcode()) { 3023 default: llvm_unreachable("Invalid opcode"); 3024 case X86::VMOVZPQILo2PQIrr: NewOpc = X86::VMOVPQI2QIrr; break; 3025 case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break; 3026 case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break; 3027 case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break; 3028 case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break; 3029 case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break; 3030 case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break; 3031 case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break; 3032 case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break; 3033 case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break; 3034 case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break; 3035 case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break; 3036 case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break; 3037 } 3038 Inst.setOpcode(NewOpc); 3039 return true; 3040 } 3041 case X86::VMOVSDrr: 3042 case X86::VMOVSSrr: { 3043 // We can get a smaller encoding by using VEX.R instead of VEX.B if one of 3044 // the registers is extended, but other isn't. 3045 if (ForcedVEXEncoding == VEXEncoding_VEX3 || 3046 MRI->getEncodingValue(Inst.getOperand(0).getReg()) >= 8 || 3047 MRI->getEncodingValue(Inst.getOperand(2).getReg()) < 8) 3048 return false; 3049 3050 unsigned NewOpc; 3051 switch (Inst.getOpcode()) { 3052 default: llvm_unreachable("Invalid opcode"); 3053 case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break; 3054 case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break; 3055 } 3056 Inst.setOpcode(NewOpc); 3057 return true; 3058 } 3059 } 3060 } 3061 3062 bool X86AsmParser::validateInstruction(MCInst &Inst, const OperandVector &Ops) { 3063 const MCRegisterInfo *MRI = getContext().getRegisterInfo(); 3064 3065 switch (Inst.getOpcode()) { 3066 case X86::VGATHERDPDYrm: 3067 case X86::VGATHERDPDrm: 3068 case X86::VGATHERDPSYrm: 3069 case X86::VGATHERDPSrm: 3070 case X86::VGATHERQPDYrm: 3071 case X86::VGATHERQPDrm: 3072 case X86::VGATHERQPSYrm: 3073 case X86::VGATHERQPSrm: 3074 case X86::VPGATHERDDYrm: 3075 case X86::VPGATHERDDrm: 3076 case X86::VPGATHERDQYrm: 3077 case X86::VPGATHERDQrm: 3078 case X86::VPGATHERQDYrm: 3079 case X86::VPGATHERQDrm: 3080 case X86::VPGATHERQQYrm: 3081 case X86::VPGATHERQQrm: { 3082 unsigned Dest = MRI->getEncodingValue(Inst.getOperand(0).getReg()); 3083 unsigned Mask = MRI->getEncodingValue(Inst.getOperand(1).getReg()); 3084 unsigned Index = 3085 MRI->getEncodingValue(Inst.getOperand(3 + X86::AddrIndexReg).getReg()); 3086 if (Dest == Mask || Dest == Index || Mask == Index) 3087 return Warning(Ops[0]->getStartLoc(), "mask, index, and destination " 3088 "registers should be distinct"); 3089 break; 3090 } 3091 case X86::VGATHERDPDZ128rm: 3092 case X86::VGATHERDPDZ256rm: 3093 case X86::VGATHERDPDZrm: 3094 case X86::VGATHERDPSZ128rm: 3095 case X86::VGATHERDPSZ256rm: 3096 case X86::VGATHERDPSZrm: 3097 case X86::VGATHERQPDZ128rm: 3098 case X86::VGATHERQPDZ256rm: 3099 case X86::VGATHERQPDZrm: 3100 case X86::VGATHERQPSZ128rm: 3101 case X86::VGATHERQPSZ256rm: 3102 case X86::VGATHERQPSZrm: 3103 case X86::VPGATHERDDZ128rm: 3104 case X86::VPGATHERDDZ256rm: 3105 case X86::VPGATHERDDZrm: 3106 case X86::VPGATHERDQZ128rm: 3107 case X86::VPGATHERDQZ256rm: 3108 case X86::VPGATHERDQZrm: 3109 case X86::VPGATHERQDZ128rm: 3110 case X86::VPGATHERQDZ256rm: 3111 case X86::VPGATHERQDZrm: 3112 case X86::VPGATHERQQZ128rm: 3113 case X86::VPGATHERQQZ256rm: 3114 case X86::VPGATHERQQZrm: { 3115 unsigned Dest = MRI->getEncodingValue(Inst.getOperand(0).getReg()); 3116 unsigned Index = 3117 MRI->getEncodingValue(Inst.getOperand(4 + X86::AddrIndexReg).getReg()); 3118 if (Dest == Index) 3119 return Warning(Ops[0]->getStartLoc(), "index and destination registers " 3120 "should be distinct"); 3121 break; 3122 } 3123 case X86::V4FMADDPSrm: 3124 case X86::V4FMADDPSrmk: 3125 case X86::V4FMADDPSrmkz: 3126 case X86::V4FMADDSSrm: 3127 case X86::V4FMADDSSrmk: 3128 case X86::V4FMADDSSrmkz: 3129 case X86::V4FNMADDPSrm: 3130 case X86::V4FNMADDPSrmk: 3131 case X86::V4FNMADDPSrmkz: 3132 case X86::V4FNMADDSSrm: 3133 case X86::V4FNMADDSSrmk: 3134 case X86::V4FNMADDSSrmkz: 3135 case X86::VP4DPWSSDSrm: 3136 case X86::VP4DPWSSDSrmk: 3137 case X86::VP4DPWSSDSrmkz: 3138 case X86::VP4DPWSSDrm: 3139 case X86::VP4DPWSSDrmk: 3140 case X86::VP4DPWSSDrmkz: { 3141 unsigned Src2 = Inst.getOperand(Inst.getNumOperands() - 3142 X86::AddrNumOperands - 1).getReg(); 3143 unsigned Src2Enc = MRI->getEncodingValue(Src2); 3144 if (Src2Enc % 4 != 0) { 3145 StringRef RegName = X86IntelInstPrinter::getRegisterName(Src2); 3146 unsigned GroupStart = (Src2Enc / 4) * 4; 3147 unsigned GroupEnd = GroupStart + 3; 3148 return Warning(Ops[0]->getStartLoc(), 3149 "source register '" + RegName + "' implicitly denotes '" + 3150 RegName.take_front(3) + Twine(GroupStart) + "' to '" + 3151 RegName.take_front(3) + Twine(GroupEnd) + 3152 "' source group"); 3153 } 3154 break; 3155 } 3156 } 3157 3158 return false; 3159 } 3160 3161 static const char *getSubtargetFeatureName(uint64_t Val); 3162 3163 void X86AsmParser::emitWarningForSpecialLVIInstruction(SMLoc Loc) { 3164 Warning(Loc, "Instruction may be vulnerable to LVI and " 3165 "requires manual mitigation"); 3166 Note(SMLoc(), "See https://software.intel.com/" 3167 "security-software-guidance/insights/" 3168 "deep-dive-load-value-injection#specialinstructions" 3169 " for more information"); 3170 } 3171 3172 /// RET instructions and also instructions that indirect calls/jumps from memory 3173 /// combine a load and a branch within a single instruction. To mitigate these 3174 /// instructions against LVI, they must be decomposed into separate load and 3175 /// branch instructions, with an LFENCE in between. For more details, see: 3176 /// - X86LoadValueInjectionRetHardening.cpp 3177 /// - X86LoadValueInjectionIndirectThunks.cpp 3178 /// - https://software.intel.com/security-software-guidance/insights/deep-dive-load-value-injection 3179 /// 3180 /// Returns `true` if a mitigation was applied or warning was emitted. 3181 bool X86AsmParser::applyLVICFIMitigation(MCInst &Inst) { 3182 // Information on control-flow instructions that require manual mitigation can 3183 // be found here: 3184 // https://software.intel.com/security-software-guidance/insights/deep-dive-load-value-injection#specialinstructions 3185 switch (Inst.getOpcode()) { 3186 case X86::RETW: 3187 case X86::RETL: 3188 case X86::RETQ: 3189 case X86::RETIL: 3190 case X86::RETIQ: 3191 case X86::RETIW: 3192 case X86::JMP16m: 3193 case X86::JMP32m: 3194 case X86::JMP64m: 3195 case X86::CALL16m: 3196 case X86::CALL32m: 3197 case X86::CALL64m: 3198 emitWarningForSpecialLVIInstruction(Inst.getLoc()); 3199 return true; 3200 } 3201 return false; 3202 } 3203 3204 /// To mitigate LVI, every instruction that performs a load can be followed by 3205 /// an LFENCE instruction to squash any potential mis-speculation. There are 3206 /// some instructions that require additional considerations, and may requre 3207 /// manual mitigation. For more details, see: 3208 /// https://software.intel.com/security-software-guidance/insights/deep-dive-load-value-injection 3209 /// 3210 /// Returns `true` if a mitigation was applied or warning was emitted. 3211 bool X86AsmParser::applyLVILoadHardeningMitigation(MCInst &Inst, 3212 MCStreamer &Out) { 3213 auto Opcode = Inst.getOpcode(); 3214 auto Flags = Inst.getFlags(); 3215 if ((Flags & X86::IP_HAS_REPEAT) || (Flags & X86::IP_HAS_REPEAT_NE)) { 3216 // Information on REP string instructions that require manual mitigation can 3217 // be found here: 3218 // https://software.intel.com/security-software-guidance/insights/deep-dive-load-value-injection#specialinstructions 3219 switch (Opcode) { 3220 case X86::CMPSB: 3221 case X86::CMPSW: 3222 case X86::CMPSL: 3223 case X86::CMPSQ: 3224 case X86::SCASB: 3225 case X86::SCASW: 3226 case X86::SCASL: 3227 case X86::SCASQ: 3228 emitWarningForSpecialLVIInstruction(Inst.getLoc()); 3229 return true; 3230 } 3231 } else if (Opcode == X86::REP_PREFIX || Opcode == X86::REPNE_PREFIX) { 3232 // If a REP instruction is found on its own line, it may or may not be 3233 // followed by a vulnerable instruction. Emit a warning just in case. 3234 emitWarningForSpecialLVIInstruction(Inst.getLoc()); 3235 return true; 3236 } 3237 3238 const MCInstrDesc &MCID = MII.get(Inst.getOpcode()); 3239 // LFENCE has the mayLoad property, don't double fence. 3240 if (MCID.mayLoad() && Inst.getOpcode() != X86::LFENCE) { 3241 MCInst FenceInst; 3242 FenceInst.setOpcode(X86::LFENCE); 3243 FenceInst.setLoc(Inst.getLoc()); 3244 Out.emitInstruction(FenceInst, getSTI()); 3245 return true; 3246 } 3247 return false; 3248 } 3249 3250 void X86AsmParser::emitInstruction(MCInst &Inst, OperandVector &Operands, 3251 MCStreamer &Out) { 3252 Out.emitInstruction(Inst, getSTI()); 3253 3254 if (LVIInlineAsmHardening) { 3255 if (getSTI().getFeatureBits()[X86::FeatureLVIControlFlowIntegrity] && 3256 applyLVICFIMitigation(Inst)) 3257 return; 3258 if (getSTI().getFeatureBits()[X86::FeatureLVILoadHardening]) 3259 applyLVILoadHardeningMitigation(Inst, Out); 3260 } 3261 } 3262 3263 bool X86AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode, 3264 OperandVector &Operands, 3265 MCStreamer &Out, uint64_t &ErrorInfo, 3266 bool MatchingInlineAsm) { 3267 if (isParsingIntelSyntax()) 3268 return MatchAndEmitIntelInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo, 3269 MatchingInlineAsm); 3270 return MatchAndEmitATTInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo, 3271 MatchingInlineAsm); 3272 } 3273 3274 void X86AsmParser::MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op, 3275 OperandVector &Operands, MCStreamer &Out, 3276 bool MatchingInlineAsm) { 3277 // FIXME: This should be replaced with a real .td file alias mechanism. 3278 // Also, MatchInstructionImpl should actually *do* the EmitInstruction 3279 // call. 3280 const char *Repl = StringSwitch<const char *>(Op.getToken()) 3281 .Case("finit", "fninit") 3282 .Case("fsave", "fnsave") 3283 .Case("fstcw", "fnstcw") 3284 .Case("fstcww", "fnstcw") 3285 .Case("fstenv", "fnstenv") 3286 .Case("fstsw", "fnstsw") 3287 .Case("fstsww", "fnstsw") 3288 .Case("fclex", "fnclex") 3289 .Default(nullptr); 3290 if (Repl) { 3291 MCInst Inst; 3292 Inst.setOpcode(X86::WAIT); 3293 Inst.setLoc(IDLoc); 3294 if (!MatchingInlineAsm) 3295 emitInstruction(Inst, Operands, Out); 3296 Operands[0] = X86Operand::CreateToken(Repl, IDLoc); 3297 } 3298 } 3299 3300 bool X86AsmParser::ErrorMissingFeature(SMLoc IDLoc, 3301 const FeatureBitset &MissingFeatures, 3302 bool MatchingInlineAsm) { 3303 assert(MissingFeatures.any() && "Unknown missing feature!"); 3304 SmallString<126> Msg; 3305 raw_svector_ostream OS(Msg); 3306 OS << "instruction requires:"; 3307 for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i) { 3308 if (MissingFeatures[i]) 3309 OS << ' ' << getSubtargetFeatureName(i); 3310 } 3311 return Error(IDLoc, OS.str(), SMRange(), MatchingInlineAsm); 3312 } 3313 3314 static unsigned getPrefixes(OperandVector &Operands) { 3315 unsigned Result = 0; 3316 X86Operand &Prefix = static_cast<X86Operand &>(*Operands.back()); 3317 if (Prefix.isPrefix()) { 3318 Result = Prefix.getPrefix(); 3319 Operands.pop_back(); 3320 } 3321 return Result; 3322 } 3323 3324 unsigned X86AsmParser::checkTargetMatchPredicate(MCInst &Inst) { 3325 unsigned Opc = Inst.getOpcode(); 3326 const MCInstrDesc &MCID = MII.get(Opc); 3327 3328 if (ForcedVEXEncoding == VEXEncoding_EVEX && 3329 (MCID.TSFlags & X86II::EncodingMask) != X86II::EVEX) 3330 return Match_Unsupported; 3331 3332 if ((ForcedVEXEncoding == VEXEncoding_VEX || 3333 ForcedVEXEncoding == VEXEncoding_VEX3) && 3334 (MCID.TSFlags & X86II::EncodingMask) != X86II::VEX) 3335 return Match_Unsupported; 3336 3337 // These instructions match ambiguously with their VEX encoded counterparts 3338 // and appear first in the matching table. Reject them unless we're forcing 3339 // EVEX encoding. 3340 // FIXME: We really need a way to break the ambiguity. 3341 switch (Opc) { 3342 case X86::VCVTSD2SIZrm_Int: 3343 case X86::VCVTSD2SI64Zrm_Int: 3344 case X86::VCVTSS2SIZrm_Int: 3345 case X86::VCVTSS2SI64Zrm_Int: 3346 case X86::VCVTTSD2SIZrm: case X86::VCVTTSD2SIZrm_Int: 3347 case X86::VCVTTSD2SI64Zrm: case X86::VCVTTSD2SI64Zrm_Int: 3348 case X86::VCVTTSS2SIZrm: case X86::VCVTTSS2SIZrm_Int: 3349 case X86::VCVTTSS2SI64Zrm: case X86::VCVTTSS2SI64Zrm_Int: 3350 if (ForcedVEXEncoding != VEXEncoding_EVEX) 3351 return Match_Unsupported; 3352 break; 3353 } 3354 3355 return Match_Success; 3356 } 3357 3358 bool X86AsmParser::MatchAndEmitATTInstruction(SMLoc IDLoc, unsigned &Opcode, 3359 OperandVector &Operands, 3360 MCStreamer &Out, 3361 uint64_t &ErrorInfo, 3362 bool MatchingInlineAsm) { 3363 assert(!Operands.empty() && "Unexpect empty operand list!"); 3364 assert((*Operands[0]).isToken() && "Leading operand should always be a mnemonic!"); 3365 SMRange EmptyRange = None; 3366 3367 // First, handle aliases that expand to multiple instructions. 3368 MatchFPUWaitAlias(IDLoc, static_cast<X86Operand &>(*Operands[0]), Operands, 3369 Out, MatchingInlineAsm); 3370 X86Operand &Op = static_cast<X86Operand &>(*Operands[0]); 3371 unsigned Prefixes = getPrefixes(Operands); 3372 3373 MCInst Inst; 3374 3375 // If VEX3 encoding is forced, we need to pass the USE_VEX3 flag to the 3376 // encoder. 3377 if (ForcedVEXEncoding == VEXEncoding_VEX3) 3378 Prefixes |= X86::IP_USE_VEX3; 3379 3380 if (Prefixes) 3381 Inst.setFlags(Prefixes); 3382 3383 // First, try a direct match. 3384 FeatureBitset MissingFeatures; 3385 unsigned OriginalError = MatchInstruction(Operands, Inst, ErrorInfo, 3386 MissingFeatures, MatchingInlineAsm, 3387 isParsingIntelSyntax()); 3388 switch (OriginalError) { 3389 default: llvm_unreachable("Unexpected match result!"); 3390 case Match_Success: 3391 if (!MatchingInlineAsm && validateInstruction(Inst, Operands)) 3392 return true; 3393 // Some instructions need post-processing to, for example, tweak which 3394 // encoding is selected. Loop on it while changes happen so the 3395 // individual transformations can chain off each other. 3396 if (!MatchingInlineAsm) 3397 while (processInstruction(Inst, Operands)) 3398 ; 3399 3400 Inst.setLoc(IDLoc); 3401 if (!MatchingInlineAsm) 3402 emitInstruction(Inst, Operands, Out); 3403 Opcode = Inst.getOpcode(); 3404 return false; 3405 case Match_InvalidImmUnsignedi4: { 3406 SMLoc ErrorLoc = ((X86Operand &)*Operands[ErrorInfo]).getStartLoc(); 3407 if (ErrorLoc == SMLoc()) 3408 ErrorLoc = IDLoc; 3409 return Error(ErrorLoc, "immediate must be an integer in range [0, 15]", 3410 EmptyRange, MatchingInlineAsm); 3411 } 3412 case Match_MissingFeature: 3413 return ErrorMissingFeature(IDLoc, MissingFeatures, MatchingInlineAsm); 3414 case Match_InvalidOperand: 3415 case Match_MnemonicFail: 3416 case Match_Unsupported: 3417 break; 3418 } 3419 if (Op.getToken().empty()) { 3420 Error(IDLoc, "instruction must have size higher than 0", EmptyRange, 3421 MatchingInlineAsm); 3422 return true; 3423 } 3424 3425 // FIXME: Ideally, we would only attempt suffix matches for things which are 3426 // valid prefixes, and we could just infer the right unambiguous 3427 // type. However, that requires substantially more matcher support than the 3428 // following hack. 3429 3430 // Change the operand to point to a temporary token. 3431 StringRef Base = Op.getToken(); 3432 SmallString<16> Tmp; 3433 Tmp += Base; 3434 Tmp += ' '; 3435 Op.setTokenValue(Tmp); 3436 3437 // If this instruction starts with an 'f', then it is a floating point stack 3438 // instruction. These come in up to three forms for 32-bit, 64-bit, and 3439 // 80-bit floating point, which use the suffixes s,l,t respectively. 3440 // 3441 // Otherwise, we assume that this may be an integer instruction, which comes 3442 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively. 3443 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0"; 3444 3445 // Check for the various suffix matches. 3446 uint64_t ErrorInfoIgnore; 3447 FeatureBitset ErrorInfoMissingFeatures; // Init suppresses compiler warnings. 3448 unsigned Match[4]; 3449 3450 for (unsigned I = 0, E = array_lengthof(Match); I != E; ++I) { 3451 Tmp.back() = Suffixes[I]; 3452 Match[I] = MatchInstruction(Operands, Inst, ErrorInfoIgnore, 3453 MissingFeatures, MatchingInlineAsm, 3454 isParsingIntelSyntax()); 3455 // If this returned as a missing feature failure, remember that. 3456 if (Match[I] == Match_MissingFeature) 3457 ErrorInfoMissingFeatures = MissingFeatures; 3458 } 3459 3460 // Restore the old token. 3461 Op.setTokenValue(Base); 3462 3463 // If exactly one matched, then we treat that as a successful match (and the 3464 // instruction will already have been filled in correctly, since the failing 3465 // matches won't have modified it). 3466 unsigned NumSuccessfulMatches = 3467 std::count(std::begin(Match), std::end(Match), Match_Success); 3468 if (NumSuccessfulMatches == 1) { 3469 Inst.setLoc(IDLoc); 3470 if (!MatchingInlineAsm) 3471 emitInstruction(Inst, Operands, Out); 3472 Opcode = Inst.getOpcode(); 3473 return false; 3474 } 3475 3476 // Otherwise, the match failed, try to produce a decent error message. 3477 3478 // If we had multiple suffix matches, then identify this as an ambiguous 3479 // match. 3480 if (NumSuccessfulMatches > 1) { 3481 char MatchChars[4]; 3482 unsigned NumMatches = 0; 3483 for (unsigned I = 0, E = array_lengthof(Match); I != E; ++I) 3484 if (Match[I] == Match_Success) 3485 MatchChars[NumMatches++] = Suffixes[I]; 3486 3487 SmallString<126> Msg; 3488 raw_svector_ostream OS(Msg); 3489 OS << "ambiguous instructions require an explicit suffix (could be "; 3490 for (unsigned i = 0; i != NumMatches; ++i) { 3491 if (i != 0) 3492 OS << ", "; 3493 if (i + 1 == NumMatches) 3494 OS << "or "; 3495 OS << "'" << Base << MatchChars[i] << "'"; 3496 } 3497 OS << ")"; 3498 Error(IDLoc, OS.str(), EmptyRange, MatchingInlineAsm); 3499 return true; 3500 } 3501 3502 // Okay, we know that none of the variants matched successfully. 3503 3504 // If all of the instructions reported an invalid mnemonic, then the original 3505 // mnemonic was invalid. 3506 if (std::count(std::begin(Match), std::end(Match), Match_MnemonicFail) == 4) { 3507 if (OriginalError == Match_MnemonicFail) 3508 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'", 3509 Op.getLocRange(), MatchingInlineAsm); 3510 3511 if (OriginalError == Match_Unsupported) 3512 return Error(IDLoc, "unsupported instruction", EmptyRange, 3513 MatchingInlineAsm); 3514 3515 assert(OriginalError == Match_InvalidOperand && "Unexpected error"); 3516 // Recover location info for the operand if we know which was the problem. 3517 if (ErrorInfo != ~0ULL) { 3518 if (ErrorInfo >= Operands.size()) 3519 return Error(IDLoc, "too few operands for instruction", EmptyRange, 3520 MatchingInlineAsm); 3521 3522 X86Operand &Operand = (X86Operand &)*Operands[ErrorInfo]; 3523 if (Operand.getStartLoc().isValid()) { 3524 SMRange OperandRange = Operand.getLocRange(); 3525 return Error(Operand.getStartLoc(), "invalid operand for instruction", 3526 OperandRange, MatchingInlineAsm); 3527 } 3528 } 3529 3530 return Error(IDLoc, "invalid operand for instruction", EmptyRange, 3531 MatchingInlineAsm); 3532 } 3533 3534 // If one instruction matched as unsupported, report this as unsupported. 3535 if (std::count(std::begin(Match), std::end(Match), 3536 Match_Unsupported) == 1) { 3537 return Error(IDLoc, "unsupported instruction", EmptyRange, 3538 MatchingInlineAsm); 3539 } 3540 3541 // If one instruction matched with a missing feature, report this as a 3542 // missing feature. 3543 if (std::count(std::begin(Match), std::end(Match), 3544 Match_MissingFeature) == 1) { 3545 ErrorInfo = Match_MissingFeature; 3546 return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeatures, 3547 MatchingInlineAsm); 3548 } 3549 3550 // If one instruction matched with an invalid operand, report this as an 3551 // operand failure. 3552 if (std::count(std::begin(Match), std::end(Match), 3553 Match_InvalidOperand) == 1) { 3554 return Error(IDLoc, "invalid operand for instruction", EmptyRange, 3555 MatchingInlineAsm); 3556 } 3557 3558 // If all of these were an outright failure, report it in a useless way. 3559 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix", 3560 EmptyRange, MatchingInlineAsm); 3561 return true; 3562 } 3563 3564 bool X86AsmParser::MatchAndEmitIntelInstruction(SMLoc IDLoc, unsigned &Opcode, 3565 OperandVector &Operands, 3566 MCStreamer &Out, 3567 uint64_t &ErrorInfo, 3568 bool MatchingInlineAsm) { 3569 assert(!Operands.empty() && "Unexpect empty operand list!"); 3570 assert((*Operands[0]).isToken() && "Leading operand should always be a mnemonic!"); 3571 StringRef Mnemonic = (static_cast<X86Operand &>(*Operands[0])).getToken(); 3572 SMRange EmptyRange = None; 3573 StringRef Base = (static_cast<X86Operand &>(*Operands[0])).getToken(); 3574 unsigned Prefixes = getPrefixes(Operands); 3575 3576 // First, handle aliases that expand to multiple instructions. 3577 MatchFPUWaitAlias(IDLoc, static_cast<X86Operand &>(*Operands[0]), Operands, Out, MatchingInlineAsm); 3578 X86Operand &Op = static_cast<X86Operand &>(*Operands[0]); 3579 3580 MCInst Inst; 3581 3582 // If VEX3 encoding is forced, we need to pass the USE_VEX3 flag to the 3583 // encoder. 3584 if (ForcedVEXEncoding == VEXEncoding_VEX3) 3585 Prefixes |= X86::IP_USE_VEX3; 3586 3587 if (Prefixes) 3588 Inst.setFlags(Prefixes); 3589 3590 // Find one unsized memory operand, if present. 3591 X86Operand *UnsizedMemOp = nullptr; 3592 for (const auto &Op : Operands) { 3593 X86Operand *X86Op = static_cast<X86Operand *>(Op.get()); 3594 if (X86Op->isMemUnsized()) { 3595 UnsizedMemOp = X86Op; 3596 // Have we found an unqualified memory operand, 3597 // break. IA allows only one memory operand. 3598 break; 3599 } 3600 } 3601 3602 // Allow some instructions to have implicitly pointer-sized operands. This is 3603 // compatible with gas. 3604 if (UnsizedMemOp) { 3605 static const char *const PtrSizedInstrs[] = {"call", "jmp", "push"}; 3606 for (const char *Instr : PtrSizedInstrs) { 3607 if (Mnemonic == Instr) { 3608 UnsizedMemOp->Mem.Size = getPointerWidth(); 3609 break; 3610 } 3611 } 3612 } 3613 3614 SmallVector<unsigned, 8> Match; 3615 FeatureBitset ErrorInfoMissingFeatures; 3616 FeatureBitset MissingFeatures; 3617 3618 // If unsized push has immediate operand we should default the default pointer 3619 // size for the size. 3620 if (Mnemonic == "push" && Operands.size() == 2) { 3621 auto *X86Op = static_cast<X86Operand *>(Operands[1].get()); 3622 if (X86Op->isImm()) { 3623 // If it's not a constant fall through and let remainder take care of it. 3624 const auto *CE = dyn_cast<MCConstantExpr>(X86Op->getImm()); 3625 unsigned Size = getPointerWidth(); 3626 if (CE && 3627 (isIntN(Size, CE->getValue()) || isUIntN(Size, CE->getValue()))) { 3628 SmallString<16> Tmp; 3629 Tmp += Base; 3630 Tmp += (is64BitMode()) 3631 ? "q" 3632 : (is32BitMode()) ? "l" : (is16BitMode()) ? "w" : " "; 3633 Op.setTokenValue(Tmp); 3634 // Do match in ATT mode to allow explicit suffix usage. 3635 Match.push_back(MatchInstruction(Operands, Inst, ErrorInfo, 3636 MissingFeatures, MatchingInlineAsm, 3637 false /*isParsingIntelSyntax()*/)); 3638 Op.setTokenValue(Base); 3639 } 3640 } 3641 } 3642 3643 // If an unsized memory operand is present, try to match with each memory 3644 // operand size. In Intel assembly, the size is not part of the instruction 3645 // mnemonic. 3646 if (UnsizedMemOp && UnsizedMemOp->isMemUnsized()) { 3647 static const unsigned MopSizes[] = {8, 16, 32, 64, 80, 128, 256, 512}; 3648 for (unsigned Size : MopSizes) { 3649 UnsizedMemOp->Mem.Size = Size; 3650 uint64_t ErrorInfoIgnore; 3651 unsigned LastOpcode = Inst.getOpcode(); 3652 unsigned M = MatchInstruction(Operands, Inst, ErrorInfoIgnore, 3653 MissingFeatures, MatchingInlineAsm, 3654 isParsingIntelSyntax()); 3655 if (Match.empty() || LastOpcode != Inst.getOpcode()) 3656 Match.push_back(M); 3657 3658 // If this returned as a missing feature failure, remember that. 3659 if (Match.back() == Match_MissingFeature) 3660 ErrorInfoMissingFeatures = MissingFeatures; 3661 } 3662 3663 // Restore the size of the unsized memory operand if we modified it. 3664 UnsizedMemOp->Mem.Size = 0; 3665 } 3666 3667 // If we haven't matched anything yet, this is not a basic integer or FPU 3668 // operation. There shouldn't be any ambiguity in our mnemonic table, so try 3669 // matching with the unsized operand. 3670 if (Match.empty()) { 3671 Match.push_back(MatchInstruction( 3672 Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm, 3673 isParsingIntelSyntax())); 3674 // If this returned as a missing feature failure, remember that. 3675 if (Match.back() == Match_MissingFeature) 3676 ErrorInfoMissingFeatures = MissingFeatures; 3677 } 3678 3679 // Restore the size of the unsized memory operand if we modified it. 3680 if (UnsizedMemOp) 3681 UnsizedMemOp->Mem.Size = 0; 3682 3683 // If it's a bad mnemonic, all results will be the same. 3684 if (Match.back() == Match_MnemonicFail) { 3685 return Error(IDLoc, "invalid instruction mnemonic '" + Mnemonic + "'", 3686 Op.getLocRange(), MatchingInlineAsm); 3687 } 3688 3689 unsigned NumSuccessfulMatches = 3690 std::count(std::begin(Match), std::end(Match), Match_Success); 3691 3692 // If matching was ambiguous and we had size information from the frontend, 3693 // try again with that. This handles cases like "movxz eax, m8/m16". 3694 if (UnsizedMemOp && NumSuccessfulMatches > 1 && 3695 UnsizedMemOp->getMemFrontendSize()) { 3696 UnsizedMemOp->Mem.Size = UnsizedMemOp->getMemFrontendSize(); 3697 unsigned M = MatchInstruction( 3698 Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm, 3699 isParsingIntelSyntax()); 3700 if (M == Match_Success) 3701 NumSuccessfulMatches = 1; 3702 3703 // Add a rewrite that encodes the size information we used from the 3704 // frontend. 3705 InstInfo->AsmRewrites->emplace_back( 3706 AOK_SizeDirective, UnsizedMemOp->getStartLoc(), 3707 /*Len=*/0, UnsizedMemOp->getMemFrontendSize()); 3708 } 3709 3710 // If exactly one matched, then we treat that as a successful match (and the 3711 // instruction will already have been filled in correctly, since the failing 3712 // matches won't have modified it). 3713 if (NumSuccessfulMatches == 1) { 3714 if (!MatchingInlineAsm && validateInstruction(Inst, Operands)) 3715 return true; 3716 // Some instructions need post-processing to, for example, tweak which 3717 // encoding is selected. Loop on it while changes happen so the individual 3718 // transformations can chain off each other. 3719 if (!MatchingInlineAsm) 3720 while (processInstruction(Inst, Operands)) 3721 ; 3722 Inst.setLoc(IDLoc); 3723 if (!MatchingInlineAsm) 3724 emitInstruction(Inst, Operands, Out); 3725 Opcode = Inst.getOpcode(); 3726 return false; 3727 } else if (NumSuccessfulMatches > 1) { 3728 assert(UnsizedMemOp && 3729 "multiple matches only possible with unsized memory operands"); 3730 return Error(UnsizedMemOp->getStartLoc(), 3731 "ambiguous operand size for instruction '" + Mnemonic + "\'", 3732 UnsizedMemOp->getLocRange()); 3733 } 3734 3735 // If one instruction matched as unsupported, report this as unsupported. 3736 if (std::count(std::begin(Match), std::end(Match), 3737 Match_Unsupported) == 1) { 3738 return Error(IDLoc, "unsupported instruction", EmptyRange, 3739 MatchingInlineAsm); 3740 } 3741 3742 // If one instruction matched with a missing feature, report this as a 3743 // missing feature. 3744 if (std::count(std::begin(Match), std::end(Match), 3745 Match_MissingFeature) == 1) { 3746 ErrorInfo = Match_MissingFeature; 3747 return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeatures, 3748 MatchingInlineAsm); 3749 } 3750 3751 // If one instruction matched with an invalid operand, report this as an 3752 // operand failure. 3753 if (std::count(std::begin(Match), std::end(Match), 3754 Match_InvalidOperand) == 1) { 3755 return Error(IDLoc, "invalid operand for instruction", EmptyRange, 3756 MatchingInlineAsm); 3757 } 3758 3759 if (std::count(std::begin(Match), std::end(Match), 3760 Match_InvalidImmUnsignedi4) == 1) { 3761 SMLoc ErrorLoc = ((X86Operand &)*Operands[ErrorInfo]).getStartLoc(); 3762 if (ErrorLoc == SMLoc()) 3763 ErrorLoc = IDLoc; 3764 return Error(ErrorLoc, "immediate must be an integer in range [0, 15]", 3765 EmptyRange, MatchingInlineAsm); 3766 } 3767 3768 // If all of these were an outright failure, report it in a useless way. 3769 return Error(IDLoc, "unknown instruction mnemonic", EmptyRange, 3770 MatchingInlineAsm); 3771 } 3772 3773 bool X86AsmParser::OmitRegisterFromClobberLists(unsigned RegNo) { 3774 return X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo); 3775 } 3776 3777 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) { 3778 MCAsmParser &Parser = getParser(); 3779 StringRef IDVal = DirectiveID.getIdentifier(); 3780 if (IDVal.startswith(".code")) 3781 return ParseDirectiveCode(IDVal, DirectiveID.getLoc()); 3782 else if (IDVal.startswith(".att_syntax")) { 3783 if (getLexer().isNot(AsmToken::EndOfStatement)) { 3784 if (Parser.getTok().getString() == "prefix") 3785 Parser.Lex(); 3786 else if (Parser.getTok().getString() == "noprefix") 3787 return Error(DirectiveID.getLoc(), "'.att_syntax noprefix' is not " 3788 "supported: registers must have a " 3789 "'%' prefix in .att_syntax"); 3790 } 3791 getParser().setAssemblerDialect(0); 3792 return false; 3793 } else if (IDVal.startswith(".intel_syntax")) { 3794 getParser().setAssemblerDialect(1); 3795 if (getLexer().isNot(AsmToken::EndOfStatement)) { 3796 if (Parser.getTok().getString() == "noprefix") 3797 Parser.Lex(); 3798 else if (Parser.getTok().getString() == "prefix") 3799 return Error(DirectiveID.getLoc(), "'.intel_syntax prefix' is not " 3800 "supported: registers must not have " 3801 "a '%' prefix in .intel_syntax"); 3802 } 3803 return false; 3804 } else if (IDVal == ".even") 3805 return parseDirectiveEven(DirectiveID.getLoc()); 3806 else if (IDVal == ".cv_fpo_proc") 3807 return parseDirectiveFPOProc(DirectiveID.getLoc()); 3808 else if (IDVal == ".cv_fpo_setframe") 3809 return parseDirectiveFPOSetFrame(DirectiveID.getLoc()); 3810 else if (IDVal == ".cv_fpo_pushreg") 3811 return parseDirectiveFPOPushReg(DirectiveID.getLoc()); 3812 else if (IDVal == ".cv_fpo_stackalloc") 3813 return parseDirectiveFPOStackAlloc(DirectiveID.getLoc()); 3814 else if (IDVal == ".cv_fpo_stackalign") 3815 return parseDirectiveFPOStackAlign(DirectiveID.getLoc()); 3816 else if (IDVal == ".cv_fpo_endprologue") 3817 return parseDirectiveFPOEndPrologue(DirectiveID.getLoc()); 3818 else if (IDVal == ".cv_fpo_endproc") 3819 return parseDirectiveFPOEndProc(DirectiveID.getLoc()); 3820 else if (IDVal == ".seh_pushreg") 3821 return parseDirectiveSEHPushReg(DirectiveID.getLoc()); 3822 else if (IDVal == ".seh_setframe") 3823 return parseDirectiveSEHSetFrame(DirectiveID.getLoc()); 3824 else if (IDVal == ".seh_savereg") 3825 return parseDirectiveSEHSaveReg(DirectiveID.getLoc()); 3826 else if (IDVal == ".seh_savexmm") 3827 return parseDirectiveSEHSaveXMM(DirectiveID.getLoc()); 3828 else if (IDVal == ".seh_pushframe") 3829 return parseDirectiveSEHPushFrame(DirectiveID.getLoc()); 3830 3831 return true; 3832 } 3833 3834 /// parseDirectiveEven 3835 /// ::= .even 3836 bool X86AsmParser::parseDirectiveEven(SMLoc L) { 3837 if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive")) 3838 return false; 3839 3840 const MCSection *Section = getStreamer().getCurrentSectionOnly(); 3841 if (!Section) { 3842 getStreamer().InitSections(false); 3843 Section = getStreamer().getCurrentSectionOnly(); 3844 } 3845 if (Section->UseCodeAlign()) 3846 getStreamer().emitCodeAlignment(2, 0); 3847 else 3848 getStreamer().emitValueToAlignment(2, 0, 1, 0); 3849 return false; 3850 } 3851 3852 /// ParseDirectiveCode 3853 /// ::= .code16 | .code32 | .code64 3854 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) { 3855 MCAsmParser &Parser = getParser(); 3856 Code16GCC = false; 3857 if (IDVal == ".code16") { 3858 Parser.Lex(); 3859 if (!is16BitMode()) { 3860 SwitchMode(X86::Mode16Bit); 3861 getParser().getStreamer().emitAssemblerFlag(MCAF_Code16); 3862 } 3863 } else if (IDVal == ".code16gcc") { 3864 // .code16gcc parses as if in 32-bit mode, but emits code in 16-bit mode. 3865 Parser.Lex(); 3866 Code16GCC = true; 3867 if (!is16BitMode()) { 3868 SwitchMode(X86::Mode16Bit); 3869 getParser().getStreamer().emitAssemblerFlag(MCAF_Code16); 3870 } 3871 } else if (IDVal == ".code32") { 3872 Parser.Lex(); 3873 if (!is32BitMode()) { 3874 SwitchMode(X86::Mode32Bit); 3875 getParser().getStreamer().emitAssemblerFlag(MCAF_Code32); 3876 } 3877 } else if (IDVal == ".code64") { 3878 Parser.Lex(); 3879 if (!is64BitMode()) { 3880 SwitchMode(X86::Mode64Bit); 3881 getParser().getStreamer().emitAssemblerFlag(MCAF_Code64); 3882 } 3883 } else { 3884 Error(L, "unknown directive " + IDVal); 3885 return false; 3886 } 3887 3888 return false; 3889 } 3890 3891 // .cv_fpo_proc foo 3892 bool X86AsmParser::parseDirectiveFPOProc(SMLoc L) { 3893 MCAsmParser &Parser = getParser(); 3894 StringRef ProcName; 3895 int64_t ParamsSize; 3896 if (Parser.parseIdentifier(ProcName)) 3897 return Parser.TokError("expected symbol name"); 3898 if (Parser.parseIntToken(ParamsSize, "expected parameter byte count")) 3899 return true; 3900 if (!isUIntN(32, ParamsSize)) 3901 return Parser.TokError("parameters size out of range"); 3902 if (Parser.parseEOL("unexpected tokens")) 3903 return addErrorSuffix(" in '.cv_fpo_proc' directive"); 3904 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName); 3905 return getTargetStreamer().emitFPOProc(ProcSym, ParamsSize, L); 3906 } 3907 3908 // .cv_fpo_setframe ebp 3909 bool X86AsmParser::parseDirectiveFPOSetFrame(SMLoc L) { 3910 MCAsmParser &Parser = getParser(); 3911 unsigned Reg; 3912 SMLoc DummyLoc; 3913 if (ParseRegister(Reg, DummyLoc, DummyLoc) || 3914 Parser.parseEOL("unexpected tokens")) 3915 return addErrorSuffix(" in '.cv_fpo_setframe' directive"); 3916 return getTargetStreamer().emitFPOSetFrame(Reg, L); 3917 } 3918 3919 // .cv_fpo_pushreg ebx 3920 bool X86AsmParser::parseDirectiveFPOPushReg(SMLoc L) { 3921 MCAsmParser &Parser = getParser(); 3922 unsigned Reg; 3923 SMLoc DummyLoc; 3924 if (ParseRegister(Reg, DummyLoc, DummyLoc) || 3925 Parser.parseEOL("unexpected tokens")) 3926 return addErrorSuffix(" in '.cv_fpo_pushreg' directive"); 3927 return getTargetStreamer().emitFPOPushReg(Reg, L); 3928 } 3929 3930 // .cv_fpo_stackalloc 20 3931 bool X86AsmParser::parseDirectiveFPOStackAlloc(SMLoc L) { 3932 MCAsmParser &Parser = getParser(); 3933 int64_t Offset; 3934 if (Parser.parseIntToken(Offset, "expected offset") || 3935 Parser.parseEOL("unexpected tokens")) 3936 return addErrorSuffix(" in '.cv_fpo_stackalloc' directive"); 3937 return getTargetStreamer().emitFPOStackAlloc(Offset, L); 3938 } 3939 3940 // .cv_fpo_stackalign 8 3941 bool X86AsmParser::parseDirectiveFPOStackAlign(SMLoc L) { 3942 MCAsmParser &Parser = getParser(); 3943 int64_t Offset; 3944 if (Parser.parseIntToken(Offset, "expected offset") || 3945 Parser.parseEOL("unexpected tokens")) 3946 return addErrorSuffix(" in '.cv_fpo_stackalign' directive"); 3947 return getTargetStreamer().emitFPOStackAlign(Offset, L); 3948 } 3949 3950 // .cv_fpo_endprologue 3951 bool X86AsmParser::parseDirectiveFPOEndPrologue(SMLoc L) { 3952 MCAsmParser &Parser = getParser(); 3953 if (Parser.parseEOL("unexpected tokens")) 3954 return addErrorSuffix(" in '.cv_fpo_endprologue' directive"); 3955 return getTargetStreamer().emitFPOEndPrologue(L); 3956 } 3957 3958 // .cv_fpo_endproc 3959 bool X86AsmParser::parseDirectiveFPOEndProc(SMLoc L) { 3960 MCAsmParser &Parser = getParser(); 3961 if (Parser.parseEOL("unexpected tokens")) 3962 return addErrorSuffix(" in '.cv_fpo_endproc' directive"); 3963 return getTargetStreamer().emitFPOEndProc(L); 3964 } 3965 3966 bool X86AsmParser::parseSEHRegisterNumber(unsigned RegClassID, 3967 unsigned &RegNo) { 3968 SMLoc startLoc = getLexer().getLoc(); 3969 const MCRegisterInfo *MRI = getContext().getRegisterInfo(); 3970 3971 // Try parsing the argument as a register first. 3972 if (getLexer().getTok().isNot(AsmToken::Integer)) { 3973 SMLoc endLoc; 3974 if (ParseRegister(RegNo, startLoc, endLoc)) 3975 return true; 3976 3977 if (!X86MCRegisterClasses[RegClassID].contains(RegNo)) { 3978 return Error(startLoc, 3979 "register is not supported for use with this directive"); 3980 } 3981 } else { 3982 // Otherwise, an integer number matching the encoding of the desired 3983 // register may appear. 3984 int64_t EncodedReg; 3985 if (getParser().parseAbsoluteExpression(EncodedReg)) 3986 return true; 3987 3988 // The SEH register number is the same as the encoding register number. Map 3989 // from the encoding back to the LLVM register number. 3990 RegNo = 0; 3991 for (MCPhysReg Reg : X86MCRegisterClasses[RegClassID]) { 3992 if (MRI->getEncodingValue(Reg) == EncodedReg) { 3993 RegNo = Reg; 3994 break; 3995 } 3996 } 3997 if (RegNo == 0) { 3998 return Error(startLoc, 3999 "incorrect register number for use with this directive"); 4000 } 4001 } 4002 4003 return false; 4004 } 4005 4006 bool X86AsmParser::parseDirectiveSEHPushReg(SMLoc Loc) { 4007 unsigned Reg = 0; 4008 if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg)) 4009 return true; 4010 4011 if (getLexer().isNot(AsmToken::EndOfStatement)) 4012 return TokError("unexpected token in directive"); 4013 4014 getParser().Lex(); 4015 getStreamer().EmitWinCFIPushReg(Reg, Loc); 4016 return false; 4017 } 4018 4019 bool X86AsmParser::parseDirectiveSEHSetFrame(SMLoc Loc) { 4020 unsigned Reg = 0; 4021 int64_t Off; 4022 if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg)) 4023 return true; 4024 if (getLexer().isNot(AsmToken::Comma)) 4025 return TokError("you must specify a stack pointer offset"); 4026 4027 getParser().Lex(); 4028 if (getParser().parseAbsoluteExpression(Off)) 4029 return true; 4030 4031 if (getLexer().isNot(AsmToken::EndOfStatement)) 4032 return TokError("unexpected token in directive"); 4033 4034 getParser().Lex(); 4035 getStreamer().EmitWinCFISetFrame(Reg, Off, Loc); 4036 return false; 4037 } 4038 4039 bool X86AsmParser::parseDirectiveSEHSaveReg(SMLoc Loc) { 4040 unsigned Reg = 0; 4041 int64_t Off; 4042 if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg)) 4043 return true; 4044 if (getLexer().isNot(AsmToken::Comma)) 4045 return TokError("you must specify an offset on the stack"); 4046 4047 getParser().Lex(); 4048 if (getParser().parseAbsoluteExpression(Off)) 4049 return true; 4050 4051 if (getLexer().isNot(AsmToken::EndOfStatement)) 4052 return TokError("unexpected token in directive"); 4053 4054 getParser().Lex(); 4055 getStreamer().EmitWinCFISaveReg(Reg, Off, Loc); 4056 return false; 4057 } 4058 4059 bool X86AsmParser::parseDirectiveSEHSaveXMM(SMLoc Loc) { 4060 unsigned Reg = 0; 4061 int64_t Off; 4062 if (parseSEHRegisterNumber(X86::VR128XRegClassID, Reg)) 4063 return true; 4064 if (getLexer().isNot(AsmToken::Comma)) 4065 return TokError("you must specify an offset on the stack"); 4066 4067 getParser().Lex(); 4068 if (getParser().parseAbsoluteExpression(Off)) 4069 return true; 4070 4071 if (getLexer().isNot(AsmToken::EndOfStatement)) 4072 return TokError("unexpected token in directive"); 4073 4074 getParser().Lex(); 4075 getStreamer().EmitWinCFISaveXMM(Reg, Off, Loc); 4076 return false; 4077 } 4078 4079 bool X86AsmParser::parseDirectiveSEHPushFrame(SMLoc Loc) { 4080 bool Code = false; 4081 StringRef CodeID; 4082 if (getLexer().is(AsmToken::At)) { 4083 SMLoc startLoc = getLexer().getLoc(); 4084 getParser().Lex(); 4085 if (!getParser().parseIdentifier(CodeID)) { 4086 if (CodeID != "code") 4087 return Error(startLoc, "expected @code"); 4088 Code = true; 4089 } 4090 } 4091 4092 if (getLexer().isNot(AsmToken::EndOfStatement)) 4093 return TokError("unexpected token in directive"); 4094 4095 getParser().Lex(); 4096 getStreamer().EmitWinCFIPushFrame(Code, Loc); 4097 return false; 4098 } 4099 4100 // Force static initialization. 4101 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeX86AsmParser() { 4102 RegisterMCAsmParser<X86AsmParser> X(getTheX86_32Target()); 4103 RegisterMCAsmParser<X86AsmParser> Y(getTheX86_64Target()); 4104 } 4105 4106 #define GET_REGISTER_MATCHER 4107 #define GET_MATCHER_IMPLEMENTATION 4108 #define GET_SUBTARGET_FEATURE_NAME 4109 #include "X86GenAsmMatcher.inc" 4110