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