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