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