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),
1405 CLOpts(X86_MC::getCLOpts(Parser.getContext().getTargetOptions())),
1406 InstInfo(nullptr), Code16GCC(false) {
1407
1408 Parser.addAliasForDirective(".word", ".2byte");
1409
1410 // Initialize the set of available features.
1411 setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
1412 }
1413
1414 bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
1415 ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
1416 SMLoc &EndLoc) override;
1417
1418 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
1419
1420 bool parseInstruction(ParseInstructionInfo &Info, StringRef Name,
1421 SMLoc NameLoc, OperandVector &Operands) override;
1422
1423 bool ParseDirective(AsmToken DirectiveID) override;
1424};
1425} // end anonymous namespace
1426
1427#define GET_REGISTER_MATCHER
1428#define GET_SUBTARGET_FEATURE_NAME
1429#include "X86GenAsmMatcher.inc"
1430
1432 MCRegister IndexReg, unsigned Scale,
1433 bool Is64BitMode,
1434 StringRef &ErrMsg) {
1435 // If we have both a base register and an index register make sure they are
1436 // both 64-bit or 32-bit registers.
1437 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1438
1439 if (BaseReg &&
1440 !(BaseReg == X86::RIP || BaseReg == X86::EIP ||
1441 getX86MCRegisterClass(X86::GR16RegClassID).contains(BaseReg) ||
1442 getX86MCRegisterClass(X86::GR32RegClassID).contains(BaseReg) ||
1443 getX86MCRegisterClass(X86::GR64RegClassID).contains(BaseReg))) {
1444 ErrMsg = "invalid base+index expression";
1445 return true;
1446 }
1447
1448 if (IndexReg &&
1449 !(IndexReg == X86::EIZ || IndexReg == X86::RIZ ||
1450 getX86MCRegisterClass(X86::GR16RegClassID).contains(IndexReg) ||
1451 getX86MCRegisterClass(X86::GR32RegClassID).contains(IndexReg) ||
1452 getX86MCRegisterClass(X86::GR64RegClassID).contains(IndexReg) ||
1453 getX86MCRegisterClass(X86::VR128XRegClassID).contains(IndexReg) ||
1454 getX86MCRegisterClass(X86::VR256XRegClassID).contains(IndexReg) ||
1455 getX86MCRegisterClass(X86::VR512RegClassID).contains(IndexReg))) {
1456 ErrMsg = "invalid base+index expression";
1457 return true;
1458 }
1459
1460 if (((BaseReg == X86::RIP || BaseReg == X86::EIP) && IndexReg) ||
1461 IndexReg == X86::EIP || IndexReg == X86::RIP || IndexReg == X86::ESP ||
1462 IndexReg == X86::RSP) {
1463 ErrMsg = "invalid base+index expression";
1464 return true;
1465 }
1466
1467 // Check for use of invalid 16-bit registers. Only BX/BP/SI/DI are allowed,
1468 // and then only in non-64-bit modes.
1469 if (getX86MCRegisterClass(X86::GR16RegClassID).contains(BaseReg) &&
1470 (Is64BitMode || (BaseReg != X86::BX && BaseReg != X86::BP &&
1471 BaseReg != X86::SI && BaseReg != X86::DI))) {
1472 ErrMsg = "invalid 16-bit base register";
1473 return true;
1474 }
1475
1476 if (!BaseReg &&
1477 getX86MCRegisterClass(X86::GR16RegClassID).contains(IndexReg)) {
1478 ErrMsg = "16-bit memory operand may not include only index register";
1479 return true;
1480 }
1481
1482 if (BaseReg && IndexReg) {
1483 if (getX86MCRegisterClass(X86::GR64RegClassID).contains(BaseReg) &&
1484 (getX86MCRegisterClass(X86::GR16RegClassID).contains(IndexReg) ||
1485 getX86MCRegisterClass(X86::GR32RegClassID).contains(IndexReg) ||
1486 IndexReg == X86::EIZ)) {
1487 ErrMsg = "base register is 64-bit, but index register is not";
1488 return true;
1489 }
1490 if (getX86MCRegisterClass(X86::GR32RegClassID).contains(BaseReg) &&
1491 (getX86MCRegisterClass(X86::GR16RegClassID).contains(IndexReg) ||
1492 getX86MCRegisterClass(X86::GR64RegClassID).contains(IndexReg) ||
1493 IndexReg == X86::RIZ)) {
1494 ErrMsg = "base register is 32-bit, but index register is not";
1495 return true;
1496 }
1497 if (getX86MCRegisterClass(X86::GR16RegClassID).contains(BaseReg)) {
1498 if (getX86MCRegisterClass(X86::GR32RegClassID).contains(IndexReg) ||
1499 getX86MCRegisterClass(X86::GR64RegClassID).contains(IndexReg)) {
1500 ErrMsg = "base register is 16-bit, but index register is not";
1501 return true;
1502 }
1503 if ((BaseReg != X86::BX && BaseReg != X86::BP) ||
1504 (IndexReg != X86::SI && IndexReg != X86::DI)) {
1505 ErrMsg = "invalid 16-bit base/index register combination";
1506 return true;
1507 }
1508 }
1509 }
1510
1511 // RIP/EIP-relative addressing is only supported in 64-bit mode.
1512 if (!Is64BitMode && (BaseReg == X86::RIP || BaseReg == X86::EIP)) {
1513 ErrMsg = "IP-relative addressing requires 64-bit mode";
1514 return true;
1515 }
1516
1517 return checkScale(Scale, ErrMsg);
1518}
1519
1520bool X86AsmParser::MatchRegisterByName(MCRegister &RegNo, StringRef RegName,
1521 SMLoc StartLoc, SMLoc EndLoc) {
1522 // If we encounter a %, ignore it. This code handles registers with and
1523 // without the prefix, unprefixed registers can occur in cfi directives.
1524 RegName.consume_front("%");
1525
1526 RegNo = MatchRegisterName(RegName);
1527
1528 // If the match failed, try the register name as lowercase.
1529 if (!RegNo)
1530 RegNo = MatchRegisterName(RegName.lower());
1531
1532 // The "flags" and "mxcsr" registers cannot be referenced directly.
1533 // Treat it as an identifier instead.
1534 if (isParsingMSInlineAsm() && isParsingIntelSyntax() &&
1535 (RegNo == X86::EFLAGS || RegNo == X86::MXCSR))
1536 RegNo = MCRegister();
1537
1538 if (!is64BitMode()) {
1539 // FIXME: This should be done using Requires<Not64BitMode> and
1540 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1541 // checked.
1542 if (RegNo == X86::RIZ || RegNo == X86::RIP ||
1543 getX86MCRegisterClass(X86::GR64RegClassID).contains(RegNo) ||
1546 return Error(StartLoc,
1547 "register %" + RegName + " is only available in 64-bit mode",
1548 SMRange(StartLoc, EndLoc));
1549 }
1550 }
1551
1552 if (X86II::isApxExtendedReg(RegNo))
1553 UseApxExtendedReg = true;
1554
1555 // If this is "db[0-15]", match it as an alias
1556 // for dr[0-15].
1557 if (!RegNo && RegName.starts_with("db")) {
1558 if (RegName.size() == 3) {
1559 switch (RegName[2]) {
1560 case '0':
1561 RegNo = X86::DR0;
1562 break;
1563 case '1':
1564 RegNo = X86::DR1;
1565 break;
1566 case '2':
1567 RegNo = X86::DR2;
1568 break;
1569 case '3':
1570 RegNo = X86::DR3;
1571 break;
1572 case '4':
1573 RegNo = X86::DR4;
1574 break;
1575 case '5':
1576 RegNo = X86::DR5;
1577 break;
1578 case '6':
1579 RegNo = X86::DR6;
1580 break;
1581 case '7':
1582 RegNo = X86::DR7;
1583 break;
1584 case '8':
1585 RegNo = X86::DR8;
1586 break;
1587 case '9':
1588 RegNo = X86::DR9;
1589 break;
1590 }
1591 } else if (RegName.size() == 4 && RegName[2] == '1') {
1592 switch (RegName[3]) {
1593 case '0':
1594 RegNo = X86::DR10;
1595 break;
1596 case '1':
1597 RegNo = X86::DR11;
1598 break;
1599 case '2':
1600 RegNo = X86::DR12;
1601 break;
1602 case '3':
1603 RegNo = X86::DR13;
1604 break;
1605 case '4':
1606 RegNo = X86::DR14;
1607 break;
1608 case '5':
1609 RegNo = X86::DR15;
1610 break;
1611 }
1612 }
1613 }
1614
1615 if (!RegNo) {
1616 if (isParsingIntelSyntax())
1617 return true;
1618 return Error(StartLoc, "invalid register name", SMRange(StartLoc, EndLoc));
1619 }
1620 return false;
1621}
1622
1623bool X86AsmParser::ParseRegister(MCRegister &RegNo, SMLoc &StartLoc,
1624 SMLoc &EndLoc, bool RestoreOnFailure) {
1625 MCAsmParser &Parser = getParser();
1626 AsmLexer &Lexer = getLexer();
1627 RegNo = MCRegister();
1628
1630 auto OnFailure = [RestoreOnFailure, &Lexer, &Tokens]() {
1631 if (RestoreOnFailure) {
1632 while (!Tokens.empty()) {
1633 Lexer.UnLex(Tokens.pop_back_val());
1634 }
1635 }
1636 };
1637
1638 const AsmToken &PercentTok = Parser.getTok();
1639 StartLoc = PercentTok.getLoc();
1640
1641 // If we encounter a %, ignore it. This code handles registers with and
1642 // without the prefix, unprefixed registers can occur in cfi directives.
1643 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent)) {
1644 Tokens.push_back(PercentTok);
1645 Parser.Lex(); // Eat percent token.
1646 }
1647
1648 const AsmToken &Tok = Parser.getTok();
1649 EndLoc = Tok.getEndLoc();
1650
1651 if (Tok.isNot(AsmToken::Identifier)) {
1652 OnFailure();
1653 if (isParsingIntelSyntax()) return true;
1654 return Error(StartLoc, "invalid register name",
1655 SMRange(StartLoc, EndLoc));
1656 }
1657
1658 if (MatchRegisterByName(RegNo, Tok.getString(), StartLoc, EndLoc)) {
1659 OnFailure();
1660 return true;
1661 }
1662
1663 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1664 if (RegNo == X86::ST0) {
1665 Tokens.push_back(Tok);
1666 Parser.Lex(); // Eat 'st'
1667
1668 // Check to see if we have '(4)' after %st.
1669 if (Lexer.isNot(AsmToken::LParen))
1670 return false;
1671 // Lex the paren.
1672 Tokens.push_back(Parser.getTok());
1673 Parser.Lex();
1674
1675 const AsmToken &IntTok = Parser.getTok();
1676 if (IntTok.isNot(AsmToken::Integer)) {
1677 OnFailure();
1678 return Error(IntTok.getLoc(), "expected stack index");
1679 }
1680 switch (IntTok.getIntVal()) {
1681 case 0: RegNo = X86::ST0; break;
1682 case 1: RegNo = X86::ST1; break;
1683 case 2: RegNo = X86::ST2; break;
1684 case 3: RegNo = X86::ST3; break;
1685 case 4: RegNo = X86::ST4; break;
1686 case 5: RegNo = X86::ST5; break;
1687 case 6: RegNo = X86::ST6; break;
1688 case 7: RegNo = X86::ST7; break;
1689 default:
1690 OnFailure();
1691 return Error(IntTok.getLoc(), "invalid stack index");
1692 }
1693
1694 // Lex IntTok
1695 Tokens.push_back(IntTok);
1696 Parser.Lex();
1697 if (Lexer.isNot(AsmToken::RParen)) {
1698 OnFailure();
1699 return Error(Parser.getTok().getLoc(), "expected ')'");
1700 }
1701
1702 EndLoc = Parser.getTok().getEndLoc();
1703 Parser.Lex(); // Eat ')'
1704 return false;
1705 }
1706
1707 EndLoc = Parser.getTok().getEndLoc();
1708
1709 if (!RegNo) {
1710 OnFailure();
1711 if (isParsingIntelSyntax()) return true;
1712 return Error(StartLoc, "invalid register name",
1713 SMRange(StartLoc, EndLoc));
1714 }
1715
1716 Parser.Lex(); // Eat identifier token.
1717 return false;
1718}
1719
1720bool X86AsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
1721 SMLoc &EndLoc) {
1722 return ParseRegister(Reg, StartLoc, EndLoc, /*RestoreOnFailure=*/false);
1723}
1724
1725ParseStatus X86AsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
1726 SMLoc &EndLoc) {
1727 bool Result = ParseRegister(Reg, StartLoc, EndLoc, /*RestoreOnFailure=*/true);
1728 bool PendingErrors = getParser().hasPendingError();
1729 getParser().clearPendingErrors();
1730 if (PendingErrors)
1731 return ParseStatus::Failure;
1732 if (Result)
1733 return ParseStatus::NoMatch;
1734 return ParseStatus::Success;
1735}
1736
1737std::unique_ptr<X86Operand> X86AsmParser::DefaultMemSIOperand(SMLoc Loc) {
1738 bool Parse32 = is32BitMode() || Code16GCC;
1739 MCRegister Basereg =
1740 is64BitMode() ? X86::RSI : (Parse32 ? X86::ESI : X86::SI);
1741 const MCExpr *Disp = MCConstantExpr::create(0, getContext());
1742 return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp,
1743 /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1,
1744 Loc, Loc, 0);
1745}
1746
1747std::unique_ptr<X86Operand> X86AsmParser::DefaultMemDIOperand(SMLoc Loc) {
1748 bool Parse32 = is32BitMode() || Code16GCC;
1749 MCRegister Basereg =
1750 is64BitMode() ? X86::RDI : (Parse32 ? X86::EDI : X86::DI);
1751 const MCExpr *Disp = MCConstantExpr::create(0, getContext());
1752 return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp,
1753 /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1,
1754 Loc, Loc, 0);
1755}
1756
1757bool X86AsmParser::IsSIReg(MCRegister Reg) {
1758 switch (Reg.id()) {
1759 default: llvm_unreachable("Only (R|E)SI and (R|E)DI are expected!");
1760 case X86::RSI:
1761 case X86::ESI:
1762 case X86::SI:
1763 return true;
1764 case X86::RDI:
1765 case X86::EDI:
1766 case X86::DI:
1767 return false;
1768 }
1769}
1770
1771MCRegister X86AsmParser::GetSIDIForRegClass(unsigned RegClassID, bool IsSIReg) {
1772 switch (RegClassID) {
1773 default: llvm_unreachable("Unexpected register class");
1774 case X86::GR64RegClassID:
1775 return IsSIReg ? X86::RSI : X86::RDI;
1776 case X86::GR32RegClassID:
1777 return IsSIReg ? X86::ESI : X86::EDI;
1778 case X86::GR16RegClassID:
1779 return IsSIReg ? X86::SI : X86::DI;
1780 }
1781}
1782
1783void X86AsmParser::AddDefaultSrcDestOperands(
1784 OperandVector& Operands, std::unique_ptr<llvm::MCParsedAsmOperand> &&Src,
1785 std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst) {
1786 if (isParsingIntelSyntax()) {
1787 Operands.push_back(std::move(Dst));
1788 Operands.push_back(std::move(Src));
1789 }
1790 else {
1791 Operands.push_back(std::move(Src));
1792 Operands.push_back(std::move(Dst));
1793 }
1794}
1795
1796bool X86AsmParser::VerifyAndAdjustOperands(OperandVector &OrigOperands,
1797 OperandVector &FinalOperands) {
1798
1799 if (OrigOperands.size() > 1) {
1800 // Check if sizes match, OrigOperands also contains the instruction name
1801 assert(OrigOperands.size() == FinalOperands.size() + 1 &&
1802 "Operand size mismatch");
1803
1805 // Verify types match
1806 int RegClassID = -1;
1807 for (unsigned int i = 0; i < FinalOperands.size(); ++i) {
1808 X86Operand &OrigOp = static_cast<X86Operand &>(*OrigOperands[i + 1]);
1809 X86Operand &FinalOp = static_cast<X86Operand &>(*FinalOperands[i]);
1810
1811 if (FinalOp.isReg() &&
1812 (!OrigOp.isReg() || FinalOp.getReg() != OrigOp.getReg()))
1813 // Return false and let a normal complaint about bogus operands happen
1814 return false;
1815
1816 if (FinalOp.isMem()) {
1817
1818 if (!OrigOp.isMem())
1819 // Return false and let a normal complaint about bogus operands happen
1820 return false;
1821
1822 MCRegister OrigReg = OrigOp.Mem.BaseReg;
1823 MCRegister FinalReg = FinalOp.Mem.BaseReg;
1824
1825 // If we've already encounterd a register class, make sure all register
1826 // bases are of the same register class
1827 if (RegClassID != -1 &&
1828 !getX86MCRegisterClass(RegClassID).contains(OrigReg)) {
1829 return Error(OrigOp.getStartLoc(),
1830 "mismatching source and destination index registers");
1831 }
1832
1833 if (getX86MCRegisterClass(X86::GR64RegClassID).contains(OrigReg))
1834 RegClassID = X86::GR64RegClassID;
1835 else if (getX86MCRegisterClass(X86::GR32RegClassID).contains(OrigReg))
1836 RegClassID = X86::GR32RegClassID;
1837 else if (getX86MCRegisterClass(X86::GR16RegClassID).contains(OrigReg))
1838 RegClassID = X86::GR16RegClassID;
1839 else
1840 // Unexpected register class type
1841 // Return false and let a normal complaint about bogus operands happen
1842 return false;
1843
1844 bool IsSI = IsSIReg(FinalReg);
1845 FinalReg = GetSIDIForRegClass(RegClassID, IsSI);
1846
1847 if (FinalReg != OrigReg) {
1848 std::string RegName = IsSI ? "ES:(R|E)SI" : "ES:(R|E)DI";
1849 Warnings.push_back(std::make_pair(
1850 OrigOp.getStartLoc(),
1851 "memory operand is only for determining the size, " + RegName +
1852 " will be used for the location"));
1853 }
1854
1855 FinalOp.Mem.Size = OrigOp.Mem.Size;
1856 FinalOp.Mem.SegReg = OrigOp.Mem.SegReg;
1857 FinalOp.Mem.BaseReg = FinalReg;
1858 }
1859 }
1860
1861 // Produce warnings only if all the operands passed the adjustment - prevent
1862 // legal cases like "movsd (%rax), %xmm0" mistakenly produce warnings
1863 for (auto &WarningMsg : Warnings) {
1864 Warning(WarningMsg.first, WarningMsg.second);
1865 }
1866
1867 // Remove old operands
1868 for (unsigned int i = 0; i < FinalOperands.size(); ++i)
1869 OrigOperands.pop_back();
1870 }
1871 // OrigOperands.append(FinalOperands.begin(), FinalOperands.end());
1872 for (auto &Op : FinalOperands)
1873 OrigOperands.push_back(std::move(Op));
1874
1875 return false;
1876}
1877
1878bool X86AsmParser::parseOperand(OperandVector &Operands, StringRef Name) {
1879 if (isParsingIntelSyntax())
1880 return parseIntelOperand(Operands, Name);
1881
1882 return parseATTOperand(Operands);
1883}
1884
1885bool X86AsmParser::CreateMemForMSInlineAsm(
1886 MCRegister SegReg, const MCExpr *Disp, MCRegister BaseReg,
1887 MCRegister IndexReg, unsigned Scale, bool NonAbsMem, SMLoc Start, SMLoc End,
1888 unsigned Size, StringRef Identifier, const InlineAsmIdentifierInfo &Info,
1890 // If we found a decl other than a VarDecl, then assume it is a FuncDecl or
1891 // some other label reference.
1893 // Create an absolute memory reference in order to match against
1894 // instructions taking a PC relative operand.
1895 Operands.push_back(X86Operand::CreateMem(getPointerWidth(), Disp, Start,
1896 End, Size, Identifier,
1897 Info.Label.Decl));
1898 return false;
1899 }
1900 // We either have a direct symbol reference, or an offset from a symbol. The
1901 // parser always puts the symbol on the LHS, so look there for size
1902 // calculation purposes.
1903 unsigned FrontendSize = 0;
1904 void *Decl = nullptr;
1905 bool IsGlobalLV = false;
1907 // Size is in terms of bits in this context.
1908 FrontendSize = Info.Var.Type * 8;
1909 Decl = Info.Var.Decl;
1910 IsGlobalLV = Info.Var.IsGlobalLV;
1911 }
1912 // It is widely common for MS InlineAsm to use a global variable and one/two
1913 // registers in a mmory expression, and though unaccessible via rip/eip.
1914 if (IsGlobalLV) {
1915 if (BaseReg || IndexReg) {
1916 Operands.push_back(X86Operand::CreateMem(getPointerWidth(), Disp, Start,
1917 End, Size, Identifier, Decl, 0,
1918 BaseReg && IndexReg));
1919 return false;
1920 }
1921 if (NonAbsMem)
1922 BaseReg = 1; // Make isAbsMem() false
1923 }
1925 getPointerWidth(), SegReg, Disp, BaseReg, IndexReg, Scale, Start, End,
1926 Size,
1927 /*DefaultBaseReg=*/X86::RIP, Identifier, Decl, FrontendSize));
1928 return false;
1929}
1930
1931// Some binary bitwise operators have a named synonymous
1932// Query a candidate string for being such a named operator
1933// and if so - invoke the appropriate handler
1934bool X86AsmParser::ParseIntelNamedOperator(StringRef Name,
1935 IntelExprStateMachine &SM,
1936 bool &ParseError, SMLoc &End) {
1937 // A named operator should be either lower or upper case, but not a mix...
1938 // except in MASM, which uses full case-insensitivity.
1939 if (Name != Name.lower() && Name != Name.upper() &&
1940 !getParser().isParsingMasm())
1941 return false;
1942 // Operators like 'offset' and 'imagerel' consume their operand tokens
1943 // internally; other named operators need a trailing consumeToken().
1944 bool AlreadyConsumed = false;
1945 if (Name.equals_insensitive("not")) {
1946 SM.onNot();
1947 } else if (Name.equals_insensitive("or")) {
1948 SM.onOr();
1949 } else if (Name.equals_insensitive("shl")) {
1950 SM.onLShift();
1951 } else if (Name.equals_insensitive("shr")) {
1952 SM.onRShift();
1953 } else if (Name.equals_insensitive("xor")) {
1954 SM.onXor();
1955 } else if (Name.equals_insensitive("and")) {
1956 SM.onAnd();
1957 } else if (Name.equals_insensitive("mod")) {
1958 SM.onMod();
1959 } else if (Name.equals_insensitive("offset")) {
1960 const MCExpr *Val = nullptr;
1961 StringRef ID;
1962 InlineAsmIdentifierInfo Info;
1963 ParseError = ParseIntelOffsetOperator(Val, ID, Info, End);
1964 if (ParseError)
1965 return true;
1966 StringRef ErrMsg;
1967 ParseError = SM.onOffset(Val, ID, Info, isParsingMSInlineAsm(), ErrMsg);
1968 if (ParseError)
1969 return Error(SMLoc::getFromPointer(Name.data()), ErrMsg);
1970 AlreadyConsumed = true;
1971 } else if (Name.equals_insensitive("imagerel")) {
1972 const MCExpr *Val;
1973 StringRef ID;
1974 InlineAsmIdentifierInfo Info;
1975 ParseError = ParseIntelImagerelOperator(Val, ID, Info, End);
1976 if (ParseError)
1977 return true;
1978 StringRef ErrMsg;
1979 ParseError = SM.onImagerel(Val, ID, ErrMsg);
1980 if (ParseError)
1981 return Error(SMLoc::getFromPointer(Name.data()), ErrMsg);
1982 AlreadyConsumed = true;
1983 } else {
1984 return false;
1985 }
1986 if (!AlreadyConsumed)
1987 End = consumeToken();
1988 return true;
1989}
1990bool X86AsmParser::ParseMasmNamedOperator(StringRef Name,
1991 IntelExprStateMachine &SM,
1992 bool &ParseError, SMLoc &End) {
1993 if (Name.equals_insensitive("eq")) {
1994 SM.onEq();
1995 } else if (Name.equals_insensitive("ne")) {
1996 SM.onNE();
1997 } else if (Name.equals_insensitive("lt")) {
1998 SM.onLT();
1999 } else if (Name.equals_insensitive("le")) {
2000 SM.onLE();
2001 } else if (Name.equals_insensitive("gt")) {
2002 SM.onGT();
2003 } else if (Name.equals_insensitive("ge")) {
2004 SM.onGE();
2005 } else {
2006 return false;
2007 }
2008 End = consumeToken();
2009 return true;
2010}
2011
2012// Check if current intel expression append after an operand.
2013// Like: [Operand][Intel Expression]
2014void X86AsmParser::tryParseOperandIdx(AsmToken::TokenKind PrevTK,
2015 IntelExprStateMachine &SM) {
2016 if (PrevTK != AsmToken::RBrac)
2017 return;
2018
2019 SM.setAppendAfterOperand();
2020}
2021
2022bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
2023 MCAsmParser &Parser = getParser();
2024 StringRef ErrMsg;
2025
2027
2028 if (getContext().getObjectFileInfo()->isPositionIndependent())
2029 SM.setPIC();
2030
2031 bool Done = false;
2032 while (!Done) {
2033 // Get a fresh reference on each loop iteration in case the previous
2034 // iteration moved the token storage during UnLex().
2035 const AsmToken &Tok = Parser.getTok();
2036
2037 bool UpdateLocLex = true;
2038 AsmToken::TokenKind TK = getLexer().getKind();
2039
2040 switch (TK) {
2041 default:
2042 if ((Done = SM.isValidEndState()))
2043 break;
2044 return Error(Tok.getLoc(), "unknown token in expression");
2045 case AsmToken::Error:
2046 return Error(getLexer().getErrLoc(), getLexer().getErr());
2047 break;
2048 case AsmToken::Real:
2049 // DotOperator: [ebx].0
2050 UpdateLocLex = false;
2051 if (ParseIntelDotOperator(SM, End))
2052 return true;
2053 break;
2054 case AsmToken::Dot:
2055 if (!Parser.isParsingMasm()) {
2056 if ((Done = SM.isValidEndState()))
2057 break;
2058 return Error(Tok.getLoc(), "unknown token in expression");
2059 }
2060 // MASM allows spaces around the dot operator (e.g., "var . x")
2061 Lex();
2062 UpdateLocLex = false;
2063 if (ParseIntelDotOperator(SM, End))
2064 return true;
2065 break;
2066 case AsmToken::Dollar:
2067 if (!Parser.isParsingMasm()) {
2068 if ((Done = SM.isValidEndState()))
2069 break;
2070 return Error(Tok.getLoc(), "unknown token in expression");
2071 }
2072 [[fallthrough]];
2073 case AsmToken::String: {
2074 if (Parser.isParsingMasm()) {
2075 // MASM parsers handle strings in expressions as constants.
2076 SMLoc ValueLoc = Tok.getLoc();
2077 int64_t Res;
2078 const MCExpr *Val;
2079 if (Parser.parsePrimaryExpr(Val, End, nullptr))
2080 return true;
2081 UpdateLocLex = false;
2082 if (!Val->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
2083 return Error(ValueLoc, "expected absolute value");
2084 if (SM.onInteger(Res, ErrMsg))
2085 return Error(SM.getErrorLoc(ValueLoc), ErrMsg);
2086 break;
2087 }
2088 [[fallthrough]];
2089 }
2090 case AsmToken::At:
2091 case AsmToken::Identifier: {
2092 SMLoc IdentLoc = Tok.getLoc();
2093 StringRef Identifier = Tok.getString();
2094 UpdateLocLex = false;
2095 if (Parser.isParsingMasm()) {
2096 size_t DotOffset = Identifier.find_first_of('.');
2097 if (DotOffset != StringRef::npos) {
2098 consumeToken();
2099 StringRef LHS = Identifier.slice(0, DotOffset);
2100 StringRef Dot = Identifier.substr(DotOffset, 1);
2101 StringRef RHS = Identifier.substr(DotOffset + 1);
2102 if (!RHS.empty()) {
2103 getLexer().UnLex(AsmToken(AsmToken::Identifier, RHS));
2104 }
2105 getLexer().UnLex(AsmToken(AsmToken::Dot, Dot));
2106 if (!LHS.empty()) {
2107 getLexer().UnLex(AsmToken(AsmToken::Identifier, LHS));
2108 }
2109 break;
2110 }
2111 }
2112 // (MASM only) <TYPE> PTR operator
2113 if (Parser.isParsingMasm()) {
2114 const AsmToken &NextTok = getLexer().peekTok();
2115 if (NextTok.is(AsmToken::Identifier) &&
2116 NextTok.getIdentifier().equals_insensitive("ptr")) {
2117 AsmTypeInfo Info;
2118 if (Parser.lookUpType(Identifier, Info))
2119 return Error(Tok.getLoc(), "unknown type");
2120 SM.onCast(Info);
2121 // Eat type and PTR.
2122 consumeToken();
2123 End = consumeToken();
2124 break;
2125 }
2126 }
2127 // Register, or (MASM only) <register>.<field>
2128 MCRegister Reg;
2129 if (Tok.is(AsmToken::Identifier)) {
2130 if (!ParseRegister(Reg, IdentLoc, End, /*RestoreOnFailure=*/true)) {
2131 if (SM.onRegister(Reg, ErrMsg))
2132 return Error(SM.getErrorLoc(IdentLoc), ErrMsg);
2133 break;
2134 }
2135 if (Parser.isParsingMasm()) {
2136 const std::pair<StringRef, StringRef> IDField =
2137 Tok.getString().split('.');
2138 const StringRef ID = IDField.first, Field = IDField.second;
2139 SMLoc IDEndLoc = SMLoc::getFromPointer(ID.data() + ID.size());
2140 if (!Field.empty() &&
2141 !MatchRegisterByName(Reg, ID, IdentLoc, IDEndLoc)) {
2142 if (SM.onRegister(Reg, ErrMsg))
2143 return Error(SM.getErrorLoc(IdentLoc), ErrMsg);
2144
2145 AsmFieldInfo Info;
2146 SMLoc FieldStartLoc = SMLoc::getFromPointer(Field.data());
2147 if (Parser.lookUpField(Field, Info))
2148 return Error(FieldStartLoc, "unknown offset");
2149 else if (SM.onPlus(ErrMsg))
2150 return Error(getTok().getLoc(), ErrMsg);
2151 else if (SM.onInteger(Info.Offset, ErrMsg))
2152 return Error(SM.getErrorLoc(IdentLoc), ErrMsg);
2153 SM.setTypeInfo(Info.Type);
2154
2155 End = consumeToken();
2156 break;
2157 }
2158 }
2159 }
2160 // Operator synonymous ("not", "or" etc.)
2161 bool ParseError = false;
2162 if (ParseIntelNamedOperator(Identifier, SM, ParseError, End)) {
2163 if (ParseError)
2164 return true;
2165 break;
2166 }
2167 if (Parser.isParsingMasm() &&
2168 ParseMasmNamedOperator(Identifier, SM, ParseError, End)) {
2169 if (ParseError)
2170 return true;
2171 break;
2172 }
2173 // Symbol reference, when parsing assembly content
2174 InlineAsmIdentifierInfo Info;
2175 AsmFieldInfo FieldInfo;
2176 const MCExpr *Val;
2177 if (isParsingMSInlineAsm() || Parser.isParsingMasm()) {
2178 // MS Dot Operator expression
2179 if (Identifier.contains('.') &&
2180 (PrevTK == AsmToken::RBrac || PrevTK == AsmToken::RParen)) {
2181 if (ParseIntelDotOperator(SM, End))
2182 return true;
2183 break;
2184 }
2185 }
2186 if (isParsingMSInlineAsm()) {
2187 // MS InlineAsm operators (TYPE/LENGTH/SIZE)
2188 if (unsigned OpKind = IdentifyIntelInlineAsmOperator(Identifier)) {
2189 if (int64_t Val = ParseIntelInlineAsmOperator(OpKind)) {
2190 if (SM.onInteger(Val, ErrMsg))
2191 return Error(SM.getErrorLoc(IdentLoc), ErrMsg);
2192 } else {
2193 return true;
2194 }
2195 break;
2196 }
2197 // MS InlineAsm identifier
2198 // Call parseIdentifier() to combine @ with the identifier behind it.
2199 if (TK == AsmToken::At && Parser.parseIdentifier(Identifier))
2200 return Error(IdentLoc, "expected identifier");
2201 if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info, false, End))
2202 return true;
2203 else if (SM.onIdentifierExpr(Val, Identifier, Info, FieldInfo.Type,
2204 true, ErrMsg))
2205 return Error(SM.getErrorLoc(IdentLoc), ErrMsg);
2206 break;
2207 }
2208 if (Parser.isParsingMasm()) {
2209 if (unsigned OpKind = IdentifyMasmOperator(Identifier)) {
2210 int64_t Val;
2211 if (ParseMasmOperator(OpKind, Val))
2212 return true;
2213 if (SM.onInteger(Val, ErrMsg))
2214 return Error(SM.getErrorLoc(IdentLoc), ErrMsg);
2215 break;
2216 }
2217 if (!getParser().lookUpType(Identifier, FieldInfo.Type)) {
2218 // Field offset immediate; <TYPE>.<field specification>
2219 Lex(); // eat type
2220 bool EndDot = parseOptionalToken(AsmToken::Dot);
2221 while (EndDot || (getTok().is(AsmToken::Identifier) &&
2222 getTok().getString().starts_with("."))) {
2223 getParser().parseIdentifier(Identifier);
2224 if (!EndDot)
2225 Identifier.consume_front(".");
2226 EndDot = Identifier.consume_back(".");
2227 if (getParser().lookUpField(FieldInfo.Type.Name, Identifier,
2228 FieldInfo)) {
2229 SMLoc IDEnd =
2231 return Error(IdentLoc, "Unable to lookup field reference!",
2232 SMRange(IdentLoc, IDEnd));
2233 }
2234 if (!EndDot)
2235 EndDot = parseOptionalToken(AsmToken::Dot);
2236 }
2237 if (SM.onInteger(FieldInfo.Offset, ErrMsg))
2238 return Error(SM.getErrorLoc(IdentLoc), ErrMsg);
2239 break;
2240 }
2241 }
2242 if (getParser().parsePrimaryExpr(Val, End, &FieldInfo.Type)) {
2243 return Error(Tok.getLoc(), "Unexpected identifier!");
2244 } else if (SM.onIdentifierExpr(Val, Identifier, Info, FieldInfo.Type,
2245 false, ErrMsg)) {
2246 return Error(SM.getErrorLoc(IdentLoc), ErrMsg);
2247 }
2248 break;
2249 }
2250 case AsmToken::Integer: {
2251 // Look for 'b' or 'f' following an Integer as a directional label
2252 SMLoc Loc = getTok().getLoc();
2253 int64_t IntVal = getTok().getIntVal();
2254 End = consumeToken();
2255 UpdateLocLex = false;
2256 if (getLexer().getKind() == AsmToken::Identifier) {
2257 StringRef IDVal = getTok().getString();
2258 if (IDVal == "f" || IDVal == "b") {
2259 MCSymbol *Sym =
2260 getContext().getDirectionalLocalSymbol(IntVal, IDVal == "b");
2261 auto Variant = X86::S_None;
2262 const MCExpr *Val =
2263 MCSymbolRefExpr::create(Sym, Variant, getContext());
2264 if (IDVal == "b" && Sym->isUndefined())
2265 return Error(Loc, "invalid reference to undefined symbol");
2266 StringRef Identifier = Sym->getName();
2267 InlineAsmIdentifierInfo Info;
2268 AsmTypeInfo Type;
2269 if (SM.onIdentifierExpr(Val, Identifier, Info, Type,
2270 isParsingMSInlineAsm(), ErrMsg))
2271 return Error(SM.getErrorLoc(Loc), ErrMsg);
2272 End = consumeToken();
2273 } else {
2274 if (SM.onInteger(IntVal, ErrMsg))
2275 return Error(SM.getErrorLoc(Loc), ErrMsg);
2276 }
2277 } else {
2278 if (SM.onInteger(IntVal, ErrMsg))
2279 return Error(SM.getErrorLoc(Loc), ErrMsg);
2280 }
2281 break;
2282 }
2283 case AsmToken::Plus:
2284 if (SM.onPlus(ErrMsg))
2285 return Error(getTok().getLoc(), ErrMsg);
2286 break;
2287 case AsmToken::Minus:
2288 if (SM.onMinus(getTok().getLoc(), ErrMsg))
2289 return Error(SM.getErrorLoc(getTok().getLoc()), ErrMsg);
2290 break;
2291 case AsmToken::Tilde: SM.onNot(); break;
2292 case AsmToken::Star: SM.onStar(); break;
2293 case AsmToken::Slash: SM.onDivide(); break;
2294 case AsmToken::Percent: SM.onMod(); break;
2295 case AsmToken::Pipe: SM.onOr(); break;
2296 case AsmToken::Caret: SM.onXor(); break;
2297 case AsmToken::Amp: SM.onAnd(); break;
2298 case AsmToken::LessLess:
2299 SM.onLShift(); break;
2301 SM.onRShift(); break;
2302 case AsmToken::LBrac:
2303 if (SM.onLBrac())
2304 return Error(Tok.getLoc(), "unexpected bracket encountered");
2305 tryParseOperandIdx(PrevTK, SM);
2306 break;
2307 case AsmToken::RBrac:
2308 if (SM.onRBrac(ErrMsg)) {
2309 return Error(SM.getErrorLoc(Tok.getLoc()), ErrMsg);
2310 }
2311 break;
2312 case AsmToken::LParen:
2313 SM.onLParen(Tok.getLoc());
2314 break;
2315 case AsmToken::RParen:
2316 if (SM.onRParen(ErrMsg)) {
2317 return Error(SM.getErrorLoc(Tok.getLoc()), ErrMsg);
2318 }
2319 break;
2320 }
2321 if (SM.hadError())
2322 return Error(Tok.getLoc(), "unknown token in expression");
2323
2324 if (!Done && UpdateLocLex)
2325 End = consumeToken();
2326
2327 PrevTK = TK;
2328 }
2329 if (SM.hasUnmatchedParen())
2330 return Error(SM.getLParenLoc(), "unmatched parenthesis");
2331 return false;
2332}
2333
2334void X86AsmParser::RewriteIntelExpression(IntelExprStateMachine &SM,
2335 SMLoc Start, SMLoc End) {
2336 SMLoc Loc = Start;
2337 unsigned ExprLen = End.getPointer() - Start.getPointer();
2338 // Skip everything before a symbol displacement (if we have one)
2339 if (SM.getSym() && !SM.isOffsetOperator()) {
2340 StringRef SymName = SM.getSymName();
2341 if (unsigned Len = SymName.data() - Start.getPointer())
2342 InstInfo->AsmRewrites->emplace_back(AOK_Skip, Start, Len);
2343 Loc = SMLoc::getFromPointer(SymName.data() + SymName.size());
2344 ExprLen = End.getPointer() - (SymName.data() + SymName.size());
2345 // If we have only a symbol than there's no need for complex rewrite,
2346 // simply skip everything after it
2347 if (!(SM.getBaseReg() || SM.getIndexReg() || SM.getImm())) {
2348 if (ExprLen)
2349 InstInfo->AsmRewrites->emplace_back(AOK_Skip, Loc, ExprLen);
2350 return;
2351 }
2352 }
2353 // Build an Intel Expression rewrite
2354 StringRef BaseRegStr;
2355 StringRef IndexRegStr;
2356 StringRef OffsetNameStr;
2357 if (SM.getBaseReg())
2358 BaseRegStr = X86IntelInstPrinter::getRegisterName(SM.getBaseReg());
2359 if (SM.getIndexReg())
2360 IndexRegStr = X86IntelInstPrinter::getRegisterName(SM.getIndexReg());
2361 if (SM.isOffsetOperator())
2362 OffsetNameStr = SM.getSymName();
2363 // Emit it
2364 IntelExpr Expr(BaseRegStr, IndexRegStr, SM.getScale(), OffsetNameStr,
2365 SM.getImm(), SM.isMemExpr());
2366 InstInfo->AsmRewrites->emplace_back(Loc, ExprLen, Expr);
2367}
2368
2369// Inline assembly may use variable names with namespace alias qualifiers.
2370bool X86AsmParser::ParseIntelInlineAsmIdentifier(
2371 const MCExpr *&Val, StringRef &Identifier, InlineAsmIdentifierInfo &Info,
2372 bool IsUnevaluatedOperand, SMLoc &End, bool IsParsingOffsetOperator) {
2373 MCAsmParser &Parser = getParser();
2374 assert(isParsingMSInlineAsm() && "Expected to be parsing inline assembly.");
2375 Val = nullptr;
2376
2377 StringRef LineBuf(Identifier.data());
2378 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
2379
2380 const AsmToken &Tok = Parser.getTok();
2381 SMLoc Loc = Tok.getLoc();
2382
2383 // Advance the token stream until the end of the current token is
2384 // after the end of what the frontend claimed.
2385 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
2386 do {
2387 End = Tok.getEndLoc();
2388 getLexer().Lex();
2389 } while (End.getPointer() < EndPtr);
2390 Identifier = LineBuf;
2391
2392 // The frontend should end parsing on an assembler token boundary, unless it
2393 // failed parsing.
2394 assert((End.getPointer() == EndPtr ||
2396 "frontend claimed part of a token?");
2397
2398 // If the identifier lookup was unsuccessful, assume that we are dealing with
2399 // a label.
2401 StringRef InternalName =
2402 SemaCallback->LookupInlineAsmLabel(Identifier, getSourceManager(),
2403 Loc, false);
2404 assert(InternalName.size() && "We should have an internal name here.");
2405 // Push a rewrite for replacing the identifier name with the internal name,
2406 // unless we are parsing the operand of an offset operator
2407 if (!IsParsingOffsetOperator)
2408 InstInfo->AsmRewrites->emplace_back(AOK_Label, Loc, Identifier.size(),
2409 InternalName);
2410 else
2411 Identifier = InternalName;
2412 } else if (Info.isKind(InlineAsmIdentifierInfo::IK_EnumVal))
2413 return false;
2414 // Create the symbol reference.
2415 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
2416 auto Variant = X86::S_None;
2417 Val = MCSymbolRefExpr::create(Sym, Variant, getParser().getContext());
2418 return false;
2419}
2420
2421//ParseRoundingModeOp - Parse AVX-512 rounding mode operand
2422bool X86AsmParser::ParseRoundingModeOp(SMLoc Start, OperandVector &Operands) {
2423 MCAsmParser &Parser = getParser();
2424 const AsmToken &Tok = Parser.getTok();
2425 // Eat "{" and mark the current place.
2426 const SMLoc consumedToken = consumeToken();
2427 if (Tok.isNot(AsmToken::Identifier))
2428 return Error(Tok.getLoc(), "Expected an identifier after {");
2429 if (Tok.getIdentifier().starts_with("r")) {
2430 int rndMode = StringSwitch<int>(Tok.getIdentifier())
2431 .Case("rn", X86::STATIC_ROUNDING::TO_NEAREST_INT)
2432 .Case("rd", X86::STATIC_ROUNDING::TO_NEG_INF)
2433 .Case("ru", X86::STATIC_ROUNDING::TO_POS_INF)
2434 .Case("rz", X86::STATIC_ROUNDING::TO_ZERO)
2435 .Default(-1);
2436 if (-1 == rndMode)
2437 return Error(Tok.getLoc(), "Invalid rounding mode.");
2438 Parser.Lex(); // Eat "r*" of r*-sae
2439 if (!getLexer().is(AsmToken::Minus))
2440 return Error(Tok.getLoc(), "Expected - at this point");
2441 Parser.Lex(); // Eat "-"
2442 Parser.Lex(); // Eat the sae
2443 if (!getLexer().is(AsmToken::RCurly))
2444 return Error(Tok.getLoc(), "Expected } at this point");
2445 SMLoc End = Tok.getEndLoc();
2446 Parser.Lex(); // Eat "}"
2447 const MCExpr *RndModeOp =
2448 MCConstantExpr::create(rndMode, Parser.getContext());
2449 Operands.push_back(X86Operand::CreateImm(RndModeOp, Start, End));
2450 return false;
2451 }
2452 if (Tok.getIdentifier() == "sae") {
2453 Parser.Lex(); // Eat the sae
2454 if (!getLexer().is(AsmToken::RCurly))
2455 return Error(Tok.getLoc(), "Expected } at this point");
2456 Parser.Lex(); // Eat "}"
2457 Operands.push_back(X86Operand::CreateToken("{sae}", consumedToken));
2458 return false;
2459 }
2460 return Error(Tok.getLoc(), "unknown token in expression");
2461}
2462
2463/// Parse condtional flags for CCMP/CTEST, e.g {dfv=of,sf,zf,cf} right after
2464/// mnemonic.
2465bool X86AsmParser::parseCFlagsOp(OperandVector &Operands) {
2466 MCAsmParser &Parser = getParser();
2467 AsmToken Tok = Parser.getTok();
2468 const SMLoc Start = Tok.getLoc();
2469 if (!Tok.is(AsmToken::LCurly))
2470 return Error(Tok.getLoc(), "Expected { at this point");
2471 Parser.Lex(); // Eat "{"
2472 Tok = Parser.getTok();
2473 if (Tok.getIdentifier().lower() != "dfv")
2474 return Error(Tok.getLoc(), "Expected dfv at this point");
2475 Parser.Lex(); // Eat "dfv"
2476 Tok = Parser.getTok();
2477 if (!Tok.is(AsmToken::Equal))
2478 return Error(Tok.getLoc(), "Expected = at this point");
2479 Parser.Lex(); // Eat "="
2480
2481 Tok = Parser.getTok();
2482 SMLoc End;
2483 if (Tok.is(AsmToken::RCurly)) {
2484 End = Tok.getEndLoc();
2486 MCConstantExpr::create(0, Parser.getContext()), Start, End));
2487 Parser.Lex(); // Eat "}"
2488 return false;
2489 }
2490 unsigned CFlags = 0;
2491 for (unsigned I = 0; I < 4; ++I) {
2492 Tok = Parser.getTok();
2493 unsigned CFlag = StringSwitch<unsigned>(Tok.getIdentifier().lower())
2494 .Case("of", 0x8)
2495 .Case("sf", 0x4)
2496 .Case("zf", 0x2)
2497 .Case("cf", 0x1)
2498 .Default(~0U);
2499 if (CFlag == ~0U)
2500 return Error(Tok.getLoc(), "Invalid conditional flags");
2501
2502 if (CFlags & CFlag)
2503 return Error(Tok.getLoc(), "Duplicated conditional flag");
2504 CFlags |= CFlag;
2505
2506 Parser.Lex(); // Eat one conditional flag
2507 Tok = Parser.getTok();
2508 if (Tok.is(AsmToken::RCurly)) {
2509 End = Tok.getEndLoc();
2511 MCConstantExpr::create(CFlags, Parser.getContext()), Start, End));
2512 Parser.Lex(); // Eat "}"
2513 return false;
2514 } else if (I == 3) {
2515 return Error(Tok.getLoc(), "Expected } at this point");
2516 } else if (Tok.isNot(AsmToken::Comma)) {
2517 return Error(Tok.getLoc(), "Expected } or , at this point");
2518 }
2519 Parser.Lex(); // Eat ","
2520 }
2521 llvm_unreachable("Unexpected control flow");
2522}
2523
2524/// Parse the '.' operator.
2525bool X86AsmParser::ParseIntelDotOperator(IntelExprStateMachine &SM,
2526 SMLoc &End) {
2527 const AsmToken &Tok = getTok();
2528 AsmFieldInfo Info;
2529
2530 // Drop the optional '.'.
2531 StringRef DotDispStr = Tok.getString();
2532 DotDispStr.consume_front(".");
2533 bool TrailingDot = false;
2534
2535 // .Imm gets lexed as a real.
2536 if (Tok.is(AsmToken::Real)) {
2537 APInt DotDisp;
2538 if (DotDispStr.getAsInteger(10, DotDisp))
2539 return Error(Tok.getLoc(), "Unexpected offset");
2540 Info.Offset = DotDisp.getZExtValue();
2541 } else if ((isParsingMSInlineAsm() || getParser().isParsingMasm()) &&
2542 Tok.is(AsmToken::Identifier)) {
2543 TrailingDot = DotDispStr.consume_back(".");
2544 const std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
2545 const StringRef Base = BaseMember.first, Member = BaseMember.second;
2546 if (getParser().lookUpField(SM.getType(), DotDispStr, Info) &&
2547 getParser().lookUpField(SM.getSymName(), DotDispStr, Info) &&
2548 getParser().lookUpField(DotDispStr, Info) &&
2549 (!SemaCallback ||
2550 SemaCallback->LookupInlineAsmField(Base, Member, Info.Offset)))
2551 return Error(Tok.getLoc(), "Unable to lookup field reference!");
2552 } else {
2553 return Error(Tok.getLoc(), "Unexpected token type!");
2554 }
2555
2556 // Eat the DotExpression and update End
2557 End = SMLoc::getFromPointer(DotDispStr.data());
2558 const char *DotExprEndLoc = DotDispStr.data() + DotDispStr.size();
2559 while (Tok.getLoc().getPointer() < DotExprEndLoc)
2560 Lex();
2561 if (TrailingDot)
2562 getLexer().UnLex(AsmToken(AsmToken::Dot, "."));
2563 SM.addImm(Info.Offset);
2564 SM.setTypeInfo(Info.Type);
2565 return false;
2566}
2567
2568/// Parse the 'offset' operator.
2569/// This operator is used to specify the location of a given operand
2570bool X86AsmParser::ParseIntelOffsetOperator(const MCExpr *&Val, StringRef &ID,
2571 InlineAsmIdentifierInfo &Info,
2572 SMLoc &End) {
2573 // Eat offset, mark start of identifier.
2574 SMLoc Start = Lex().getLoc();
2575 ID = getTok().getString();
2576 if (!isParsingMSInlineAsm()) {
2577 if ((getTok().isNot(AsmToken::Identifier) &&
2578 getTok().isNot(AsmToken::String)) ||
2579 getParser().parsePrimaryExpr(Val, End, nullptr))
2580 return Error(Start, "unexpected token!");
2581 } else if (ParseIntelInlineAsmIdentifier(Val, ID, Info, false, End, true)) {
2582 return Error(Start, "unable to lookup expression");
2583 } else if (Info.isKind(InlineAsmIdentifierInfo::IK_EnumVal)) {
2584 return Error(Start, "offset operator cannot yet handle constants");
2585 }
2586 return false;
2587}
2588
2589/// Parse the 'imagerel' operator.
2590/// This operator is used to specify an image-relative reference to a symbol.
2591bool X86AsmParser::ParseIntelImagerelOperator(const MCExpr *&Val, StringRef &ID,
2592 InlineAsmIdentifierInfo &Info,
2593 SMLoc &End) {
2594 // Eat imagerel, mark start of identifier.
2595 SMLoc Start = Lex().getLoc();
2596 ID = getTok().getString();
2597 if (!isParsingMSInlineAsm()) {
2598 if ((getTok().isNot(AsmToken::Identifier) &&
2599 getTok().isNot(AsmToken::String)) ||
2600 getParser().parsePrimaryExpr(Val, End, nullptr))
2601 return Error(Start, "unexpected token!");
2602 } else if (ParseIntelInlineAsmIdentifier(Val, ID, Info, false, End, true)) {
2603 return Error(Start, "unable to lookup expression");
2604 } else if (Info.isKind(InlineAsmIdentifierInfo::IK_EnumVal)) {
2605 return Error(Start, "imagerel operator cannot yet handle constants");
2606 }
2607
2608 const MCExpr *ModifiedVal =
2609 getParser().applySpecifier(Val, MCSymbolRefExpr::VK_COFF_IMGREL32);
2610 if (!ModifiedVal)
2611 return Error(Start, "cannot apply 'imagerel' to this expression");
2612 Val = ModifiedVal;
2613 return false;
2614}
2615
2616// Query a candidate string for being an Intel assembly operator
2617// Report back its kind, or IOK_INVALID if does not evaluated as a known one
2618unsigned X86AsmParser::IdentifyIntelInlineAsmOperator(StringRef Name) {
2619 return StringSwitch<unsigned>(Name)
2620 .Cases({"TYPE", "type"}, IOK_TYPE)
2621 .Cases({"SIZE", "size"}, IOK_SIZE)
2622 .Cases({"LENGTH", "length"}, IOK_LENGTH)
2623 .Default(IOK_INVALID);
2624}
2625
2626/// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
2627/// returns the number of elements in an array. It returns the value 1 for
2628/// non-array variables. The SIZE operator returns the size of a C or C++
2629/// variable. A variable's size is the product of its LENGTH and TYPE. The
2630/// TYPE operator returns the size of a C or C++ type or variable. If the
2631/// variable is an array, TYPE returns the size of a single element.
2632unsigned X86AsmParser::ParseIntelInlineAsmOperator(unsigned OpKind) {
2633 MCAsmParser &Parser = getParser();
2634 const AsmToken &Tok = Parser.getTok();
2635 Parser.Lex(); // Eat operator.
2636
2637 const MCExpr *Val = nullptr;
2638 InlineAsmIdentifierInfo Info;
2639 SMLoc Start = Tok.getLoc(), End;
2640 StringRef Identifier = Tok.getString();
2641 if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info,
2642 /*IsUnevaluatedOperand=*/true, End))
2643 return 0;
2644
2646 Error(Start, "unable to lookup expression");
2647 return 0;
2648 }
2649
2650 unsigned CVal = 0;
2651 switch(OpKind) {
2652 default: llvm_unreachable("Unexpected operand kind!");
2653 case IOK_LENGTH: CVal = Info.Var.Length; break;
2654 case IOK_SIZE: CVal = Info.Var.Size; break;
2655 case IOK_TYPE: CVal = Info.Var.Type; break;
2656 }
2657
2658 return CVal;
2659}
2660
2661// Query a candidate string for being an Intel assembly operator
2662// Report back its kind, or IOK_INVALID if does not evaluated as a known one
2663unsigned X86AsmParser::IdentifyMasmOperator(StringRef Name) {
2664 return StringSwitch<unsigned>(Name.lower())
2665 .Case("type", MOK_TYPE)
2666 .Cases({"size", "sizeof"}, MOK_SIZEOF)
2667 .Cases({"length", "lengthof"}, MOK_LENGTHOF)
2668 .Default(MOK_INVALID);
2669}
2670
2671/// Parse the 'LENGTHOF', 'SIZEOF', and 'TYPE' operators. The LENGTHOF operator
2672/// returns the number of elements in an array. It returns the value 1 for
2673/// non-array variables. The SIZEOF operator returns the size of a type or
2674/// variable in bytes. A variable's size is the product of its LENGTH and TYPE.
2675/// The TYPE operator returns the size of a variable. If the variable is an
2676/// array, TYPE returns the size of a single element.
2677bool X86AsmParser::ParseMasmOperator(unsigned OpKind, int64_t &Val) {
2678 MCAsmParser &Parser = getParser();
2679 SMLoc OpLoc = Parser.getTok().getLoc();
2680 Parser.Lex(); // Eat operator.
2681
2682 Val = 0;
2683 if (OpKind == MOK_SIZEOF || OpKind == MOK_TYPE) {
2684 // Check for SIZEOF(<type>) and TYPE(<type>).
2685 bool InParens = Parser.getTok().is(AsmToken::LParen);
2686 const AsmToken &IDTok = InParens ? getLexer().peekTok() : Parser.getTok();
2687 AsmTypeInfo Type;
2688 if (IDTok.is(AsmToken::Identifier) &&
2689 !Parser.lookUpType(IDTok.getIdentifier(), Type)) {
2690 Val = Type.Size;
2691
2692 // Eat tokens.
2693 if (InParens)
2694 parseToken(AsmToken::LParen);
2695 parseToken(AsmToken::Identifier);
2696 if (InParens)
2697 parseToken(AsmToken::RParen);
2698 }
2699 }
2700
2701 if (!Val) {
2702 IntelExprStateMachine SM;
2703 SMLoc End, Start = Parser.getTok().getLoc();
2704 if (ParseIntelExpression(SM, End))
2705 return true;
2706
2707 switch (OpKind) {
2708 default:
2709 llvm_unreachable("Unexpected operand kind!");
2710 case MOK_SIZEOF:
2711 Val = SM.getSize();
2712 break;
2713 case MOK_LENGTHOF:
2714 Val = SM.getLength();
2715 break;
2716 case MOK_TYPE:
2717 Val = SM.getElementSize();
2718 break;
2719 }
2720
2721 if (!Val)
2722 return Error(OpLoc, "expression has unknown type", SMRange(Start, End));
2723 }
2724
2725 return false;
2726}
2727
2728bool X86AsmParser::ParseIntelMemoryOperandSize(unsigned &Size,
2729 StringRef *SizeStr) {
2730 Size = StringSwitch<unsigned>(getTok().getString())
2731 .Cases({"BYTE", "byte"}, 8)
2732 .Cases({"WORD", "word"}, 16)
2733 .Cases({"DWORD", "dword"}, 32)
2734 .Cases({"FLOAT", "float"}, 32)
2735 .Cases({"LONG", "long"}, 32)
2736 .Cases({"FWORD", "fword"}, 48)
2737 .Cases({"DOUBLE", "double"}, 64)
2738 .Cases({"QWORD", "qword"}, 64)
2739 .Cases({"MMWORD", "mmword"}, 64)
2740 .Cases({"XWORD", "xword"}, 80)
2741 .Cases({"TBYTE", "tbyte"}, 80)
2742 .Cases({"XMMWORD", "xmmword"}, 128)
2743 .Cases({"YMMWORD", "ymmword"}, 256)
2744 .Cases({"ZMMWORD", "zmmword"}, 512)
2745 .Default(0);
2746 if (Size) {
2747 if (SizeStr)
2748 *SizeStr = getTok().getString();
2749 const AsmToken &Tok = Lex(); // Eat operand size (e.g., byte, word).
2750 if (!(Tok.getString() == "PTR" || Tok.getString() == "ptr"))
2751 return Error(Tok.getLoc(), "Expected 'PTR' or 'ptr' token!");
2752 Lex(); // Eat ptr.
2753 }
2754 return false;
2755}
2756
2758 if (getX86MCRegisterClass(X86::GR8RegClassID).contains(RegNo))
2759 return 8;
2760 if (getX86MCRegisterClass(X86::GR16RegClassID).contains(RegNo))
2761 return 16;
2762 if (getX86MCRegisterClass(X86::GR32RegClassID).contains(RegNo))
2763 return 32;
2764 if (getX86MCRegisterClass(X86::GR64RegClassID).contains(RegNo))
2765 return 64;
2766 // Unknown register size
2767 return 0;
2768}
2769
2770bool X86AsmParser::parseIntelOperand(OperandVector &Operands, StringRef Name) {
2771 MCAsmParser &Parser = getParser();
2772 const AsmToken &Tok = Parser.getTok();
2773 SMLoc Start, End;
2774
2775 // Parse optional Size directive.
2776 unsigned Size;
2777 StringRef SizeStr;
2778 if (ParseIntelMemoryOperandSize(Size, &SizeStr))
2779 return true;
2780 bool PtrInOperand = bool(Size);
2781
2782 Start = Tok.getLoc();
2783
2784 // Rounding mode operand.
2785 if (getLexer().is(AsmToken::LCurly))
2786 return ParseRoundingModeOp(Start, Operands);
2787
2788 // Register operand.
2789 MCRegister RegNo;
2790 if (Tok.is(AsmToken::Identifier) && !parseRegister(RegNo, Start, End)) {
2791 if (RegNo == X86::RIP)
2792 return Error(Start, "rip can only be used as a base register");
2793 // A Register followed by ':' is considered a segment override
2794 if (Tok.isNot(AsmToken::Colon)) {
2795 if (PtrInOperand) {
2796 if (!Parser.isParsingMasm())
2797 return Error(Start, "expected memory operand after 'ptr', "
2798 "found register operand instead");
2799
2800 // If we are parsing MASM, we are allowed to cast registers to their own
2801 // sizes, but not to other types.
2802 uint16_t RegSize =
2803 RegSizeInBits(*getContext().getRegisterInfo(), RegNo);
2804 if (RegSize == 0)
2805 return Error(
2806 Start,
2807 "cannot cast register '" +
2808 StringRef(getContext().getRegisterInfo()->getName(RegNo)) +
2809 "'; its size is not easily defined.");
2810 if (RegSize != Size)
2811 return Error(
2812 Start,
2813 std::to_string(RegSize) + "-bit register '" +
2814 StringRef(getContext().getRegisterInfo()->getName(RegNo)) +
2815 "' cannot be used as a " + std::to_string(Size) + "-bit " +
2816 SizeStr.upper());
2817 }
2818 Operands.push_back(X86Operand::CreateReg(RegNo, Start, End));
2819 return false;
2820 }
2821 // An alleged segment override. check if we have a valid segment register
2822 if (!getX86MCRegisterClass(X86::SEGMENT_REGRegClassID).contains(RegNo))
2823 return Error(Start, "invalid segment register");
2824 // Eat ':' and update Start location
2825 Start = Lex().getLoc();
2826 }
2827
2828 // Immediates and Memory
2829 IntelExprStateMachine SM;
2830 if (ParseIntelExpression(SM, End))
2831 return true;
2832
2833 if (isParsingMSInlineAsm())
2834 RewriteIntelExpression(SM, Start, Tok.getLoc());
2835
2836 int64_t Imm = SM.getImm();
2837 const MCExpr *Disp = SM.getSym();
2838 const MCExpr *ImmDisp = MCConstantExpr::create(Imm, getContext());
2839 if (Disp && Imm)
2840 Disp = MCBinaryExpr::createAdd(Disp, ImmDisp, getContext());
2841 if (!Disp)
2842 Disp = ImmDisp;
2843
2844 // RegNo != 0 specifies a valid segment register,
2845 // and we are parsing a segment override
2846 if (!SM.isMemExpr() && !RegNo) {
2847 if (isParsingMSInlineAsm() && SM.isOffsetOperator()) {
2848 const InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
2850 // Disp includes the address of a variable; make sure this is recorded
2851 // for later handling.
2852 Operands.push_back(X86Operand::CreateImm(Disp, Start, End,
2853 SM.getSymName(), Info.Var.Decl,
2854 Info.Var.IsGlobalLV));
2855 return false;
2856 }
2857 }
2858
2859 Operands.push_back(X86Operand::CreateImm(Disp, Start, End));
2860 return false;
2861 }
2862
2863 StringRef ErrMsg;
2864 MCRegister BaseReg = SM.getBaseReg();
2865 MCRegister IndexReg = SM.getIndexReg();
2866 if (IndexReg && BaseReg == X86::RIP)
2867 BaseReg = MCRegister();
2868 unsigned Scale = SM.getScale();
2869 if (!PtrInOperand)
2870 Size = SM.getElementSize() << 3;
2871
2872 if (Scale == 0 && BaseReg != X86::ESP && BaseReg != X86::RSP &&
2873 (IndexReg == X86::ESP || IndexReg == X86::RSP))
2874 std::swap(BaseReg, IndexReg);
2875
2876 // If BaseReg is a vector register and IndexReg is not, swap them unless
2877 // Scale was specified in which case it would be an error.
2878 if (Scale == 0 &&
2879 !(getX86MCRegisterClass(X86::VR128XRegClassID).contains(IndexReg) ||
2880 getX86MCRegisterClass(X86::VR256XRegClassID).contains(IndexReg) ||
2881 getX86MCRegisterClass(X86::VR512RegClassID).contains(IndexReg)) &&
2882 (getX86MCRegisterClass(X86::VR128XRegClassID).contains(BaseReg) ||
2883 getX86MCRegisterClass(X86::VR256XRegClassID).contains(BaseReg) ||
2884 getX86MCRegisterClass(X86::VR512RegClassID).contains(BaseReg)))
2885 std::swap(BaseReg, IndexReg);
2886
2887 if (Scale != 0 &&
2888 getX86MCRegisterClass(X86::GR16RegClassID).contains(IndexReg))
2889 return Error(Start, "16-bit addresses cannot have a scale");
2890
2891 // If there was no explicit scale specified, change it to 1.
2892 if (Scale == 0)
2893 Scale = 1;
2894
2895 // If this is a 16-bit addressing mode with the base and index in the wrong
2896 // order, swap them so CheckBaseRegAndIndexRegAndScale doesn't fail. It is
2897 // shared with att syntax where order matters.
2898 if ((BaseReg == X86::SI || BaseReg == X86::DI) &&
2899 (IndexReg == X86::BX || IndexReg == X86::BP))
2900 std::swap(BaseReg, IndexReg);
2901
2902 if ((BaseReg || IndexReg) &&
2903 CheckBaseRegAndIndexRegAndScale(BaseReg, IndexReg, Scale, is64BitMode(),
2904 ErrMsg))
2905 return Error(Start, ErrMsg);
2906 bool IsUnconditionalBranch =
2907 Name.equals_insensitive("jmp") || Name.equals_insensitive("call");
2908 if (isParsingMSInlineAsm())
2909 return CreateMemForMSInlineAsm(RegNo, Disp, BaseReg, IndexReg, Scale,
2910 IsUnconditionalBranch && is64BitMode(),
2911 Start, End, Size, SM.getSymName(),
2912 SM.getIdentifierInfo(), Operands);
2913
2914 // When parsing x64 MS-style assembly, all non-absolute references to a named
2915 // variable default to RIP-relative.
2916 MCRegister DefaultBaseReg;
2917 bool MaybeDirectBranchDest = true;
2918
2919 if (Parser.isParsingMasm()) {
2920 if (is64BitMode() &&
2921 ((PtrInOperand && !IndexReg) || SM.getElementSize() > 0)) {
2922 DefaultBaseReg = X86::RIP;
2923 }
2924 if (IsUnconditionalBranch) {
2925 if (PtrInOperand) {
2926 MaybeDirectBranchDest = false;
2927 if (is64BitMode())
2928 DefaultBaseReg = X86::RIP;
2929 } else if (!BaseReg && !IndexReg && Disp &&
2930 Disp->getKind() == MCExpr::SymbolRef) {
2931 if (is64BitMode()) {
2932 if (SM.getSize() == 8) {
2933 MaybeDirectBranchDest = false;
2934 DefaultBaseReg = X86::RIP;
2935 }
2936 } else {
2937 if (SM.getSize() == 4 || SM.getSize() == 2)
2938 MaybeDirectBranchDest = false;
2939 }
2940 }
2941 }
2942 } else if (IsUnconditionalBranch) {
2943 // Treat `call [offset fn_ref]` (or `jmp`) syntax as an error.
2944 if (!PtrInOperand && SM.isOffsetOperator())
2945 return Error(
2946 Start, "`OFFSET` operator cannot be used in an unconditional branch");
2947 if (PtrInOperand || SM.isBracketUsed())
2948 MaybeDirectBranchDest = false;
2949 }
2950
2951 if (CheckDispOverflow(BaseReg, IndexReg, Disp, Start))
2952 return true;
2953
2954 if ((BaseReg || IndexReg || RegNo || DefaultBaseReg))
2956 getPointerWidth(), RegNo, Disp, BaseReg, IndexReg, Scale, Start, End,
2957 Size, DefaultBaseReg, /*SymName=*/StringRef(), /*OpDecl=*/nullptr,
2958 /*FrontendSize=*/0, /*UseUpRegs=*/false, MaybeDirectBranchDest));
2959 else
2961 getPointerWidth(), Disp, Start, End, Size, /*SymName=*/StringRef(),
2962 /*OpDecl=*/nullptr, /*FrontendSize=*/0, /*UseUpRegs=*/false,
2963 MaybeDirectBranchDest));
2964 return false;
2965}
2966
2967bool X86AsmParser::parseATTOperand(OperandVector &Operands) {
2968 MCAsmParser &Parser = getParser();
2969 switch (getLexer().getKind()) {
2970 case AsmToken::Dollar: {
2971 // $42 or $ID -> immediate.
2972 SMLoc Start = Parser.getTok().getLoc(), End;
2973 Parser.Lex();
2974 const MCExpr *Val;
2975 // This is an immediate, so we should not parse a register. Do a precheck
2976 // for '%' to supercede intra-register parse errors.
2977 SMLoc L = Parser.getTok().getLoc();
2978 if (check(getLexer().is(AsmToken::Percent), L,
2979 "expected immediate expression") ||
2980 getParser().parseExpression(Val, End) ||
2981 check(isa<X86MCExpr>(Val), L, "expected immediate expression"))
2982 return true;
2983 Operands.push_back(X86Operand::CreateImm(Val, Start, End));
2984 return false;
2985 }
2986 case AsmToken::LCurly: {
2987 SMLoc Start = Parser.getTok().getLoc();
2988 return ParseRoundingModeOp(Start, Operands);
2989 }
2990 default: {
2991 // This a memory operand or a register. We have some parsing complications
2992 // as a '(' may be part of an immediate expression or the addressing mode
2993 // block. This is complicated by the fact that an assembler-level variable
2994 // may refer either to a register or an immediate expression.
2995
2996 SMLoc Loc = Parser.getTok().getLoc(), EndLoc;
2997 const MCExpr *Expr = nullptr;
2998 MCRegister Reg;
2999 if (getLexer().isNot(AsmToken::LParen)) {
3000 // No '(' so this is either a displacement expression or a register.
3001 if (Parser.parseExpression(Expr, EndLoc))
3002 return true;
3003 if (auto *RE = dyn_cast<X86MCExpr>(Expr)) {
3004 // Segment Register. Reset Expr and copy value to register.
3005 Expr = nullptr;
3006 Reg = RE->getReg();
3007
3008 // Check the register.
3009 if (Reg == X86::EIZ || Reg == X86::RIZ)
3010 return Error(
3011 Loc, "%eiz and %riz can only be used as index registers",
3012 SMRange(Loc, EndLoc));
3013 if (Reg == X86::RIP)
3014 return Error(Loc, "%rip can only be used as a base register",
3015 SMRange(Loc, EndLoc));
3016 // Return register that are not segment prefixes immediately.
3017 if (!Parser.parseOptionalToken(AsmToken::Colon)) {
3018 Operands.push_back(X86Operand::CreateReg(Reg, Loc, EndLoc));
3019 return false;
3020 }
3021 if (!getX86MCRegisterClass(X86::SEGMENT_REGRegClassID).contains(Reg))
3022 return Error(Loc, "invalid segment register");
3023 // Accept a '*' absolute memory reference after the segment. Place it
3024 // before the full memory operand.
3025 if (getLexer().is(AsmToken::Star))
3026 Operands.push_back(X86Operand::CreateToken("*", consumeToken()));
3027 }
3028 }
3029 // This is a Memory operand.
3030 return ParseMemOperand(Reg, Expr, Loc, EndLoc, Operands);
3031 }
3032 }
3033}
3034
3035// X86::COND_INVALID if not a recognized condition code or alternate mnemonic,
3036// otherwise the EFLAGS Condition Code enumerator.
3037X86::CondCode X86AsmParser::ParseConditionCode(StringRef CC) {
3038 return StringSwitch<X86::CondCode>(CC)
3039 .Case("o", X86::COND_O) // Overflow
3040 .Case("no", X86::COND_NO) // No Overflow
3041 .Cases({"b", "nae"}, X86::COND_B) // Below/Neither Above nor Equal
3042 .Cases({"ae", "nb"}, X86::COND_AE) // Above or Equal/Not Below
3043 .Cases({"e", "z"}, X86::COND_E) // Equal/Zero
3044 .Cases({"ne", "nz"}, X86::COND_NE) // Not Equal/Not Zero
3045 .Cases({"be", "na"}, X86::COND_BE) // Below or Equal/Not Above
3046 .Cases({"a", "nbe"}, X86::COND_A) // Above/Neither Below nor Equal
3047 .Case("s", X86::COND_S) // Sign
3048 .Case("ns", X86::COND_NS) // No Sign
3049 .Cases({"p", "pe"}, X86::COND_P) // Parity/Parity Even
3050 .Cases({"np", "po"}, X86::COND_NP) // No Parity/Parity Odd
3051 .Cases({"l", "nge"}, X86::COND_L) // Less/Neither Greater nor Equal
3052 .Cases({"ge", "nl"}, X86::COND_GE) // Greater or Equal/Not Less
3053 .Cases({"le", "ng"}, X86::COND_LE) // Less or Equal/Not Greater
3054 .Cases({"g", "nle"}, X86::COND_G) // Greater/Neither Less nor Equal
3056}
3057
3058// true on failure, false otherwise
3059// If no {z} mark was found - Parser doesn't advance
3060bool X86AsmParser::ParseZ(std::unique_ptr<X86Operand> &Z, SMLoc StartLoc) {
3061 MCAsmParser &Parser = getParser();
3062 // Assuming we are just pass the '{' mark, quering the next token
3063 // Searched for {z}, but none was found. Return false, as no parsing error was
3064 // encountered
3065 if (!(getLexer().is(AsmToken::Identifier) &&
3066 (getLexer().getTok().getIdentifier() == "z")))
3067 return false;
3068 Parser.Lex(); // Eat z
3069 // Query and eat the '}' mark
3070 if (!getLexer().is(AsmToken::RCurly))
3071 return Error(getLexer().getLoc(), "Expected } at this point");
3072 Parser.Lex(); // Eat '}'
3073 // Assign Z with the {z} mark operand
3074 Z = X86Operand::CreateToken("{z}", StartLoc);
3075 return false;
3076}
3077
3078// true on failure, false otherwise
3079bool X86AsmParser::HandleAVX512Operand(OperandVector &Operands) {
3080 MCAsmParser &Parser = getParser();
3081 if (getLexer().is(AsmToken::LCurly)) {
3082 // Eat "{" and mark the current place.
3083 const SMLoc consumedToken = consumeToken();
3084 // Distinguish {1to<NUM>} from {%k<NUM>}.
3085 if(getLexer().is(AsmToken::Integer)) {
3086 // Parse memory broadcasting ({1to<NUM>}).
3087 if (getLexer().getTok().getIntVal() != 1)
3088 return TokError("Expected 1to<NUM> at this point");
3089 StringRef Prefix = getLexer().getTok().getString();
3090 Parser.Lex(); // Eat first token of 1to8
3091 if (!getLexer().is(AsmToken::Identifier))
3092 return TokError("Expected 1to<NUM> at this point");
3093 // Recognize only reasonable suffixes.
3094 SmallVector<char, 5> BroadcastVector;
3095 StringRef BroadcastString = (Prefix + getLexer().getTok().getIdentifier())
3096 .toStringRef(BroadcastVector);
3097 if (!BroadcastString.starts_with("1to"))
3098 return TokError("Expected 1to<NUM> at this point");
3099 const char *BroadcastPrimitive =
3100 StringSwitch<const char *>(BroadcastString)
3101 .Case("1to2", "{1to2}")
3102 .Case("1to4", "{1to4}")
3103 .Case("1to8", "{1to8}")
3104 .Case("1to16", "{1to16}")
3105 .Case("1to32", "{1to32}")
3106 .Default(nullptr);
3107 if (!BroadcastPrimitive)
3108 return TokError("Invalid memory broadcast primitive.");
3109 Parser.Lex(); // Eat trailing token of 1toN
3110 if (!getLexer().is(AsmToken::RCurly))
3111 return TokError("Expected } at this point");
3112 Parser.Lex(); // Eat "}"
3113 Operands.push_back(X86Operand::CreateToken(BroadcastPrimitive,
3114 consumedToken));
3115 // No AVX512 specific primitives can pass
3116 // after memory broadcasting, so return.
3117 return false;
3118 } else {
3119 // Parse either {k}{z}, {z}{k}, {k} or {z}
3120 // last one have no meaning, but GCC accepts it
3121 // Currently, we're just pass a '{' mark
3122 std::unique_ptr<X86Operand> Z;
3123 if (ParseZ(Z, consumedToken))
3124 return true;
3125 // Reaching here means that parsing of the allegadly '{z}' mark yielded
3126 // no errors.
3127 // Query for the need of further parsing for a {%k<NUM>} mark
3128 if (!Z || getLexer().is(AsmToken::LCurly)) {
3129 SMLoc StartLoc = Z ? consumeToken() : consumedToken;
3130 // Parse an op-mask register mark ({%k<NUM>}), which is now to be
3131 // expected
3132 MCRegister RegNo;
3133 SMLoc RegLoc;
3134 if (!parseRegister(RegNo, RegLoc, StartLoc) &&
3135 getX86MCRegisterClass(X86::VK1RegClassID).contains(RegNo)) {
3136 if (RegNo == X86::K0)
3137 return Error(RegLoc, "Register k0 can't be used as write mask");
3138 if (!getLexer().is(AsmToken::RCurly))
3139 return Error(getLexer().getLoc(), "Expected } at this point");
3140 Operands.push_back(X86Operand::CreateToken("{", StartLoc));
3141 Operands.push_back(
3142 X86Operand::CreateReg(RegNo, StartLoc, StartLoc));
3143 Operands.push_back(X86Operand::CreateToken("}", consumeToken()));
3144 } else
3145 return Error(getLexer().getLoc(),
3146 "Expected an op-mask register at this point");
3147 // {%k<NUM>} mark is found, inquire for {z}
3148 if (getLexer().is(AsmToken::LCurly) && !Z) {
3149 // Have we've found a parsing error, or found no (expected) {z} mark
3150 // - report an error
3151 if (ParseZ(Z, consumeToken()) || !Z)
3152 return Error(getLexer().getLoc(),
3153 "Expected a {z} mark at this point");
3154
3155 }
3156 // '{z}' on its own is meaningless, hence should be ignored.
3157 // on the contrary - have it been accompanied by a K register,
3158 // allow it.
3159 if (Z)
3160 Operands.push_back(std::move(Z));
3161 }
3162 }
3163 }
3164 return false;
3165}
3166
3167/// Returns false if okay and true if there was an overflow.
3168bool X86AsmParser::CheckDispOverflow(MCRegister BaseReg, MCRegister IndexReg,
3169 const MCExpr *Disp, SMLoc Loc) {
3170 // If the displacement is a constant, check overflows. For 64-bit addressing,
3171 // gas requires isInt<32> and otherwise reports an error. For others, gas
3172 // reports a warning and allows a wider range. E.g. gas allows
3173 // [-0xffffffff,0xffffffff] for 32-bit addressing (e.g. Linux kernel uses
3174 // `leal -__PAGE_OFFSET(%ecx),%esp` where __PAGE_OFFSET is 0xc0000000).
3175 if (BaseReg || IndexReg) {
3176 if (auto CE = dyn_cast<MCConstantExpr>(Disp)) {
3177 auto Imm = CE->getValue();
3178 bool Is64 =
3179 getX86MCRegisterClass(X86::GR64RegClassID).contains(BaseReg) ||
3180 getX86MCRegisterClass(X86::GR64RegClassID).contains(IndexReg);
3181 bool Is16 = getX86MCRegisterClass(X86::GR16RegClassID).contains(BaseReg);
3182 if (Is64) {
3183 if (!isInt<32>(Imm))
3184 return Error(Loc, "displacement " + Twine(Imm) +
3185 " is not within [-2147483648, 2147483647]");
3186 } else if (!Is16) {
3187 if (!isUInt<32>(Imm < 0 ? -uint64_t(Imm) : uint64_t(Imm))) {
3188 Warning(Loc, "displacement " + Twine(Imm) +
3189 " shortened to 32-bit signed " +
3190 Twine(static_cast<int32_t>(Imm)));
3191 }
3192 } else if (!isUInt<16>(Imm < 0 ? -uint64_t(Imm) : uint64_t(Imm))) {
3193 Warning(Loc, "displacement " + Twine(Imm) +
3194 " shortened to 16-bit signed " +
3195 Twine(static_cast<int16_t>(Imm)));
3196 }
3197 }
3198 }
3199 return false;
3200}
3201
3202/// ParseMemOperand: 'seg : disp(basereg, indexreg, scale)'. The '%ds:' prefix
3203/// has already been parsed if present. disp may be provided as well.
3204bool X86AsmParser::ParseMemOperand(MCRegister SegReg, const MCExpr *Disp,
3205 SMLoc StartLoc, SMLoc EndLoc,
3207 MCAsmParser &Parser = getParser();
3208 SMLoc Loc;
3209 // Based on the initial passed values, we may be in any of these cases, we are
3210 // in one of these cases (with current position (*)):
3211
3212 // 1. seg : * disp (base-index-scale-expr)
3213 // 2. seg : *(disp) (base-index-scale-expr)
3214 // 3. seg : *(base-index-scale-expr)
3215 // 4. disp *(base-index-scale-expr)
3216 // 5. *(disp) (base-index-scale-expr)
3217 // 6. *(base-index-scale-expr)
3218 // 7. disp *
3219 // 8. *(disp)
3220
3221 // If we do not have an displacement yet, check if we're in cases 4 or 6 by
3222 // checking if the first object after the parenthesis is a register (or an
3223 // identifier referring to a register) and parse the displacement or default
3224 // to 0 as appropriate.
3225 auto isAtMemOperand = [this]() {
3226 if (this->getLexer().isNot(AsmToken::LParen))
3227 return false;
3228 AsmToken Buf[2];
3229 StringRef Id;
3230 auto TokCount = this->getLexer().peekTokens(Buf, true);
3231 if (TokCount == 0)
3232 return false;
3233 switch (Buf[0].getKind()) {
3234 case AsmToken::Percent:
3235 case AsmToken::Comma:
3236 return true;
3237 // These lower cases are doing a peekIdentifier.
3238 case AsmToken::At:
3239 case AsmToken::Dollar:
3240 if ((TokCount > 1) &&
3241 (Buf[1].is(AsmToken::Identifier) || Buf[1].is(AsmToken::String)) &&
3242 (Buf[0].getLoc().getPointer() + 1 == Buf[1].getLoc().getPointer()))
3243 Id = StringRef(Buf[0].getLoc().getPointer(),
3244 Buf[1].getIdentifier().size() + 1);
3245 break;
3247 case AsmToken::String:
3248 Id = Buf[0].getIdentifier();
3249 break;
3250 default:
3251 return false;
3252 }
3253 // We have an ID. Check if it is bound to a register.
3254 if (!Id.empty()) {
3255 MCSymbol *Sym = this->getContext().getOrCreateSymbol(Id);
3256 if (Sym->isVariable()) {
3257 auto V = Sym->getVariableValue();
3258 return isa<X86MCExpr>(V);
3259 }
3260 }
3261 return false;
3262 };
3263
3264 if (!Disp) {
3265 // Parse immediate if we're not at a mem operand yet.
3266 if (!isAtMemOperand()) {
3267 if (Parser.parseTokenLoc(Loc) || Parser.parseExpression(Disp, EndLoc))
3268 return true;
3269 // A register here is a second segment override, or a register standing
3270 // where the displacement belongs.
3271 if (isa<X86MCExpr>(Disp))
3272 return Error(Loc, "unexpected register in memory operand",
3273 SMRange(Loc, EndLoc));
3274 } else {
3275 // Disp is implicitly zero if we haven't parsed it yet.
3276 Disp = MCConstantExpr::create(0, Parser.getContext());
3277 }
3278 }
3279
3280 // We are now either at the end of the operand or at the '(' at the start of a
3281 // base-index-scale-expr.
3282
3283 if (!parseOptionalToken(AsmToken::LParen)) {
3284 if (!SegReg)
3285 Operands.push_back(
3286 X86Operand::CreateMem(getPointerWidth(), Disp, StartLoc, EndLoc));
3287 else
3288 Operands.push_back(X86Operand::CreateMem(getPointerWidth(), SegReg, Disp,
3289 0, 0, 1, StartLoc, EndLoc));
3290 return false;
3291 }
3292
3293 // If we reached here, then eat the '(' and Process
3294 // the rest of the memory operand.
3295 MCRegister BaseReg, IndexReg;
3296 unsigned Scale = 1;
3297 SMLoc BaseLoc = getLexer().getLoc();
3298 const MCExpr *E;
3299 StringRef ErrMsg;
3300
3301 // Parse BaseReg if one is provided.
3302 if (getLexer().isNot(AsmToken::Comma) && getLexer().isNot(AsmToken::RParen)) {
3303 if (Parser.parseExpression(E, EndLoc) ||
3304 check(!isa<X86MCExpr>(E), BaseLoc, "expected register here"))
3305 return true;
3306
3307 // Check the register.
3308 BaseReg = cast<X86MCExpr>(E)->getReg();
3309 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ)
3310 return Error(BaseLoc, "eiz and riz can only be used as index registers",
3311 SMRange(BaseLoc, EndLoc));
3312 }
3313
3314 if (parseOptionalToken(AsmToken::Comma)) {
3315 // Following the comma we should have either an index register, or a scale
3316 // value. We don't support the later form, but we want to parse it
3317 // correctly.
3318 //
3319 // Even though it would be completely consistent to support syntax like
3320 // "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
3321 if (getLexer().isNot(AsmToken::RParen)) {
3322 if (Parser.parseTokenLoc(Loc) || Parser.parseExpression(E, EndLoc))
3323 return true;
3324
3325 if (!isa<X86MCExpr>(E)) {
3326 // We've parsed an unexpected Scale Value instead of an index
3327 // register. Interpret it as an absolute.
3328 int64_t ScaleVal;
3329 if (!E->evaluateAsAbsolute(ScaleVal, getStreamer().getAssemblerPtr()))
3330 return Error(Loc, "expected absolute expression");
3331 if (ScaleVal != 1)
3332 Warning(Loc, "scale factor without index register is ignored");
3333 Scale = 1;
3334 } else { // IndexReg Found.
3335 IndexReg = cast<X86MCExpr>(E)->getReg();
3336
3337 if (BaseReg == X86::RIP)
3338 return Error(Loc,
3339 "%rip as base register can not have an index register");
3340 if (IndexReg == X86::RIP)
3341 return Error(Loc, "%rip is not allowed as an index register");
3342
3343 if (parseOptionalToken(AsmToken::Comma)) {
3344 // Parse the scale amount:
3345 // ::= ',' [scale-expression]
3346
3347 // A scale amount without an index is ignored.
3348 if (getLexer().isNot(AsmToken::RParen)) {
3349 int64_t ScaleVal;
3350 if (Parser.parseTokenLoc(Loc) ||
3351 Parser.parseAbsoluteExpression(ScaleVal))
3352 return Error(Loc, "expected scale expression");
3353 Scale = (unsigned)ScaleVal;
3354 // Validate the scale amount.
3355 if (getX86MCRegisterClass(X86::GR16RegClassID).contains(BaseReg) &&
3356 Scale != 1)
3357 return Error(Loc, "scale factor in 16-bit address must be 1");
3358 if (checkScale(Scale, ErrMsg))
3359 return Error(Loc, ErrMsg);
3360 }
3361 }
3362 }
3363 }
3364 }
3365
3366 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
3367 if (parseToken(AsmToken::RParen, "unexpected token in memory operand"))
3368 return true;
3369
3370 // This is to support otherwise illegal operand (%dx) found in various
3371 // unofficial manuals examples (e.g. "out[s]?[bwl]? %al, (%dx)") and must now
3372 // be supported. Mark such DX variants separately fix only in special cases.
3373 if (BaseReg == X86::DX && !IndexReg && Scale == 1 && !SegReg &&
3374 isa<MCConstantExpr>(Disp) &&
3375 cast<MCConstantExpr>(Disp)->getValue() == 0) {
3376 Operands.push_back(X86Operand::CreateDXReg(BaseLoc, BaseLoc));
3377 return false;
3378 }
3379
3380 if (CheckBaseRegAndIndexRegAndScale(BaseReg, IndexReg, Scale, is64BitMode(),
3381 ErrMsg))
3382 return Error(BaseLoc, ErrMsg);
3383
3384 if (CheckDispOverflow(BaseReg, IndexReg, Disp, BaseLoc))
3385 return true;
3386
3387 if (SegReg || BaseReg || IndexReg)
3388 Operands.push_back(X86Operand::CreateMem(getPointerWidth(), SegReg, Disp,
3389 BaseReg, IndexReg, Scale, StartLoc,
3390 EndLoc));
3391 else
3392 Operands.push_back(
3393 X86Operand::CreateMem(getPointerWidth(), Disp, StartLoc, EndLoc));
3394 return false;
3395}
3396
3397// Parse either a standard primary expression or a register.
3398bool X86AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
3399 MCAsmParser &Parser = getParser();
3400 // See if this is a register first.
3401 if (getTok().is(AsmToken::Percent) ||
3402 (isParsingIntelSyntax() && getTok().is(AsmToken::Identifier) &&
3403 MatchRegisterName(Parser.getTok().getString()))) {
3404 SMLoc StartLoc = Parser.getTok().getLoc();
3405 MCRegister RegNo;
3406 if (parseRegister(RegNo, StartLoc, EndLoc))
3407 return true;
3408 Res = X86MCExpr::create(RegNo, Parser.getContext());
3409 return false;
3410 }
3411 return Parser.parsePrimaryExpr(Res, EndLoc, nullptr);
3412}
3413
3414bool X86AsmParser::parseInstruction(ParseInstructionInfo &Info, StringRef Name,
3415 SMLoc NameLoc, OperandVector &Operands) {
3416 MCAsmParser &Parser = getParser();
3417 InstInfo = &Info;
3418
3419 // Reset the forced VEX encoding.
3420 ForcedOpcodePrefix = OpcodePrefix_Default;
3421 ForcedDispEncoding = DispEncoding_Default;
3422 UseApxExtendedReg = false;
3423 ForcedNoFlag = false;
3424
3425 // Parse pseudo prefixes.
3426 while (true) {
3427 if (Name == "{") {
3428 if (getLexer().isNot(AsmToken::Identifier))
3429 return Error(Parser.getTok().getLoc(), "Unexpected token after '{'");
3430 std::string Prefix = Parser.getTok().getString().lower();
3431 Parser.Lex(); // Eat identifier.
3432 if (getLexer().isNot(AsmToken::RCurly))
3433 return Error(Parser.getTok().getLoc(), "Expected '}'");
3434 Parser.Lex(); // Eat curly.
3435
3436 if (Prefix == "rex")
3437 ForcedOpcodePrefix = OpcodePrefix_REX;
3438 else if (Prefix == "rex2")
3439 ForcedOpcodePrefix = OpcodePrefix_REX2;
3440 else if (Prefix == "vex")
3441 ForcedOpcodePrefix = OpcodePrefix_VEX;
3442 else if (Prefix == "vex2")
3443 ForcedOpcodePrefix = OpcodePrefix_VEX2;
3444 else if (Prefix == "vex3")
3445 ForcedOpcodePrefix = OpcodePrefix_VEX3;
3446 else if (Prefix == "evex")
3447 ForcedOpcodePrefix = OpcodePrefix_EVEX;
3448 else if (Prefix == "disp8")
3449 ForcedDispEncoding = DispEncoding_Disp8;
3450 else if (Prefix == "disp32")
3451 ForcedDispEncoding = DispEncoding_Disp32;
3452 else if (Prefix == "nf")
3453 ForcedNoFlag = true;
3454 else
3455 return Error(NameLoc, "unknown prefix");
3456
3457 NameLoc = Parser.getTok().getLoc();
3458 if (getLexer().is(AsmToken::LCurly)) {
3459 Parser.Lex();
3460 Name = "{";
3461 } else {
3462 if (getLexer().isNot(AsmToken::Identifier))
3463 return Error(Parser.getTok().getLoc(), "Expected identifier");
3464 // FIXME: The mnemonic won't match correctly if its not in lower case.
3465 Name = Parser.getTok().getString();
3466 Parser.Lex();
3467 }
3468 continue;
3469 }
3470 // Parse MASM style pseudo prefixes.
3471 if (isParsingMSInlineAsm()) {
3472 if (Name.equals_insensitive("vex"))
3473 ForcedOpcodePrefix = OpcodePrefix_VEX;
3474 else if (Name.equals_insensitive("vex2"))
3475 ForcedOpcodePrefix = OpcodePrefix_VEX2;
3476 else if (Name.equals_insensitive("vex3"))
3477 ForcedOpcodePrefix = OpcodePrefix_VEX3;
3478 else if (Name.equals_insensitive("evex"))
3479 ForcedOpcodePrefix = OpcodePrefix_EVEX;
3480
3481 if (ForcedOpcodePrefix != OpcodePrefix_Default) {
3482 if (getLexer().isNot(AsmToken::Identifier))
3483 return Error(Parser.getTok().getLoc(), "Expected identifier");
3484 // FIXME: The mnemonic won't match correctly if its not in lower case.
3485 Name = Parser.getTok().getString();
3486 NameLoc = Parser.getTok().getLoc();
3487 Parser.Lex();
3488 }
3489 }
3490 break;
3491 }
3492
3493 // Support the suffix syntax for overriding displacement size as well.
3494 if (Name.consume_back(".d32")) {
3495 ForcedDispEncoding = DispEncoding_Disp32;
3496 } else if (Name.consume_back(".d8")) {
3497 ForcedDispEncoding = DispEncoding_Disp8;
3498 }
3499
3500 StringRef PatchedName = Name;
3501
3502 // Hack to skip "short" following Jcc.
3503 if (isParsingIntelSyntax() &&
3504 (PatchedName == "jmp" || PatchedName == "jc" || PatchedName == "jnc" ||
3505 PatchedName == "jcxz" || PatchedName == "jecxz" ||
3506 (PatchedName.starts_with("j") &&
3507 ParseConditionCode(PatchedName.substr(1)) != X86::COND_INVALID))) {
3508 StringRef NextTok = Parser.getTok().getString();
3509 if (Parser.isParsingMasm() ? NextTok.equals_insensitive("short")
3510 : NextTok == "short") {
3511 SMLoc NameEndLoc =
3512 NameLoc.getFromPointer(NameLoc.getPointer() + Name.size());
3513 // Eat the short keyword.
3514 Parser.Lex();
3515 // MS and GAS ignore the short keyword; they both determine the jmp type
3516 // based on the distance of the label. (NASM does emit different code with
3517 // and without "short," though.)
3518 InstInfo->AsmRewrites->emplace_back(AOK_Skip, NameEndLoc,
3519 NextTok.size() + 1);
3520 }
3521 }
3522
3523 // FIXME: Hack to recognize setneb as setne.
3524 if (PatchedName.starts_with("set") && PatchedName.ends_with("b") &&
3525 PatchedName != "setzub" && PatchedName != "setzunb" &&
3526 PatchedName != "setb" && PatchedName != "setnb")
3527 PatchedName = PatchedName.substr(0, Name.size()-1);
3528
3529 unsigned ComparisonPredicate = ~0U;
3530
3531 // FIXME: Hack to recognize cmp<comparison code>{sh,ss,sd,ph,ps,pd}.
3532 if ((PatchedName.starts_with("cmp") || PatchedName.starts_with("vcmp")) &&
3533 (PatchedName.ends_with("ss") || PatchedName.ends_with("sd") ||
3534 PatchedName.ends_with("sh") || PatchedName.ends_with("ph") ||
3535 PatchedName.ends_with("bf16") || PatchedName.ends_with("ps") ||
3536 PatchedName.ends_with("pd"))) {
3537 bool IsVCMP = PatchedName[0] == 'v';
3538 unsigned CCIdx = IsVCMP ? 4 : 3;
3539 unsigned suffixLength = PatchedName.ends_with("bf16") ? 5 : 2;
3540 unsigned CC = StringSwitch<unsigned>(
3541 PatchedName.slice(CCIdx, PatchedName.size() - suffixLength))
3542 .Case("eq", 0x00)
3543 .Case("eq_oq", 0x00)
3544 .Case("lt", 0x01)
3545 .Case("lt_os", 0x01)
3546 .Case("le", 0x02)
3547 .Case("le_os", 0x02)
3548 .Case("unord", 0x03)
3549 .Case("unord_q", 0x03)
3550 .Case("neq", 0x04)
3551 .Case("neq_uq", 0x04)
3552 .Case("nlt", 0x05)
3553 .Case("nlt_us", 0x05)
3554 .Case("nle", 0x06)
3555 .Case("nle_us", 0x06)
3556 .Case("ord", 0x07)
3557 .Case("ord_q", 0x07)
3558 /* AVX only from here */
3559 .Case("eq_uq", 0x08)
3560 .Case("nge", 0x09)
3561 .Case("nge_us", 0x09)
3562 .Case("ngt", 0x0A)
3563 .Case("ngt_us", 0x0A)
3564 .Case("false", 0x0B)
3565 .Case("false_oq", 0x0B)
3566 .Case("neq_oq", 0x0C)
3567 .Case("ge", 0x0D)
3568 .Case("ge_os", 0x0D)
3569 .Case("gt", 0x0E)
3570 .Case("gt_os", 0x0E)
3571 .Case("true", 0x0F)
3572 .Case("true_uq", 0x0F)
3573 .Case("eq_os", 0x10)
3574 .Case("lt_oq", 0x11)
3575 .Case("le_oq", 0x12)
3576 .Case("unord_s", 0x13)
3577 .Case("neq_us", 0x14)
3578 .Case("nlt_uq", 0x15)
3579 .Case("nle_uq", 0x16)
3580 .Case("ord_s", 0x17)
3581 .Case("eq_us", 0x18)
3582 .Case("nge_uq", 0x19)
3583 .Case("ngt_uq", 0x1A)
3584 .Case("false_os", 0x1B)
3585 .Case("neq_os", 0x1C)
3586 .Case("ge_oq", 0x1D)
3587 .Case("gt_oq", 0x1E)
3588 .Case("true_us", 0x1F)
3589 .Default(~0U);
3590 if (CC != ~0U && (IsVCMP || CC < 8) &&
3591 (IsVCMP || PatchedName.back() != 'h')) {
3592 if (PatchedName.ends_with("ss"))
3593 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
3594 else if (PatchedName.ends_with("sd"))
3595 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
3596 else if (PatchedName.ends_with("ps"))
3597 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
3598 else if (PatchedName.ends_with("pd"))
3599 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
3600 else if (PatchedName.ends_with("sh"))
3601 PatchedName = "vcmpsh";
3602 else if (PatchedName.ends_with("ph"))
3603 PatchedName = "vcmpph";
3604 else if (PatchedName.ends_with("bf16"))
3605 PatchedName = "vcmpbf16";
3606 else
3607 llvm_unreachable("Unexpected suffix!");
3608
3609 ComparisonPredicate = CC;
3610 }
3611 }
3612
3613 // FIXME: Hack to recognize vpcmp<comparison code>{ub,uw,ud,uq,b,w,d,q}.
3614 if (PatchedName.starts_with("vpcmp") &&
3615 (PatchedName.back() == 'b' || PatchedName.back() == 'w' ||
3616 PatchedName.back() == 'd' || PatchedName.back() == 'q')) {
3617 unsigned SuffixSize = PatchedName.drop_back().back() == 'u' ? 2 : 1;
3618 unsigned CC = StringSwitch<unsigned>(
3619 PatchedName.slice(5, PatchedName.size() - SuffixSize))
3620 .Case("eq", 0x0) // Only allowed on unsigned. Checked below.
3621 .Case("lt", 0x1)
3622 .Case("le", 0x2)
3623 //.Case("false", 0x3) // Not a documented alias.
3624 .Case("neq", 0x4)
3625 .Case("nlt", 0x5)
3626 .Case("nle", 0x6)
3627 //.Case("true", 0x7) // Not a documented alias.
3628 .Default(~0U);
3629 if (CC != ~0U && (CC != 0 || SuffixSize == 2)) {
3630 switch (PatchedName.back()) {
3631 default: llvm_unreachable("Unexpected character!");
3632 case 'b': PatchedName = SuffixSize == 2 ? "vpcmpub" : "vpcmpb"; break;
3633 case 'w': PatchedName = SuffixSize == 2 ? "vpcmpuw" : "vpcmpw"; break;
3634 case 'd': PatchedName = SuffixSize == 2 ? "vpcmpud" : "vpcmpd"; break;
3635 case 'q': PatchedName = SuffixSize == 2 ? "vpcmpuq" : "vpcmpq"; break;
3636 }
3637 // Set up the immediate to push into the operands later.
3638 ComparisonPredicate = CC;
3639 }
3640 }
3641
3642 // FIXME: Hack to recognize vpcom<comparison code>{ub,uw,ud,uq,b,w,d,q}.
3643 if (PatchedName.starts_with("vpcom") &&
3644 (PatchedName.back() == 'b' || PatchedName.back() == 'w' ||
3645 PatchedName.back() == 'd' || PatchedName.back() == 'q')) {
3646 unsigned SuffixSize = PatchedName.drop_back().back() == 'u' ? 2 : 1;
3647 unsigned CC = StringSwitch<unsigned>(
3648 PatchedName.slice(5, PatchedName.size() - SuffixSize))
3649 .Case("lt", 0x0)
3650 .Case("le", 0x1)
3651 .Case("gt", 0x2)
3652 .Case("ge", 0x3)
3653 .Case("eq", 0x4)
3654 .Case("neq", 0x5)
3655 .Case("false", 0x6)
3656 .Case("true", 0x7)
3657 .Default(~0U);
3658 if (CC != ~0U) {
3659 switch (PatchedName.back()) {
3660 default: llvm_unreachable("Unexpected character!");
3661 case 'b': PatchedName = SuffixSize == 2 ? "vpcomub" : "vpcomb"; break;
3662 case 'w': PatchedName = SuffixSize == 2 ? "vpcomuw" : "vpcomw"; break;
3663 case 'd': PatchedName = SuffixSize == 2 ? "vpcomud" : "vpcomd"; break;
3664 case 'q': PatchedName = SuffixSize == 2 ? "vpcomuq" : "vpcomq"; break;
3665 }
3666 // Set up the immediate to push into the operands later.
3667 ComparisonPredicate = CC;
3668 }
3669 }
3670
3671 // Determine whether this is an instruction prefix.
3672 // FIXME:
3673 // Enhance prefixes integrity robustness. for example, following forms
3674 // are currently tolerated:
3675 // repz repnz <insn> ; GAS errors for the use of two similar prefixes
3676 // lock addq %rax, %rbx ; Destination operand must be of memory type
3677 // xacquire <insn> ; xacquire must be accompanied by 'lock'
3678 bool IsPrefix =
3679 StringSwitch<bool>(Name)
3680 .Cases({"cs", "ds", "es", "fs", "gs", "ss"}, true)
3681 .Cases({"rex64", "data32", "data16", "addr32", "addr16"}, true)
3682 .Cases({"xacquire", "xrelease"}, true)
3683 .Cases({"acquire", "release"}, isParsingIntelSyntax())
3684 .Default(false);
3685
3686 auto isLockRepeatNtPrefix = [](StringRef N) {
3687 return StringSwitch<bool>(N)
3688 .Cases({"lock", "rep", "repe", "repz", "repne", "repnz", "notrack"},
3689 true)
3690 .Default(false);
3691 };
3692
3693 bool CurlyAsEndOfStatement = false;
3694
3695 unsigned Flags = X86::IP_NO_PREFIX;
3696 while (isLockRepeatNtPrefix(Name.lower())) {
3697 unsigned Prefix =
3698 StringSwitch<unsigned>(Name)
3699 .Case("lock", X86::IP_HAS_LOCK)
3700 .Cases({"rep", "repe", "repz"}, X86::IP_HAS_REPEAT)
3701 .Cases({"repne", "repnz"}, X86::IP_HAS_REPEAT_NE)
3702 .Case("notrack", X86::IP_HAS_NOTRACK)
3703 .Default(X86::IP_NO_PREFIX); // Invalid prefix (impossible)
3704 Flags |= Prefix;
3705 if (getLexer().is(AsmToken::EndOfStatement)) {
3706 // We don't have real instr with the given prefix
3707 // let's use the prefix as the instr.
3708 // TODO: there could be several prefixes one after another
3710 break;
3711 }
3712 // FIXME: The mnemonic won't match correctly if its not in lower case.
3713 Name = Parser.getTok().getString();
3714 Parser.Lex(); // eat the prefix
3715 // Hack: we could have something like "rep # some comment" or
3716 // "lock; cmpxchg16b $1" or "lock\0A\09incl" or "lock/incl"
3717 while (Name.starts_with(";") || Name.starts_with("\n") ||
3718 Name.starts_with("#") || Name.starts_with("\t") ||
3719 Name.starts_with("/")) {
3720 // FIXME: The mnemonic won't match correctly if its not in lower case.
3721 Name = Parser.getTok().getString();
3722 Parser.Lex(); // go to next prefix or instr
3723 }
3724 }
3725
3726 if (Flags)
3727 PatchedName = Name;
3728
3729 // Hacks to handle 'data16' and 'data32'
3730 if (PatchedName == "data16" && is16BitMode()) {
3731 return Error(NameLoc, "redundant data16 prefix");
3732 }
3733 if (PatchedName == "data32") {
3734 if (is32BitMode())
3735 return Error(NameLoc, "redundant data32 prefix");
3736 if (is64BitMode())
3737 return Error(NameLoc, "'data32' is not supported in 64-bit mode");
3738 // Hack to 'data16' for the table lookup.
3739 PatchedName = "data16";
3740
3741 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3742 StringRef Next = Parser.getTok().getString();
3743 getLexer().Lex();
3744 // data32 effectively changes the instruction suffix.
3745 // TODO Generalize.
3746 if (Next == "callw")
3747 Next = "calll";
3748 if (Next == "ljmpw")
3749 Next = "ljmpl";
3750
3751 Name = Next;
3752 PatchedName = Name;
3753 ForcedDataPrefix = X86::Is32Bit;
3754 IsPrefix = false;
3755 }
3756 }
3757
3758 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
3759
3760 // Push the immediate if we extracted one from the mnemonic.
3761 if (ComparisonPredicate != ~0U && !isParsingIntelSyntax()) {
3762 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonPredicate,
3763 getParser().getContext());
3764 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc));
3765 }
3766
3767 // Parse condtional flags after mnemonic.
3768 if ((Name.starts_with("ccmp") || Name.starts_with("ctest")) &&
3769 parseCFlagsOp(Operands))
3770 return true;
3771
3772 // This does the actual operand parsing. Don't parse any more if we have a
3773 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
3774 // just want to parse the "lock" as the first instruction and the "incl" as
3775 // the next one.
3776 if (getLexer().isNot(AsmToken::EndOfStatement) && !IsPrefix) {
3777 // Parse '*' modifier.
3778 if (getLexer().is(AsmToken::Star))
3779 Operands.push_back(X86Operand::CreateToken("*", consumeToken()));
3780
3781 // Read the operands.
3782 while (true) {
3783 if (parseOperand(Operands, Name))
3784 return true;
3785 if (HandleAVX512Operand(Operands))
3786 return true;
3787
3788 // check for comma and eat it
3789 if (getLexer().is(AsmToken::Comma))
3790 Parser.Lex();
3791 else
3792 break;
3793 }
3794
3795 // In MS inline asm curly braces mark the beginning/end of a block,
3796 // therefore they should be interepreted as end of statement
3797 CurlyAsEndOfStatement =
3798 isParsingIntelSyntax() && isParsingMSInlineAsm() &&
3799 (getLexer().is(AsmToken::LCurly) || getLexer().is(AsmToken::RCurly));
3800 if (getLexer().isNot(AsmToken::EndOfStatement) && !CurlyAsEndOfStatement)
3801 return TokError("unexpected token in argument list");
3802 }
3803
3804 // Push the immediate if we extracted one from the mnemonic.
3805 if (ComparisonPredicate != ~0U && isParsingIntelSyntax()) {
3806 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonPredicate,
3807 getParser().getContext());
3808 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc));
3809 }
3810
3811 // Consume the EndOfStatement or the prefix separator Slash
3812 if (getLexer().is(AsmToken::EndOfStatement) ||
3813 (IsPrefix && getLexer().is(AsmToken::Slash)))
3814 Parser.Lex();
3815 else if (CurlyAsEndOfStatement)
3816 // Add an actual EndOfStatement before the curly brace
3817 Info.AsmRewrites->emplace_back(AOK_EndOfStatement,
3818 getLexer().getTok().getLoc(), 0);
3819
3820 // This is for gas compatibility and cannot be done in td.
3821 // Adding "p" for some floating point with no argument.
3822 // For example: fsub --> fsubp
3823 bool IsFp =
3824 Name == "fsub" || Name == "fdiv" || Name == "fsubr" || Name == "fdivr";
3825 if (IsFp && Operands.size() == 1) {
3826 const char *Repl = StringSwitch<const char *>(Name)
3827 .Case("fsub", "fsubp")
3828 .Case("fdiv", "fdivp")
3829 .Case("fsubr", "fsubrp")
3830 .Case("fdivr", "fdivrp");
3831 static_cast<X86Operand &>(*Operands[0]).setTokenValue(Repl);
3832 }
3833
3834 if ((Name == "mov" || Name == "movw" || Name == "movl") &&
3835 (Operands.size() == 3)) {
3836 X86Operand &Op1 = (X86Operand &)*Operands[1];
3837 X86Operand &Op2 = (X86Operand &)*Operands[2];
3838 SMLoc Loc = Op1.getEndLoc();
3839 // Moving a 32 or 16 bit value into a segment register has the same
3840 // behavior. Modify such instructions to always take shorter form.
3841 if (Op1.isReg() && Op2.isReg() &&
3842 getX86MCRegisterClass(X86::SEGMENT_REGRegClassID)
3843 .contains(Op2.getReg()) &&
3844 (getX86MCRegisterClass(X86::GR16RegClassID).contains(Op1.getReg()) ||
3845 getX86MCRegisterClass(X86::GR32RegClassID).contains(Op1.getReg()))) {
3846 // Change instruction name to match new instruction.
3847 if (Name != "mov" && Name[3] == (is16BitMode() ? 'l' : 'w')) {
3848 Name = is16BitMode() ? "movw" : "movl";
3849 Operands[0] = X86Operand::CreateToken(Name, NameLoc);
3850 }
3851 // Select the correct equivalent 16-/32-bit source register.
3852 MCRegister Reg =
3853 getX86SubSuperRegister(Op1.getReg(), is16BitMode() ? 16 : 32);
3854 Operands[1] = X86Operand::CreateReg(Reg, Loc, Loc);
3855 }
3856 }
3857
3858 // This is a terrible hack to handle "out[s]?[bwl]? %al, (%dx)" ->
3859 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
3860 // documented form in various unofficial manuals, so a lot of code uses it.
3861 if ((Name == "outb" || Name == "outsb" || Name == "outw" || Name == "outsw" ||
3862 Name == "outl" || Name == "outsl" || Name == "out" || Name == "outs") &&
3863 Operands.size() == 3) {
3864 X86Operand &Op = (X86Operand &)*Operands.back();
3865 if (Op.isDXReg())
3866 Operands.back() = X86Operand::CreateReg(X86::DX, Op.getStartLoc(),
3867 Op.getEndLoc());
3868 }
3869 // Same hack for "in[s]?[bwl]? (%dx), %al" -> "inb %dx, %al".
3870 if ((Name == "inb" || Name == "insb" || Name == "inw" || Name == "insw" ||
3871 Name == "inl" || Name == "insl" || Name == "in" || Name == "ins") &&
3872 Operands.size() == 3) {
3873 X86Operand &Op = (X86Operand &)*Operands[1];
3874 if (Op.isDXReg())
3875 Operands[1] = X86Operand::CreateReg(X86::DX, Op.getStartLoc(),
3876 Op.getEndLoc());
3877 }
3878
3880 bool HadVerifyError = false;
3881
3882 // Append default arguments to "ins[bwld]"
3883 if (Name.starts_with("ins") &&
3884 (Operands.size() == 1 || Operands.size() == 3) &&
3885 (Name == "insb" || Name == "insw" || Name == "insl" || Name == "insd" ||
3886 Name == "ins")) {
3887
3888 AddDefaultSrcDestOperands(TmpOperands,
3889 X86Operand::CreateReg(X86::DX, NameLoc, NameLoc),
3890 DefaultMemDIOperand(NameLoc));
3891 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
3892 }
3893
3894 // Append default arguments to "outs[bwld]"
3895 if (Name.starts_with("outs") &&
3896 (Operands.size() == 1 || Operands.size() == 3) &&
3897 (Name == "outsb" || Name == "outsw" || Name == "outsl" ||
3898 Name == "outsd" || Name == "outs")) {
3899 AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc),
3900 X86Operand::CreateReg(X86::DX, NameLoc, NameLoc));
3901 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
3902 }
3903
3904 // Transform "lods[bwlq]" into "lods[bwlq] ($SIREG)" for appropriate
3905 // values of $SIREG according to the mode. It would be nice if this
3906 // could be achieved with InstAlias in the tables.
3907 if (Name.starts_with("lods") &&
3908 (Operands.size() == 1 || Operands.size() == 2) &&
3909 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
3910 Name == "lodsl" || Name == "lodsd" || Name == "lodsq")) {
3911 TmpOperands.push_back(DefaultMemSIOperand(NameLoc));
3912 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
3913 }
3914
3915 // Transform "stos[bwlq]" into "stos[bwlq] ($DIREG)" for appropriate
3916 // values of $DIREG according to the mode. It would be nice if this
3917 // could be achieved with InstAlias in the tables.
3918 if (Name.starts_with("stos") &&
3919 (Operands.size() == 1 || Operands.size() == 2) &&
3920 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
3921 Name == "stosl" || Name == "stosd" || Name == "stosq")) {
3922 TmpOperands.push_back(DefaultMemDIOperand(NameLoc));
3923 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
3924 }
3925
3926 // Transform "scas[bwlq]" into "scas[bwlq] ($DIREG)" for appropriate
3927 // values of $DIREG according to the mode. It would be nice if this
3928 // could be achieved with InstAlias in the tables.
3929 if (Name.starts_with("scas") &&
3930 (Operands.size() == 1 || Operands.size() == 2) &&
3931 (Name == "scas" || Name == "scasb" || Name == "scasw" ||
3932 Name == "scasl" || Name == "scasd" || Name == "scasq")) {
3933 TmpOperands.push_back(DefaultMemDIOperand(NameLoc));
3934 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
3935 }
3936
3937 // Add default SI and DI operands to "cmps[bwlq]".
3938 if (Name.starts_with("cmps") &&
3939 (Operands.size() == 1 || Operands.size() == 3) &&
3940 (Name == "cmps" || Name == "cmpsb" || Name == "cmpsw" ||
3941 Name == "cmpsl" || Name == "cmpsd" || Name == "cmpsq")) {
3942 AddDefaultSrcDestOperands(TmpOperands, DefaultMemDIOperand(NameLoc),
3943 DefaultMemSIOperand(NameLoc));
3944 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
3945 }
3946
3947 // Add default SI and DI operands to "movs[bwlq]".
3948 if (((Name.starts_with("movs") &&
3949 (Name == "movs" || Name == "movsb" || Name == "movsw" ||
3950 Name == "movsl" || Name == "movsd" || Name == "movsq")) ||
3951 (Name.starts_with("smov") &&
3952 (Name == "smov" || Name == "smovb" || Name == "smovw" ||
3953 Name == "smovl" || Name == "smovd" || Name == "smovq"))) &&
3954 (Operands.size() == 1 || Operands.size() == 3)) {
3955 if (Name == "movsd" && Operands.size() == 1 && !isParsingIntelSyntax())
3956 Operands.back() = X86Operand::CreateToken("movsl", NameLoc);
3957 AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc),
3958 DefaultMemDIOperand(NameLoc));
3959 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
3960 }
3961
3962 // Check if we encountered an error for one the string insturctions
3963 if (HadVerifyError) {
3964 return HadVerifyError;
3965 }
3966
3967 // Transforms "xlat mem8" into "xlatb"
3968 if ((Name == "xlat" || Name == "xlatb") && Operands.size() == 2) {
3969 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]);
3970 if (Op1.isMem8()) {
3971 Warning(Op1.getStartLoc(), "memory operand is only for determining the "
3972 "size, (R|E)BX will be used for the location");
3973 Operands.pop_back();
3974 static_cast<X86Operand &>(*Operands[0]).setTokenValue("xlatb");
3975 }
3976 }
3977
3978 if (Flags)
3979 Operands.push_back(X86Operand::CreatePrefix(Flags, NameLoc, NameLoc));
3980 return false;
3981}
3982
3983static bool convertSSEToAVX(MCInst &Inst) {
3984 ArrayRef<X86TableEntry> Table{X86SSE2AVXTable};
3985 unsigned Opcode = Inst.getOpcode();
3986 const auto I = llvm::lower_bound(Table, Opcode);
3987 if (I == Table.end() || I->OldOpc != Opcode)
3988 return false;
3989
3990 Inst.setOpcode(I->NewOpc);
3991 // AVX variant of BLENDVPD/BLENDVPS/PBLENDVB instructions has more
3992 // operand compare to SSE variant, which is added below
3993 if (X86::isBLENDVPD(Opcode) || X86::isBLENDVPS(Opcode) ||
3994 X86::isPBLENDVB(Opcode))
3995 Inst.addOperand(Inst.getOperand(2));
3996
3997 return true;
3998}
3999
4000bool X86AsmParser::processInstruction(MCInst &Inst, const OperandVector &Ops) {
4001 if (getTargetOptions().X86Sse2Avx && convertSSEToAVX(Inst))
4002 return true;
4003
4004 if (ForcedOpcodePrefix != OpcodePrefix_VEX3 &&
4005 X86::optimizeInstFromVEX3ToVEX2(Inst, MII.get(Inst.getOpcode())))
4006 return true;
4007
4009 return true;
4010
4011 auto replaceWithCCMPCTEST = [&](unsigned Opcode) -> bool {
4012 if (ForcedOpcodePrefix == OpcodePrefix_EVEX) {
4013 Inst.setFlags(~(X86::IP_USE_EVEX)&Inst.getFlags());
4014 Inst.setOpcode(Opcode);
4017 return true;
4018 }
4019 return false;
4020 };
4021
4022 switch (Inst.getOpcode()) {
4023 default: return false;
4024 case X86::JMP_1:
4025 // {disp32} forces a larger displacement as if the instruction was relaxed.
4026 // NOTE: 16-bit mode uses 16-bit displacement even though it says {disp32}.
4027 // This matches GNU assembler.
4028 if (ForcedDispEncoding == DispEncoding_Disp32) {
4029 Inst.setOpcode(is16BitMode() ? X86::JMP_2 : X86::JMP_4);
4030 return true;
4031 }
4032
4033 return false;
4034 case X86::JCC_1:
4035 // {disp32} forces a larger displacement as if the instruction was relaxed.
4036 // NOTE: 16-bit mode uses 16-bit displacement even though it says {disp32}.
4037 // This matches GNU assembler.
4038 if (ForcedDispEncoding == DispEncoding_Disp32) {
4039 Inst.setOpcode(is16BitMode() ? X86::JCC_2 : X86::JCC_4);
4040 return true;
4041 }
4042
4043 return false;
4044 case X86::INT: {
4045 // Transforms "int $3" into "int3" as a size optimization.
4046 // We can't write this as an InstAlias.
4047 if (!Inst.getOperand(0).isImm() || Inst.getOperand(0).getImm() != 3)
4048 return false;
4049 Inst.clear();
4050 Inst.setOpcode(X86::INT3);
4051 return true;
4052 }
4053 // `{evex} cmp <>, <>` is alias of `ccmpt {dfv=} <>, <>`, and
4054 // `{evex} test <>, <>` is alias of `ctest {dfv=} <>, <>`
4055#define FROM_TO(FROM, TO) \
4056 case X86::FROM: \
4057 return replaceWithCCMPCTEST(X86::TO);
4058 FROM_TO(CMP64rr, CCMP64rr)
4059 FROM_TO(CMP64mi32, CCMP64mi32)
4060 FROM_TO(CMP64mi8, CCMP64mi8)
4061 FROM_TO(CMP64mr, CCMP64mr)
4062 FROM_TO(CMP64ri32, CCMP64ri32)
4063 FROM_TO(CMP64ri8, CCMP64ri8)
4064 FROM_TO(CMP64rm, CCMP64rm)
4065
4066 FROM_TO(CMP32rr, CCMP32rr)
4067 FROM_TO(CMP32mi, CCMP32mi)
4068 FROM_TO(CMP32mi8, CCMP32mi8)
4069 FROM_TO(CMP32mr, CCMP32mr)
4070 FROM_TO(CMP32ri, CCMP32ri)
4071 FROM_TO(CMP32ri8, CCMP32ri8)
4072 FROM_TO(CMP32rm, CCMP32rm)
4073
4074 FROM_TO(CMP16rr, CCMP16rr)
4075 FROM_TO(CMP16mi, CCMP16mi)
4076 FROM_TO(CMP16mi8, CCMP16mi8)
4077 FROM_TO(CMP16mr, CCMP16mr)
4078 FROM_TO(CMP16ri, CCMP16ri)
4079 FROM_TO(CMP16ri8, CCMP16ri8)
4080 FROM_TO(CMP16rm, CCMP16rm)
4081
4082 FROM_TO(CMP8rr, CCMP8rr)
4083 FROM_TO(CMP8mi, CCMP8mi)
4084 FROM_TO(CMP8mr, CCMP8mr)
4085 FROM_TO(CMP8ri, CCMP8ri)
4086 FROM_TO(CMP8rm, CCMP8rm)
4087
4088 FROM_TO(TEST64rr, CTEST64rr)
4089 FROM_TO(TEST64mi32, CTEST64mi32)
4090 FROM_TO(TEST64mr, CTEST64mr)
4091 FROM_TO(TEST64ri32, CTEST64ri32)
4092
4093 FROM_TO(TEST32rr, CTEST32rr)
4094 FROM_TO(TEST32mi, CTEST32mi)
4095 FROM_TO(TEST32mr, CTEST32mr)
4096 FROM_TO(TEST32ri, CTEST32ri)
4097
4098 FROM_TO(TEST16rr, CTEST16rr)
4099 FROM_TO(TEST16mi, CTEST16mi)
4100 FROM_TO(TEST16mr, CTEST16mr)
4101 FROM_TO(TEST16ri, CTEST16ri)
4102
4103 FROM_TO(TEST8rr, CTEST8rr)
4104 FROM_TO(TEST8mi, CTEST8mi)
4105 FROM_TO(TEST8mr, CTEST8mr)
4106 FROM_TO(TEST8ri, CTEST8ri)
4107#undef FROM_TO
4108 }
4109}
4110
4111bool X86AsmParser::validateInstruction(MCInst &Inst, const OperandVector &Ops) {
4112 using namespace X86;
4113 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
4114 unsigned Opcode = Inst.getOpcode();
4115 uint64_t TSFlags = MII.get(Opcode).TSFlags;
4116 if (isVFCMADDCPH(Opcode) || isVFCMADDCSH(Opcode) || isVFMADDCPH(Opcode) ||
4117 isVFMADDCSH(Opcode)) {
4118 MCRegister Dest = Inst.getOperand(0).getReg();
4119 for (unsigned i = 2; i < Inst.getNumOperands(); i++)
4120 if (Inst.getOperand(i).isReg() && Dest == Inst.getOperand(i).getReg())
4121 return Warning(Ops[0]->getStartLoc(), "Destination register should be "
4122 "distinct from source registers");
4123 } else if (isVFCMULCPH(Opcode) || isVFCMULCSH(Opcode) || isVFMULCPH(Opcode) ||
4124 isVFMULCSH(Opcode)) {
4125 MCRegister Dest = Inst.getOperand(0).getReg();
4126 // The mask variants have different operand list. Scan from the third
4127 // operand to avoid emitting incorrect warning.
4128 // VFMULCPHZrr Dest, Src1, Src2
4129 // VFMULCPHZrrk Dest, Dest, Mask, Src1, Src2
4130 // VFMULCPHZrrkz Dest, Mask, Src1, Src2
4131 for (unsigned i = ((TSFlags & X86II::EVEX_K) ? 2 : 1);
4132 i < Inst.getNumOperands(); i++)
4133 if (Inst.getOperand(i).isReg() && Dest == Inst.getOperand(i).getReg())
4134 return Warning(Ops[0]->getStartLoc(), "Destination register should be "
4135 "distinct from source registers");
4136 } else if (isV4FMADDPS(Opcode) || isV4FMADDSS(Opcode) ||
4137 isV4FNMADDPS(Opcode) || isV4FNMADDSS(Opcode) ||
4138 isVP4DPWSSDS(Opcode) || isVP4DPWSSD(Opcode)) {
4139 MCRegister Src2 =
4141 .getReg();
4142 unsigned Src2Enc = MRI->getEncodingValue(Src2);
4143 if (Src2Enc % 4 != 0) {
4145 unsigned GroupStart = (Src2Enc / 4) * 4;
4146 unsigned GroupEnd = GroupStart + 3;
4147 return Warning(Ops[0]->getStartLoc(),
4148 "source register '" + RegName + "' implicitly denotes '" +
4149 RegName.take_front(3) + Twine(GroupStart) + "' to '" +
4150 RegName.take_front(3) + Twine(GroupEnd) +
4151 "' source group");
4152 }
4153 } else if (isVGATHERDPD(Opcode) || isVGATHERDPS(Opcode) ||
4154 isVGATHERQPD(Opcode) || isVGATHERQPS(Opcode) ||
4155 isVPGATHERDD(Opcode) || isVPGATHERDQ(Opcode) ||
4156 isVPGATHERQD(Opcode) || isVPGATHERQQ(Opcode)) {
4157 bool HasEVEX = (TSFlags & X86II::EncodingMask) == X86II::EVEX;
4158 if (HasEVEX) {
4159 unsigned Dest = MRI->getEncodingValue(Inst.getOperand(0).getReg());
4160 unsigned Index = MRI->getEncodingValue(
4161 Inst.getOperand(4 + X86::AddrIndexReg).getReg());
4162 if (Dest == Index)
4163 return Warning(Ops[0]->getStartLoc(), "index and destination registers "
4164 "should be distinct");
4165 } else {
4166 unsigned Dest = MRI->getEncodingValue(Inst.getOperand(0).getReg());
4167 unsigned Mask = MRI->getEncodingValue(Inst.getOperand(1).getReg());
4168 unsigned Index = MRI->getEncodingValue(
4169 Inst.getOperand(3 + X86::AddrIndexReg).getReg());
4170 if (Dest == Mask || Dest == Index || Mask == Index)
4171 return Warning(Ops[0]->getStartLoc(), "mask, index, and destination "
4172 "registers should be distinct");
4173 }
4174 } else if (isTCMMIMFP16PS(Opcode) || isTCMMRLFP16PS(Opcode) ||
4175 isTDPBF16PS(Opcode) || isTDPFP16PS(Opcode) || isTDPBSSD(Opcode) ||
4176 isTDPBSUD(Opcode) || isTDPBUSD(Opcode) || isTDPBUUD(Opcode)) {
4177 MCRegister SrcDest = Inst.getOperand(0).getReg();
4178 MCRegister Src1 = Inst.getOperand(2).getReg();
4179 MCRegister Src2 = Inst.getOperand(3).getReg();
4180 if (SrcDest == Src1 || SrcDest == Src2 || Src1 == Src2)
4181 return Error(Ops[0]->getStartLoc(), "all tmm registers must be distinct");
4182 }
4183
4184 // High 8-bit regs (AH/BH/CH/DH) are incompatible with encodings that imply
4185 // extended prefixes:
4186 // * Legacy path that would emit a REX (e.g. uses r8..r15 or sil/dil/bpl/spl)
4187 // * EVEX
4188 // * REX2
4189 // VEX/XOP don't use REX; they are excluded from the legacy check.
4190 const unsigned Enc = TSFlags & X86II::EncodingMask;
4191 if (Enc != X86II::VEX && Enc != X86II::XOP) {
4192 MCRegister HReg;
4193 bool UsesRex = TSFlags & X86II::REX_W;
4194 unsigned NumOps = Inst.getNumOperands();
4195 for (unsigned i = 0; i != NumOps; ++i) {
4196 const MCOperand &MO = Inst.getOperand(i);
4197 if (!MO.isReg())
4198 continue;
4199 MCRegister Reg = MO.getReg();
4200 if (Reg == X86::AH || Reg == X86::BH || Reg == X86::CH || Reg == X86::DH)
4201 HReg = Reg;
4204 UsesRex = true;
4205 }
4206
4207 if (HReg &&
4208 (Enc == X86II::EVEX || ForcedOpcodePrefix == OpcodePrefix_REX2 ||
4209 ForcedOpcodePrefix == OpcodePrefix_REX || UsesRex)) {
4211 return Error(Ops[0]->getStartLoc(),
4212 "can't encode '" + RegName.str() +
4213 "' in an instruction requiring EVEX/REX2/REX prefix");
4214 }
4215 }
4216
4217 if ((Opcode == X86::PREFETCHIT0 || Opcode == X86::PREFETCHIT1)) {
4218 const MCOperand &MO = Inst.getOperand(X86::AddrBaseReg);
4219 if (!MO.isReg() || MO.getReg() != X86::RIP)
4220 return Warning(
4221 Ops[0]->getStartLoc(),
4222 Twine((Inst.getOpcode() == X86::PREFETCHIT0 ? "'prefetchit0'"
4223 : "'prefetchit1'")) +
4224 " only supports RIP-relative address");
4225 }
4226 return false;
4227}
4228
4229void X86AsmParser::emitWarningForSpecialLVIInstruction(SMLoc Loc) {
4230 Warning(Loc, "Instruction may be vulnerable to LVI and "
4231 "requires manual mitigation");
4232 Note(SMLoc(), "See https://software.intel.com/"
4233 "security-software-guidance/insights/"
4234 "deep-dive-load-value-injection#specialinstructions"
4235 " for more information");
4236}
4237
4238/// RET instructions and also instructions that indirect calls/jumps from memory
4239/// combine a load and a branch within a single instruction. To mitigate these
4240/// instructions against LVI, they must be decomposed into separate load and
4241/// branch instructions, with an LFENCE in between. For more details, see:
4242/// - X86LoadValueInjectionRetHardening.cpp
4243/// - X86LoadValueInjectionIndirectThunks.cpp
4244/// - https://software.intel.com/security-software-guidance/insights/deep-dive-load-value-injection
4245///
4246/// Returns `true` if a mitigation was applied or warning was emitted.
4247void X86AsmParser::applyLVICFIMitigation(MCInst &Inst, MCStreamer &Out) {
4248 // Information on control-flow instructions that require manual mitigation can
4249 // be found here:
4250 // https://software.intel.com/security-software-guidance/insights/deep-dive-load-value-injection#specialinstructions
4251 switch (Inst.getOpcode()) {
4252 case X86::RET16:
4253 case X86::RET32:
4254 case X86::RET64:
4255 case X86::RETI16:
4256 case X86::RETI32:
4257 case X86::RETI64: {
4258 MCInst ShlInst, FenceInst;
4259 bool Parse32 = is32BitMode() || Code16GCC;
4260 MCRegister Basereg =
4261 is64BitMode() ? X86::RSP : (Parse32 ? X86::ESP : X86::SP);
4262 const MCExpr *Disp = MCConstantExpr::create(0, getContext());
4263 auto ShlMemOp = X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp,
4264 /*BaseReg=*/Basereg, /*IndexReg=*/0,
4265 /*Scale=*/1, SMLoc{}, SMLoc{}, 0);
4266 ShlInst.setOpcode(X86::SHL64mi);
4267 ShlMemOp->addMemOperands(ShlInst, 5);
4268 ShlInst.addOperand(MCOperand::createImm(0));
4269 FenceInst.setOpcode(X86::LFENCE);
4270 Out.emitInstruction(ShlInst, getSTI());
4271 Out.emitInstruction(FenceInst, getSTI());
4272 return;
4273 }
4274 case X86::JMP16m:
4275 case X86::JMP32m:
4276 case X86::JMP64m:
4277 case X86::CALL16m:
4278 case X86::CALL32m:
4279 case X86::CALL64m:
4280 emitWarningForSpecialLVIInstruction(Inst.getLoc());
4281 return;
4282 }
4283}
4284
4285/// To mitigate LVI, every instruction that performs a load can be followed by
4286/// an LFENCE instruction to squash any potential mis-speculation. There are
4287/// some instructions that require additional considerations, and may requre
4288/// manual mitigation. For more details, see:
4289/// https://software.intel.com/security-software-guidance/insights/deep-dive-load-value-injection
4290///
4291/// Returns `true` if a mitigation was applied or warning was emitted.
4292void X86AsmParser::applyLVILoadHardeningMitigation(MCInst &Inst,
4293 MCStreamer &Out) {
4294 auto Opcode = Inst.getOpcode();
4295 auto Flags = Inst.getFlags();
4296 if ((Flags & X86::IP_HAS_REPEAT) || (Flags & X86::IP_HAS_REPEAT_NE)) {
4297 // Information on REP string instructions that require manual mitigation can
4298 // be found here:
4299 // https://software.intel.com/security-software-guidance/insights/deep-dive-load-value-injection#specialinstructions
4300 switch (Opcode) {
4301 case X86::CMPSB:
4302 case X86::CMPSW:
4303 case X86::CMPSL:
4304 case X86::CMPSQ:
4305 case X86::SCASB:
4306 case X86::SCASW:
4307 case X86::SCASL:
4308 case X86::SCASQ:
4309 emitWarningForSpecialLVIInstruction(Inst.getLoc());
4310 return;
4311 }
4312 } else if (Opcode == X86::REP_PREFIX || Opcode == X86::REPNE_PREFIX) {
4313 // If a REP instruction is found on its own line, it may or may not be
4314 // followed by a vulnerable instruction. Emit a warning just in case.
4315 emitWarningForSpecialLVIInstruction(Inst.getLoc());
4316 return;
4317 }
4318
4319 const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
4320
4321 // Can't mitigate after terminators or calls. A control flow change may have
4322 // already occurred.
4323 if (MCID.isTerminator() || MCID.isCall())
4324 return;
4325
4326 // LFENCE has the mayLoad property, don't double fence.
4327 if (MCID.mayLoad() && Inst.getOpcode() != X86::LFENCE) {
4328 MCInst FenceInst;
4329 FenceInst.setOpcode(X86::LFENCE);
4330 Out.emitInstruction(FenceInst, getSTI());
4331 }
4332}
4333
4334void X86AsmParser::emitInstruction(MCInst &Inst, OperandVector &Operands,
4335 MCStreamer &Out) {
4336 if (CLOpts.experimental_lvi_inline_asm_hardening &&
4337 getSTI().hasFeature(X86::FeatureLVIControlFlowIntegrity))
4338 applyLVICFIMitigation(Inst, Out);
4339
4340 Out.emitInstruction(Inst, getSTI());
4341
4342 if (CLOpts.experimental_lvi_inline_asm_hardening &&
4343 getSTI().hasFeature(X86::FeatureLVILoadHardening))
4344 applyLVILoadHardeningMitigation(Inst, Out);
4345}
4346
4348 unsigned Result = 0;
4349 X86Operand &Prefix = static_cast<X86Operand &>(*Operands.back());
4350 if (Prefix.isPrefix()) {
4351 Result = Prefix.getPrefix();
4352 Operands.pop_back();
4353 }
4354 return Result;
4355}
4356
4357bool X86AsmParser::matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
4359 MCStreamer &Out, uint64_t &ErrorInfo,
4360 bool MatchingInlineAsm) {
4361 assert(!Operands.empty() && "Unexpect empty operand list!");
4362 assert((*Operands[0]).isToken() && "Leading operand should always be a mnemonic!");
4363
4364 // First, handle aliases that expand to multiple instructions.
4365 MatchFPUWaitAlias(IDLoc, static_cast<X86Operand &>(*Operands[0]), Operands,
4366 Out, MatchingInlineAsm);
4367 unsigned Prefixes = getPrefixes(Operands);
4368
4369 MCInst Inst;
4370
4371 // If REX/REX2/VEX/EVEX encoding is forced, we need to pass the USE_* flag to
4372 // the encoder and printer.
4373 if (ForcedOpcodePrefix == OpcodePrefix_REX)
4374 Prefixes |= X86::IP_USE_REX;
4375 else if (ForcedOpcodePrefix == OpcodePrefix_REX2)
4376 Prefixes |= X86::IP_USE_REX2;
4377 else if (ForcedOpcodePrefix == OpcodePrefix_VEX)
4378 Prefixes |= X86::IP_USE_VEX;
4379 else if (ForcedOpcodePrefix == OpcodePrefix_VEX2)
4380 Prefixes |= X86::IP_USE_VEX2;
4381 else if (ForcedOpcodePrefix == OpcodePrefix_VEX3)
4382 Prefixes |= X86::IP_USE_VEX3;
4383 else if (ForcedOpcodePrefix == OpcodePrefix_EVEX)
4384 Prefixes |= X86::IP_USE_EVEX;
4385
4386 // Set encoded flags for {disp8} and {disp32}.
4387 if (ForcedDispEncoding == DispEncoding_Disp8)
4388 Prefixes |= X86::IP_USE_DISP8;
4389 else if (ForcedDispEncoding == DispEncoding_Disp32)
4390 Prefixes |= X86::IP_USE_DISP32;
4391
4392 if (Prefixes)
4393 Inst.setFlags(Prefixes);
4394
4395 return isParsingIntelSyntax()
4396 ? matchAndEmitIntelInstruction(IDLoc, Opcode, Inst, Operands, Out,
4397 ErrorInfo, MatchingInlineAsm)
4398 : matchAndEmitATTInstruction(IDLoc, Opcode, Inst, Operands, Out,
4399 ErrorInfo, MatchingInlineAsm);
4400}
4401
4402void X86AsmParser::MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op,
4403 OperandVector &Operands, MCStreamer &Out,
4404 bool MatchingInlineAsm) {
4405 // FIXME: This should be replaced with a real .td file alias mechanism.
4406 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
4407 // call.
4408 const char *Repl = StringSwitch<const char *>(Op.getToken())
4409 .Case("finit", "fninit")
4410 .Case("fsave", "fnsave")
4411 .Case("fstcw", "fnstcw")
4412 .Case("fstcww", "fnstcw")
4413 .Case("fstenv", "fnstenv")
4414 .Case("fstsw", "fnstsw")
4415 .Case("fstsww", "fnstsw")
4416 .Case("fclex", "fnclex")
4417 .Default(nullptr);
4418 if (Repl) {
4419 MCInst Inst;
4420 Inst.setOpcode(X86::WAIT);
4421 Inst.setLoc(IDLoc);
4422 if (!MatchingInlineAsm)
4423 emitInstruction(Inst, Operands, Out);
4424 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
4425 }
4426}
4427
4428bool X86AsmParser::ErrorMissingFeature(SMLoc IDLoc,
4429 const FeatureBitset &MissingFeatures,
4430 bool MatchingInlineAsm) {
4431 assert(MissingFeatures.any() && "Unknown missing feature!");
4432 SmallString<126> Msg;
4433 raw_svector_ostream OS(Msg);
4434 OS << "instruction requires:";
4435 for (unsigned Feature : MissingFeatures)
4436 OS << ' ' << getSubtargetFeatureName(Feature);
4437 return Error(IDLoc, OS.str(), SMRange(), MatchingInlineAsm);
4438}
4439
4440unsigned X86AsmParser::checkTargetMatchPredicate(MCInst &Inst) {
4441 unsigned Opc = Inst.getOpcode();
4442 const MCInstrDesc &MCID = MII.get(Opc);
4443 uint64_t TSFlags = MCID.TSFlags;
4444
4445 if (UseApxExtendedReg && !X86II::canUseApxExtendedReg(MCID))
4446 return Match_Unsupported;
4447 if (ForcedNoFlag == !(TSFlags & X86II::EVEX_NF) && !X86::isCFCMOVCC(Opc))
4448 return Match_Unsupported;
4449
4450 switch (ForcedOpcodePrefix) {
4451 case OpcodePrefix_Default:
4452 break;
4453 case OpcodePrefix_REX:
4454 case OpcodePrefix_REX2:
4455 if (TSFlags & X86II::EncodingMask)
4456 return Match_Unsupported;
4457 break;
4458 case OpcodePrefix_VEX:
4459 case OpcodePrefix_VEX2:
4460 case OpcodePrefix_VEX3:
4461 if ((TSFlags & X86II::EncodingMask) != X86II::VEX)
4462 return Match_Unsupported;
4463 break;
4464 case OpcodePrefix_EVEX:
4465 if (is64BitMode() && (TSFlags & X86II::EncodingMask) != X86II::EVEX &&
4466 !X86::isCMP(Opc) && !X86::isTEST(Opc))
4467 return Match_Unsupported;
4468 if (!is64BitMode() && (TSFlags & X86II::EncodingMask) != X86II::EVEX)
4469 return Match_Unsupported;
4470 break;
4471 }
4472
4474 (ForcedOpcodePrefix != OpcodePrefix_VEX &&
4475 ForcedOpcodePrefix != OpcodePrefix_VEX2 &&
4476 ForcedOpcodePrefix != OpcodePrefix_VEX3))
4477 return Match_Unsupported;
4478
4479 return Match_Success;
4480}
4481
4482bool X86AsmParser::matchAndEmitATTInstruction(
4483 SMLoc IDLoc, unsigned &Opcode, MCInst &Inst, OperandVector &Operands,
4484 MCStreamer &Out, uint64_t &ErrorInfo, bool MatchingInlineAsm) {
4485 X86Operand &Op = static_cast<X86Operand &>(*Operands[0]);
4486 SMRange EmptyRange;
4487 // In 16-bit mode, if data32 is specified, temporarily switch to 32-bit mode
4488 // when matching the instruction.
4489 if (ForcedDataPrefix == X86::Is32Bit)
4490 SwitchMode(X86::Is32Bit);
4491 // First, try a direct match.
4492 FeatureBitset MissingFeatures;
4493 unsigned OriginalError = MatchInstruction(Operands, Inst, ErrorInfo,
4494 MissingFeatures, MatchingInlineAsm,
4495 isParsingIntelSyntax());
4496 if (ForcedDataPrefix == X86::Is32Bit) {
4497 SwitchMode(X86::Is16Bit);
4498 ForcedDataPrefix = 0;
4499 }
4500 switch (OriginalError) {
4501 default: llvm_unreachable("Unexpected match result!");
4502 case Match_Success:
4503 if (!MatchingInlineAsm && validateInstruction(Inst, Operands))
4504 return true;
4505 // Some instructions need post-processing to, for example, tweak which
4506 // encoding is selected. Loop on it while changes happen so the
4507 // individual transformations can chain off each other.
4508 if (!MatchingInlineAsm)
4509 while (processInstruction(Inst, Operands))
4510 ;
4511
4512 Inst.setLoc(IDLoc);
4513 if (!MatchingInlineAsm)
4514 emitInstruction(Inst, Operands, Out);
4515 Opcode = Inst.getOpcode();
4516 return false;
4517 case Match_InvalidImmUnsignedi4: {
4518 SMLoc ErrorLoc = ((X86Operand &)*Operands[ErrorInfo]).getStartLoc();
4519 if (ErrorLoc == SMLoc())
4520 ErrorLoc = IDLoc;
4521 return Error(ErrorLoc, "immediate must be an integer in range [0, 15]",
4522 EmptyRange, MatchingInlineAsm);
4523 }
4524 case Match_InvalidImmUnsignedi6: {
4525 SMLoc ErrorLoc = ((X86Operand &)*Operands[ErrorInfo]).getStartLoc();
4526 if (ErrorLoc == SMLoc())
4527 ErrorLoc = IDLoc;
4528 return Error(ErrorLoc, "immediate must be an integer in range [0, 63]",
4529 EmptyRange, MatchingInlineAsm);
4530 }
4531 case Match_MissingFeature:
4532 return ErrorMissingFeature(IDLoc, MissingFeatures, MatchingInlineAsm);
4533 case Match_InvalidOperand:
4534 case Match_MnemonicFail:
4535 case Match_Unsupported:
4536 break;
4537 }
4538 if (Op.getToken().empty()) {
4539 Error(IDLoc, "instruction must have size higher than 0", EmptyRange,
4540 MatchingInlineAsm);
4541 return true;
4542 }
4543
4544 // FIXME: Ideally, we would only attempt suffix matches for things which are
4545 // valid prefixes, and we could just infer the right unambiguous
4546 // type. However, that requires substantially more matcher support than the
4547 // following hack.
4548
4549 // Change the operand to point to a temporary token.
4550 StringRef Base = Op.getToken();
4551 SmallString<16> Tmp;
4552 Tmp += Base;
4553 Tmp += ' ';
4554 Op.setTokenValue(Tmp);
4555
4556 // If this instruction starts with an 'f', then it is a floating point stack
4557 // instruction. These come in up to three forms for 32-bit, 64-bit, and
4558 // 80-bit floating point, which use the suffixes s,l,t respectively.
4559 //
4560 // Otherwise, we assume that this may be an integer instruction, which comes
4561 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
4562 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
4563 // MemSize corresponding to Suffixes. { 8, 16, 32, 64 } { 32, 64, 80, 0 }
4564 const char *MemSize = Base[0] != 'f' ? "\x08\x10\x20\x40" : "\x20\x40\x50\0";
4565
4566 // Check for the various suffix matches.
4567 uint64_t ErrorInfoIgnore;
4568 FeatureBitset ErrorInfoMissingFeatures; // Init suppresses compiler warnings.
4569 unsigned Match[4];
4570
4571 // Some instruction like VPMULDQ is NOT the variant of VPMULD but a new one.
4572 // So we should make sure the suffix matcher only works for memory variant
4573 // that has the same size with the suffix.
4574 // FIXME: This flag is a workaround for legacy instructions that didn't
4575 // declare non suffix variant assembly.
4576 bool HasVectorReg = false;
4577 X86Operand *MemOp = nullptr;
4578 for (const auto &Op : Operands) {
4579 X86Operand *X86Op = static_cast<X86Operand *>(Op.get());
4580 if (X86Op->isVectorReg())
4581 HasVectorReg = true;
4582 else if (X86Op->isMem()) {
4583 MemOp = X86Op;
4584 assert(MemOp->Mem.Size == 0 && "Memory size always 0 under ATT syntax");
4585 // Have we found an unqualified memory operand,
4586 // break. IA allows only one memory operand.
4587 break;
4588 }
4589 }
4590
4591 for (unsigned I = 0, E = std::size(Match); I != E; ++I) {
4592 Tmp.back() = Suffixes[I];
4593 if (MemOp && HasVectorReg)
4594 MemOp->Mem.Size = MemSize[I];
4595 Match[I] = Match_MnemonicFail;
4596 if (MemOp || !HasVectorReg) {
4597 Match[I] =
4598 MatchInstruction(Operands, Inst, ErrorInfoIgnore, MissingFeatures,
4599 MatchingInlineAsm, isParsingIntelSyntax());
4600 // If this returned as a missing feature failure, remember that.
4601 if (Match[I] == Match_MissingFeature)
4602 ErrorInfoMissingFeatures = MissingFeatures;
4603 }
4604 }
4605
4606 // Restore the old token.
4607 Op.setTokenValue(Base);
4608
4609 // If exactly one matched, then we treat that as a successful match (and the
4610 // instruction will already have been filled in correctly, since the failing
4611 // matches won't have modified it).
4612 unsigned NumSuccessfulMatches = llvm::count(Match, Match_Success);
4613 if (NumSuccessfulMatches == 1) {
4614 if (!MatchingInlineAsm && validateInstruction(Inst, Operands))
4615 return true;
4616 // Some instructions need post-processing to, for example, tweak which
4617 // encoding is selected. Loop on it while changes happen so the
4618 // individual transformations can chain off each other.
4619 if (!MatchingInlineAsm)
4620 while (processInstruction(Inst, Operands))
4621 ;
4622
4623 Inst.setLoc(IDLoc);
4624 if (!MatchingInlineAsm)
4625 emitInstruction(Inst, Operands, Out);
4626 Opcode = Inst.getOpcode();
4627 return false;
4628 }
4629
4630 // Otherwise, the match failed, try to produce a decent error message.
4631
4632 // If we had multiple suffix matches, then identify this as an ambiguous
4633 // match.
4634 if (NumSuccessfulMatches > 1) {
4635 char MatchChars[4];
4636 unsigned NumMatches = 0;
4637 for (unsigned I = 0, E = std::size(Match); I != E; ++I)
4638 if (Match[I] == Match_Success)
4639 MatchChars[NumMatches++] = Suffixes[I];
4640
4641 SmallString<126> Msg;
4642 raw_svector_ostream OS(Msg);
4643 OS << "ambiguous instructions require an explicit suffix (could be ";
4644 for (unsigned i = 0; i != NumMatches; ++i) {
4645 if (i != 0)
4646 OS << ", ";
4647 if (i + 1 == NumMatches)
4648 OS << "or ";
4649 OS << "'" << Base << MatchChars[i] << "'";
4650 }
4651 OS << ")";
4652 Error(IDLoc, OS.str(), EmptyRange, MatchingInlineAsm);
4653 return true;
4654 }
4655
4656 // Okay, we know that none of the variants matched successfully.
4657
4658 // If all of the instructions reported an invalid mnemonic, then the original
4659 // mnemonic was invalid.
4660 if (llvm::count(Match, Match_MnemonicFail) == 4) {
4661 if (OriginalError == Match_MnemonicFail)
4662 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
4663 Op.getLocRange(), MatchingInlineAsm);
4664
4665 if (OriginalError == Match_Unsupported)
4666 return Error(IDLoc, "unsupported instruction", EmptyRange,
4667 MatchingInlineAsm);
4668
4669 assert(OriginalError == Match_InvalidOperand && "Unexpected error");
4670 // Recover location info for the operand if we know which was the problem.
4671 if (ErrorInfo != ~0ULL) {
4672 if (ErrorInfo >= Operands.size())
4673 return Error(IDLoc, "too few operands for instruction", EmptyRange,
4674 MatchingInlineAsm);
4675
4676 X86Operand &Operand = (X86Operand &)*Operands[ErrorInfo];
4677 if (Operand.getStartLoc().isValid()) {
4678 SMRange OperandRange = Operand.getLocRange();
4679 return Error(Operand.getStartLoc(), "invalid operand for instruction",
4680 OperandRange, MatchingInlineAsm);
4681 }
4682 }
4683
4684 return Error(IDLoc, "invalid operand for instruction", EmptyRange,
4685 MatchingInlineAsm);
4686 }
4687
4688 // If one instruction matched as unsupported, report this as unsupported.
4689 if (llvm::count(Match, Match_Unsupported) == 1) {
4690 return Error(IDLoc, "unsupported instruction", EmptyRange,
4691 MatchingInlineAsm);
4692 }
4693
4694 // If one instruction matched with a missing feature, report this as a
4695 // missing feature.
4696 if (llvm::count(Match, Match_MissingFeature) == 1) {
4697 ErrorInfo = Match_MissingFeature;
4698 return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeatures,
4699 MatchingInlineAsm);
4700 }
4701
4702 // If one instruction matched with an invalid operand, report this as an
4703 // operand failure.
4704 if (llvm::count(Match, Match_InvalidOperand) == 1) {
4705 return Error(IDLoc, "invalid operand for instruction", EmptyRange,
4706 MatchingInlineAsm);
4707 }
4708
4709 // If all of these were an outright failure, report it in a useless way.
4710 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
4711 EmptyRange, MatchingInlineAsm);
4712 return true;
4713}
4714
4715bool X86AsmParser::matchAndEmitIntelInstruction(
4716 SMLoc IDLoc, unsigned &Opcode, MCInst &Inst, OperandVector &Operands,
4717 MCStreamer &Out, uint64_t &ErrorInfo, bool MatchingInlineAsm) {
4718 X86Operand &Op = static_cast<X86Operand &>(*Operands[0]);
4719 SMRange EmptyRange;
4720 // In 16-bit mode, if data32 is specified, temporarily switch to 32-bit mode
4721 // when matching the instruction. The mode must be restored before the
4722 // instruction is emitted, or the 32-bit form loses its 0x66 prefix.
4723 const bool ForcedData32 = ForcedDataPrefix == X86::Is32Bit;
4724 auto RestoreMode = [&] {
4725 if (ForcedData32) {
4726 SwitchMode(X86::Is16Bit);
4727 ForcedDataPrefix = 0;
4728 }
4729 };
4730 if (ForcedData32)
4731 SwitchMode(X86::Is32Bit);
4732 // Find one unsized memory operand, if present.
4733 X86Operand *UnsizedMemOp = nullptr;
4734 for (const auto &Op : Operands) {
4735 X86Operand *X86Op = static_cast<X86Operand *>(Op.get());
4736 if (X86Op->isMemUnsized()) {
4737 UnsizedMemOp = X86Op;
4738 // Have we found an unqualified memory operand,
4739 // break. IA allows only one memory operand.
4740 break;
4741 }
4742 }
4743
4744 // Allow some instructions to have implicitly pointer-sized operands. This is
4745 // compatible with gas.
4746 StringRef Mnemonic = (static_cast<X86Operand &>(*Operands[0])).getToken();
4747 if (UnsizedMemOp) {
4748 static const char *const PtrSizedInstrs[] = {"call", "jmp", "push", "pop"};
4749 for (const char *Instr : PtrSizedInstrs) {
4750 if (Mnemonic == Instr) {
4751 UnsizedMemOp->Mem.Size = getPointerWidth();
4752 break;
4753 }
4754 }
4755 }
4756
4757 SmallVector<unsigned, 8> Match;
4758 FeatureBitset ErrorInfoMissingFeatures;
4759 FeatureBitset MissingFeatures;
4760 StringRef Base = (static_cast<X86Operand &>(*Operands[0])).getToken();
4761
4762 // If unsized push has immediate operand we should default the default pointer
4763 // size for the size.
4764 if (Mnemonic == "push" && Operands.size() == 2) {
4765 auto *X86Op = static_cast<X86Operand *>(Operands[1].get());
4766 if (X86Op->isImm()) {
4767 // If it's not a constant fall through and let remainder take care of it.
4768 const auto *CE = dyn_cast<MCConstantExpr>(X86Op->getImm());
4769 unsigned Size = getPointerWidth();
4770 if (CE &&
4771 (isIntN(Size, CE->getValue()) || isUIntN(Size, CE->getValue()))) {
4772 SmallString<16> Tmp;
4773 Tmp += Base;
4774 Tmp += (is64BitMode())
4775 ? "q"
4776 : (is32BitMode()) ? "l" : (is16BitMode()) ? "w" : " ";
4777 Op.setTokenValue(Tmp);
4778 // Do match in ATT mode to allow explicit suffix usage.
4779 Match.push_back(MatchInstruction(Operands, Inst, ErrorInfo,
4780 MissingFeatures, MatchingInlineAsm,
4781 false /*isParsingIntelSyntax()*/));
4782 Op.setTokenValue(Base);
4783 }
4784 }
4785 }
4786
4787 // If an unsized memory operand is present, try to match with each memory
4788 // operand size. In Intel assembly, the size is not part of the instruction
4789 // mnemonic.
4790 if (UnsizedMemOp && UnsizedMemOp->isMemUnsized()) {
4791 static const unsigned MopSizes[] = {8, 16, 32, 64, 80, 128, 256, 512};
4792 for (unsigned Size : MopSizes) {
4793 UnsizedMemOp->Mem.Size = Size;
4794 uint64_t ErrorInfoIgnore;
4795 unsigned LastOpcode = Inst.getOpcode();
4796 unsigned M = MatchInstruction(Operands, Inst, ErrorInfoIgnore,
4797 MissingFeatures, MatchingInlineAsm,
4798 isParsingIntelSyntax());
4799 if (Match.empty() || LastOpcode != Inst.getOpcode())
4800 Match.push_back(M);
4801
4802 // If this returned as a missing feature failure, remember that.
4803 if (Match.back() == Match_MissingFeature)
4804 ErrorInfoMissingFeatures = MissingFeatures;
4805 }
4806
4807 // Restore the size of the unsized memory operand if we modified it.
4808 UnsizedMemOp->Mem.Size = 0;
4809 }
4810
4811 // If we haven't matched anything yet, this is not a basic integer or FPU
4812 // operation. There shouldn't be any ambiguity in our mnemonic table, so try
4813 // matching with the unsized operand.
4814 if (Match.empty()) {
4815 Match.push_back(MatchInstruction(
4816 Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm,
4817 isParsingIntelSyntax()));
4818 // If this returned as a missing feature failure, remember that.
4819 if (Match.back() == Match_MissingFeature)
4820 ErrorInfoMissingFeatures = MissingFeatures;
4821 }
4822
4823 // Restore the size of the unsized memory operand if we modified it.
4824 if (UnsizedMemOp)
4825 UnsizedMemOp->Mem.Size = 0;
4826
4827 // If it's a bad mnemonic, all results will be the same.
4828 if (Match.back() == Match_MnemonicFail) {
4829 RestoreMode();
4830 return Error(IDLoc, "invalid instruction mnemonic '" + Mnemonic + "'",
4831 Op.getLocRange(), MatchingInlineAsm);
4832 }
4833
4834 unsigned NumSuccessfulMatches = llvm::count(Match, Match_Success);
4835
4836 // If matching was ambiguous and we had size information from the frontend,
4837 // try again with that. This handles cases like "movxz eax, m8/m16".
4838 if (UnsizedMemOp && NumSuccessfulMatches > 1 &&
4839 UnsizedMemOp->getMemFrontendSize()) {
4840 UnsizedMemOp->Mem.Size = UnsizedMemOp->getMemFrontendSize();
4841 unsigned M = MatchInstruction(
4842 Operands, Inst, ErrorInfo, MissingFeatures, MatchingInlineAsm,
4843 isParsingIntelSyntax());
4844 if (M == Match_Success)
4845 NumSuccessfulMatches = 1;
4846
4847 // Add a rewrite that encodes the size information we used from the
4848 // frontend.
4849 InstInfo->AsmRewrites->emplace_back(
4850 AOK_SizeDirective, UnsizedMemOp->getStartLoc(),
4851 /*Len=*/0, UnsizedMemOp->getMemFrontendSize());
4852 }
4853
4854 // Matching is done, so drop back to 16-bit before anything is emitted.
4855 RestoreMode();
4856
4857 // If exactly one matched, then we treat that as a successful match (and the
4858 // instruction will already have been filled in correctly, since the failing
4859 // matches won't have modified it).
4860 if (NumSuccessfulMatches == 1) {
4861 if (!MatchingInlineAsm && validateInstruction(Inst, Operands))
4862 return true;
4863 // Some instructions need post-processing to, for example, tweak which
4864 // encoding is selected. Loop on it while changes happen so the individual
4865 // transformations can chain off each other.
4866 if (!MatchingInlineAsm)
4867 while (processInstruction(Inst, Operands))
4868 ;
4869 Inst.setLoc(IDLoc);
4870 if (!MatchingInlineAsm)
4871 emitInstruction(Inst, Operands, Out);
4872 Opcode = Inst.getOpcode();
4873 return false;
4874 } else if (NumSuccessfulMatches > 1) {
4875 assert(UnsizedMemOp &&
4876 "multiple matches only possible with unsized memory operands");
4877 return Error(UnsizedMemOp->getStartLoc(),
4878 "ambiguous operand size for instruction '" + Mnemonic + "\'",
4879 UnsizedMemOp->getLocRange());
4880 }
4881
4882 // If one instruction matched as unsupported, report this as unsupported.
4883 if (llvm::count(Match, Match_Unsupported) == 1) {
4884 return Error(IDLoc, "unsupported instruction", EmptyRange,
4885 MatchingInlineAsm);
4886 }
4887
4888 // If one instruction matched with a missing feature, report this as a
4889 // missing feature.
4890 if (llvm::count(Match, Match_MissingFeature) == 1) {
4891 ErrorInfo = Match_MissingFeature;
4892 return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeatures,
4893 MatchingInlineAsm);
4894 }
4895
4896 // If one instruction matched with an invalid operand, report this as an
4897 // operand failure.
4898 if (llvm::count(Match, Match_InvalidOperand) == 1) {
4899 return Error(IDLoc, "invalid operand for instruction", EmptyRange,
4900 MatchingInlineAsm);
4901 }
4902
4903 if (llvm::count(Match, Match_InvalidImmUnsignedi4) == 1) {
4904 SMLoc ErrorLoc = ((X86Operand &)*Operands[ErrorInfo]).getStartLoc();
4905 if (ErrorLoc == SMLoc())
4906 ErrorLoc = IDLoc;
4907 return Error(ErrorLoc, "immediate must be an integer in range [0, 15]",
4908 EmptyRange, MatchingInlineAsm);
4909 }
4910
4911 if (llvm::count(Match, Match_InvalidImmUnsignedi6) == 1) {
4912 SMLoc ErrorLoc = ((X86Operand &)*Operands[ErrorInfo]).getStartLoc();
4913 if (ErrorLoc == SMLoc())
4914 ErrorLoc = IDLoc;
4915 return Error(ErrorLoc, "immediate must be an integer in range [0, 63]",
4916 EmptyRange, MatchingInlineAsm);
4917 }
4918
4919 // If all of these were an outright failure, report it in a useless way.
4920 return Error(IDLoc, "unknown instruction mnemonic", EmptyRange,
4921 MatchingInlineAsm);
4922}
4923
4924bool X86AsmParser::omitRegisterFromClobberLists(MCRegister Reg) {
4925 return getX86MCRegisterClass(X86::SEGMENT_REGRegClassID).contains(Reg);
4926}
4927
4928bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
4929 MCAsmParser &Parser = getParser();
4930 StringRef IDVal = DirectiveID.getIdentifier();
4931 if (IDVal.starts_with(".arch"))
4932 return parseDirectiveArch();
4933 if (IDVal.starts_with(".code"))
4934 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
4935 else if (IDVal.starts_with(".att_syntax")) {
4936 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4937 if (Parser.getTok().getString() == "prefix")
4938 Parser.Lex();
4939 else if (Parser.getTok().getString() == "noprefix")
4940 return Error(DirectiveID.getLoc(), "'.att_syntax noprefix' is not "
4941 "supported: registers must have a "
4942 "'%' prefix in .att_syntax");
4943 }
4944 getParser().setAssemblerDialect(0);
4945 return false;
4946 } else if (IDVal.starts_with(".intel_syntax")) {
4947 getParser().setAssemblerDialect(1);
4948 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4949 if (Parser.getTok().getString() == "noprefix")
4950 Parser.Lex();
4951 else if (Parser.getTok().getString() == "prefix")
4952 return Error(DirectiveID.getLoc(), "'.intel_syntax prefix' is not "
4953 "supported: registers must not have "
4954 "a '%' prefix in .intel_syntax");
4955 }
4956 return false;
4957 } else if (IDVal == ".nops")
4958 return parseDirectiveNops(DirectiveID.getLoc());
4959 else if (IDVal == ".even")
4960 return parseDirectiveEven(DirectiveID.getLoc());
4961 else if (IDVal == ".cv_fpo_proc")
4962 return parseDirectiveFPOProc(DirectiveID.getLoc());
4963 else if (IDVal == ".cv_fpo_setframe")
4964 return parseDirectiveFPOSetFrame(DirectiveID.getLoc());
4965 else if (IDVal == ".cv_fpo_pushreg")
4966 return parseDirectiveFPOPushReg(DirectiveID.getLoc());
4967 else if (IDVal == ".cv_fpo_stackalloc")
4968 return parseDirectiveFPOStackAlloc(DirectiveID.getLoc());
4969 else if (IDVal == ".cv_fpo_stackalign")
4970 return parseDirectiveFPOStackAlign(DirectiveID.getLoc());
4971 else if (IDVal == ".cv_fpo_endprologue")
4972 return parseDirectiveFPOEndPrologue(DirectiveID.getLoc());
4973 else if (IDVal == ".cv_fpo_endproc")
4974 return parseDirectiveFPOEndProc(DirectiveID.getLoc());
4975 else if (IDVal == ".seh_pushreg")
4976 return parseDirectiveSEHPushReg(DirectiveID.getLoc());
4977 else if (IDVal == ".seh_push2regs")
4978 return parseDirectiveSEHPush2Regs(DirectiveID.getLoc());
4979 else if (IDVal == ".seh_setframe")
4980 return parseDirectiveSEHSetFrame(DirectiveID.getLoc());
4981 else if (IDVal == ".seh_savereg")
4982 return parseDirectiveSEHSaveReg(DirectiveID.getLoc());
4983 else if (IDVal == ".seh_savexmm")
4984 return parseDirectiveSEHSaveXMM(DirectiveID.getLoc());
4985 else if (IDVal == ".seh_pushframe")
4986 return parseDirectiveSEHPushFrame(DirectiveID.getLoc());
4987 else if (Parser.isParsingMasm()) {
4988 // MASM prolog directives.
4989 if (IDVal.equals_insensitive(".pushreg")) {
4990 return ensureMasmPrologContext(DirectiveID.getLoc()) ||
4991 parseDirectiveSEHPushReg(DirectiveID.getLoc());
4992 } else if (IDVal.equals_insensitive(".push2reg")) {
4993 return ensureMasmPrologContext(DirectiveID.getLoc()) ||
4994 parseDirectiveSEHPush2Regs(DirectiveID.getLoc());
4995 } else if (IDVal.equals_insensitive(".setframe")) {
4996 return ensureMasmPrologContext(DirectiveID.getLoc()) ||
4997 parseDirectiveSEHSetFrame(DirectiveID.getLoc());
4998 } else if (IDVal.equals_insensitive(".savereg")) {
4999 return ensureMasmPrologContext(DirectiveID.getLoc()) ||
5000 parseDirectiveSEHSaveReg(DirectiveID.getLoc());
5001 } else if (IDVal.equals_insensitive(".savexmm128")) {
5002 return ensureMasmPrologContext(DirectiveID.getLoc()) ||
5003 parseDirectiveSEHSaveXMM(DirectiveID.getLoc());
5004 } else if (IDVal.equals_insensitive(".pushframe")) {
5005 return ensureMasmPrologContext(DirectiveID.getLoc()) ||
5006 parseDirectiveSEHPushFrame(DirectiveID.getLoc());
5007 }
5008 // MASM epilog directives
5009 if (IDVal.equals_insensitive(".popreg")) {
5010 return ensureMasmEpilogContext(DirectiveID.getLoc()) ||
5011 parseDirectiveSEHPushReg(DirectiveID.getLoc());
5012 } else if (IDVal.equals_insensitive(".pop2reg")) {
5013 // .pop2reg args are in the order they are popped, so reverse them to get
5014 // the order they were pushed.
5015 return ensureMasmEpilogContext(DirectiveID.getLoc()) ||
5016 parseDirectiveSEHPush2Regs(DirectiveID.getLoc(),
5017 /*SwapRegs=*/true);
5018 } else if (IDVal.equals_insensitive(".unsetframe")) {
5019 return ensureMasmEpilogContext(DirectiveID.getLoc()) ||
5020 parseDirectiveSEHSetFrame(DirectiveID.getLoc());
5021 } else if (IDVal.equals_insensitive(".restorereg")) {
5022 return ensureMasmEpilogContext(DirectiveID.getLoc()) ||
5023 parseDirectiveSEHSaveReg(DirectiveID.getLoc());
5024 } else if (IDVal.equals_insensitive(".restorexmm128")) {
5025 return ensureMasmEpilogContext(DirectiveID.getLoc()) ||
5026 parseDirectiveSEHSaveXMM(DirectiveID.getLoc());
5027 }
5028 }
5029
5030 return true;
5031}
5032
5033bool X86AsmParser::parseDirectiveArch() {
5034 // Ignore .arch for now.
5035 getParser().parseStringToEndOfStatement();
5036 return false;
5037}
5038
5039/// parseDirectiveNops
5040/// ::= .nops size[, control]
5041bool X86AsmParser::parseDirectiveNops(SMLoc L) {
5042 int64_t NumBytes = 0, Control = 0;
5043 SMLoc NumBytesLoc, ControlLoc;
5044 const MCSubtargetInfo& STI = getSTI();
5045 NumBytesLoc = getTok().getLoc();
5046 if (getParser().checkForValidSection() ||
5047 getParser().parseAbsoluteExpression(NumBytes))
5048 return true;
5049
5050 if (parseOptionalToken(AsmToken::Comma)) {
5051 ControlLoc = getTok().getLoc();
5052 if (getParser().parseAbsoluteExpression(Control))
5053 return true;
5054 }
5055 if (getParser().parseEOL())
5056 return true;
5057
5058 if (NumBytes <= 0) {
5059 Error(NumBytesLoc, "'.nops' directive with non-positive size");
5060 return false;
5061 }
5062
5063 if (Control < 0) {
5064 Error(ControlLoc, "'.nops' directive with negative NOP size");
5065 return false;
5066 }
5067
5068 /// Emit nops
5069 getParser().getStreamer().emitNops(NumBytes, Control, L, STI);
5070
5071 return false;
5072}
5073
5074/// parseDirectiveEven
5075/// ::= .even
5076bool X86AsmParser::parseDirectiveEven(SMLoc L) {
5077 if (parseEOL())
5078 return false;
5079
5080 const MCSection *Section = getStreamer().getCurrentSectionOnly();
5081 if (!Section) {
5082 getStreamer().initSections(getSTI());
5083 Section = getStreamer().getCurrentSectionOnly();
5084 }
5085 if (getContext().getAsmInfo().useCodeAlign(*Section))
5086 getStreamer().emitCodeAlignment(Align(2), getSTI(), 0);
5087 else
5088 getStreamer().emitValueToAlignment(Align(2), 0, 1, 0);
5089 return false;
5090}
5091
5092/// ParseDirectiveCode
5093/// ::= .code16 | .code32 | .code64
5094bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
5095 MCAsmParser &Parser = getParser();
5096 Code16GCC = false;
5097 if (IDVal == ".code16") {
5098 Parser.Lex();
5099 if (!is16BitMode()) {
5100 SwitchMode(X86::Is16Bit);
5101 getTargetStreamer().emitCode16();
5102 }
5103 } else if (IDVal == ".code16gcc") {
5104 // .code16gcc parses as if in 32-bit mode, but emits code in 16-bit mode.
5105 Parser.Lex();
5106 Code16GCC = true;
5107 if (!is16BitMode()) {
5108 SwitchMode(X86::Is16Bit);
5109 getTargetStreamer().emitCode16();
5110 }
5111 } else if (IDVal == ".code32") {
5112 Parser.Lex();
5113 if (!is32BitMode()) {
5114 SwitchMode(X86::Is32Bit);
5115 getTargetStreamer().emitCode32();
5116 }
5117 } else if (IDVal == ".code64") {
5118 Parser.Lex();
5119 if (!is64BitMode()) {
5120 SwitchMode(X86::Is64Bit);
5121 getTargetStreamer().emitCode64();
5122 }
5123 } else {
5124 Error(L, "unknown directive " + IDVal);
5125 return false;
5126 }
5127
5128 return false;
5129}
5130
5131// .cv_fpo_proc foo
5132bool X86AsmParser::parseDirectiveFPOProc(SMLoc L) {
5133 MCAsmParser &Parser = getParser();
5134 StringRef ProcName;
5135 int64_t ParamsSize;
5136 if (Parser.parseIdentifier(ProcName))
5137 return Parser.TokError("expected symbol name");
5138 if (Parser.parseIntToken(ParamsSize, "expected parameter byte count"))
5139 return true;
5140 if (!isUIntN(32, ParamsSize))
5141 return Parser.TokError("parameters size out of range");
5142 if (parseEOL())
5143 return true;
5144 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
5145 return getTargetStreamer().emitFPOProc(ProcSym, ParamsSize, L);
5146}
5147
5148// .cv_fpo_setframe ebp
5149bool X86AsmParser::parseDirectiveFPOSetFrame(SMLoc L) {
5150 MCRegister Reg;
5151 SMLoc DummyLoc;
5152 if (parseRegister(Reg, DummyLoc, DummyLoc) || parseEOL())
5153 return true;
5154 return getTargetStreamer().emitFPOSetFrame(Reg, L);
5155}
5156
5157// .cv_fpo_pushreg ebx
5158bool X86AsmParser::parseDirectiveFPOPushReg(SMLoc L) {
5159 MCRegister Reg;
5160 SMLoc DummyLoc;
5161 if (parseRegister(Reg, DummyLoc, DummyLoc) || parseEOL())
5162 return true;
5163 return getTargetStreamer().emitFPOPushReg(Reg, L);
5164}
5165
5166// .cv_fpo_stackalloc 20
5167bool X86AsmParser::parseDirectiveFPOStackAlloc(SMLoc L) {
5168 MCAsmParser &Parser = getParser();
5169 int64_t Offset;
5170 if (Parser.parseIntToken(Offset, "expected offset") || parseEOL())
5171 return true;
5172 return getTargetStreamer().emitFPOStackAlloc(Offset, L);
5173}
5174
5175// .cv_fpo_stackalign 8
5176bool X86AsmParser::parseDirectiveFPOStackAlign(SMLoc L) {
5177 MCAsmParser &Parser = getParser();
5178 int64_t Offset;
5179 if (Parser.parseIntToken(Offset, "expected offset") || parseEOL())
5180 return true;
5181 return getTargetStreamer().emitFPOStackAlign(Offset, L);
5182}
5183
5184// .cv_fpo_endprologue
5185bool X86AsmParser::parseDirectiveFPOEndPrologue(SMLoc L) {
5186 MCAsmParser &Parser = getParser();
5187 if (Parser.parseEOL())
5188 return true;
5189 return getTargetStreamer().emitFPOEndPrologue(L);
5190}
5191
5192// .cv_fpo_endproc
5193bool X86AsmParser::parseDirectiveFPOEndProc(SMLoc L) {
5194 MCAsmParser &Parser = getParser();
5195 if (Parser.parseEOL())
5196 return true;
5197 return getTargetStreamer().emitFPOEndProc(L);
5198}
5199
5200bool X86AsmParser::parseSEHRegisterNumber(unsigned RegClassID,
5201 MCRegister &RegNo) {
5202 SMLoc startLoc = getLexer().getLoc();
5203 const MCRegisterInfo *MRI = getContext().getRegisterInfo();
5204
5205 // Try parsing the argument as a register first.
5206 if (getLexer().getTok().isNot(AsmToken::Integer)) {
5207 SMLoc endLoc;
5208 if (parseRegister(RegNo, startLoc, endLoc))
5209 return true;
5210
5211 if (!getX86MCRegisterClass(RegClassID).contains(RegNo)) {
5212 return Error(startLoc,
5213 "register is not supported for use with this directive");
5214 }
5215 } else {
5216 // Otherwise, an integer number matching the encoding of the desired
5217 // register may appear.
5218 int64_t EncodedReg;
5219 if (getParser().parseAbsoluteExpression(EncodedReg))
5220 return true;
5221
5222 // The SEH register number is the same as the encoding register number. Map
5223 // from the encoding back to the LLVM register number.
5224 RegNo = MCRegister();
5225 for (MCPhysReg Reg : getX86MCRegisterClass(RegClassID)) {
5226 if (MRI->getEncodingValue(Reg) == EncodedReg) {
5227 RegNo = Reg;
5228 break;
5229 }
5230 }
5231 if (!RegNo) {
5232 return Error(startLoc,
5233 "incorrect register number for use with this directive");
5234 }
5235 }
5236
5237 return false;
5238}
5239
5240bool X86AsmParser::parseDirectiveSEHPushReg(SMLoc Loc) {
5241 MCRegister Reg;
5242 if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg))
5243 return true;
5244
5245 if (getLexer().isNot(AsmToken::EndOfStatement))
5246 return TokError("expected end of directive");
5247
5248 getParser().Lex();
5249 getStreamer().emitWinCFIPushReg(Reg, Loc);
5250 return false;
5251}
5252
5253bool X86AsmParser::parseDirectiveSEHPush2Regs(SMLoc Loc, bool SwapRegs) {
5254 MCRegister Reg1;
5255 if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg1))
5256 return true;
5257
5258 if (getLexer().isNot(AsmToken::Comma))
5259 return TokError("expected comma between registers");
5260 getParser().Lex();
5261
5262 MCRegister Reg2;
5263 if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg2))
5264 return true;
5265
5266 if (getLexer().isNot(AsmToken::EndOfStatement))
5267 return TokError("expected end of directive");
5268
5269 getParser().Lex();
5270 // Swap regs to go from pop order to push order.
5271 if (SwapRegs)
5272 std::swap(Reg1, Reg2);
5273 getStreamer().emitWinCFIPush2Regs(Reg1, Reg2, Loc);
5274 return false;
5275}
5276
5277bool X86AsmParser::parseDirectiveSEHSetFrame(SMLoc Loc) {
5278 MCRegister Reg;
5279 int64_t Off;
5280 if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg))
5281 return true;
5282 if (getLexer().isNot(AsmToken::Comma))
5283 return TokError("you must specify a stack pointer offset");
5284
5285 getParser().Lex();
5286 if (getParser().parseAbsoluteExpression(Off))
5287 return true;
5288
5289 if (getLexer().isNot(AsmToken::EndOfStatement))
5290 return TokError("expected end of directive");
5291
5292 getParser().Lex();
5293 getStreamer().emitWinCFISetFrame(Reg, Off, Loc);
5294 return false;
5295}
5296
5297bool X86AsmParser::parseDirectiveSEHSaveReg(SMLoc Loc) {
5298 MCRegister Reg;
5299 int64_t Off;
5300 if (parseSEHRegisterNumber(X86::GR64RegClassID, Reg))
5301 return true;
5302 if (getLexer().isNot(AsmToken::Comma))
5303 return TokError("you must specify an offset on the stack");
5304
5305 getParser().Lex();
5306 if (getParser().parseAbsoluteExpression(Off))
5307 return true;
5308
5309 if (getLexer().isNot(AsmToken::EndOfStatement))
5310 return TokError("expected end of directive");
5311
5312 getParser().Lex();
5313 getStreamer().emitWinCFISaveReg(Reg, Off, Loc);
5314 return false;
5315}
5316
5317bool X86AsmParser::parseDirectiveSEHSaveXMM(SMLoc Loc) {
5318 MCRegister Reg;
5319 int64_t Off;
5320 if (parseSEHRegisterNumber(X86::VR128XRegClassID, Reg))
5321 return true;
5322 if (getLexer().isNot(AsmToken::Comma))
5323 return TokError("you must specify an offset on the stack");
5324
5325 getParser().Lex();
5326 if (getParser().parseAbsoluteExpression(Off))
5327 return true;
5328
5329 if (getLexer().isNot(AsmToken::EndOfStatement))
5330 return TokError("expected end of directive");
5331
5332 getParser().Lex();
5333 getStreamer().emitWinCFISaveXMM(Reg, Off, Loc);
5334 return false;
5335}
5336
5337bool X86AsmParser::ensureMasmPrologContext(SMLoc Loc) {
5338 if (getStreamer().isWinCFIPrologEnded()) {
5339 return Error(Loc, "prolog directive must be used inside a prolog");
5340 }
5341 return false;
5342}
5343
5344bool X86AsmParser::ensureMasmEpilogContext(SMLoc Loc) {
5345 if (!getStreamer().isInEpilogCFI()) {
5346 return Error(Loc, "epilog directive must be used inside an epilog");
5347 }
5348 return false;
5349}
5350
5351bool X86AsmParser::parseDirectiveSEHPushFrame(SMLoc Loc) {
5352 bool Code = false;
5353 StringRef CodeID;
5354 if (getLexer().is(AsmToken::At)) {
5355 SMLoc startLoc = getLexer().getLoc();
5356 getParser().Lex();
5357 if (!getParser().parseIdentifier(CodeID)) {
5358 if (CodeID != "code")
5359 return Error(startLoc, "expected @code");
5360 Code = true;
5361 }
5362 } else if (getParser().isParsingMasm() &&
5363 getLexer().is(AsmToken::Identifier) &&
5364 getTok().getString().equals_insensitive("code")) {
5365 getParser().Lex();
5366 Code = true;
5367 }
5368
5369 if (getLexer().isNot(AsmToken::EndOfStatement))
5370 return TokError("expected end of directive");
5371
5372 getParser().Lex();
5373 getStreamer().emitWinCFIPushFrame(Code, Loc);
5374 return false;
5375}
5376
5377// Force static initialization.
5382
5383#define GET_MATCHER_IMPLEMENTATION
5384#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!")
uint64_t uint64_t
uint64_t Imm
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:480
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.
const AArch64MCOptions & getCLOpts(const MCTargetOptions &Options)
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
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
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
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