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