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