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