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