ebad87aada04e80e5e87752c3f0fdf0a4454fd65
[oota-llvm.git] / lib / Target / X86 / AsmParser / X86AsmParser.cpp
1 //===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "MCTargetDesc/X86BaseInfo.h"
11 #include "llvm/ADT/APFloat.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCExpr.h"
19 #include "llvm/MC/MCInst.h"
20 #include "llvm/MC/MCParser/MCAsmLexer.h"
21 #include "llvm/MC/MCParser/MCAsmParser.h"
22 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCTargetAsmParser.h"
28 #include "llvm/Support/SourceMgr.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/raw_ostream.h"
31
32 using namespace llvm;
33
34 namespace {
35 struct X86Operand;
36
37 static const char OpPrecedence[] = {
38   0, // IC_OR
39   1, // IC_AND
40   2, // IC_LSHIFT
41   2, // IC_RSHIFT
42   3, // IC_PLUS
43   3, // IC_MINUS
44   4, // IC_MULTIPLY
45   4, // IC_DIVIDE
46   5, // IC_RPAREN
47   6, // IC_LPAREN
48   0, // IC_IMM
49   0  // IC_REGISTER
50 };
51
52 class X86AsmParser : public MCTargetAsmParser {
53   MCSubtargetInfo &STI;
54   MCAsmParser &Parser;
55   ParseInstructionInfo *InstInfo;
56 private:
57   SMLoc consumeToken() {
58     SMLoc Result = Parser.getTok().getLoc();
59     Parser.Lex();
60     return Result;
61   }
62
63   enum InfixCalculatorTok {
64     IC_OR = 0,
65     IC_AND,
66     IC_LSHIFT,
67     IC_RSHIFT,
68     IC_PLUS,
69     IC_MINUS,
70     IC_MULTIPLY,
71     IC_DIVIDE,
72     IC_RPAREN,
73     IC_LPAREN,
74     IC_IMM,
75     IC_REGISTER
76   };
77
78   class InfixCalculator {
79     typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
80     SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
81     SmallVector<ICToken, 4> PostfixStack;
82     
83   public:
84     int64_t popOperand() {
85       assert (!PostfixStack.empty() && "Poped an empty stack!");
86       ICToken Op = PostfixStack.pop_back_val();
87       assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
88               && "Expected and immediate or register!");
89       return Op.second;
90     }
91     void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
92       assert ((Op == IC_IMM || Op == IC_REGISTER) &&
93               "Unexpected operand!");
94       PostfixStack.push_back(std::make_pair(Op, Val));
95     }
96     
97     void popOperator() { InfixOperatorStack.pop_back(); }
98     void pushOperator(InfixCalculatorTok Op) {
99       // Push the new operator if the stack is empty.
100       if (InfixOperatorStack.empty()) {
101         InfixOperatorStack.push_back(Op);
102         return;
103       }
104       
105       // Push the new operator if it has a higher precedence than the operator
106       // on the top of the stack or the operator on the top of the stack is a
107       // left parentheses.
108       unsigned Idx = InfixOperatorStack.size() - 1;
109       InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
110       if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
111         InfixOperatorStack.push_back(Op);
112         return;
113       }
114       
115       // The operator on the top of the stack has higher precedence than the
116       // new operator.
117       unsigned ParenCount = 0;
118       while (1) {
119         // Nothing to process.
120         if (InfixOperatorStack.empty())
121           break;
122         
123         Idx = InfixOperatorStack.size() - 1;
124         StackOp = InfixOperatorStack[Idx];
125         if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
126           break;
127         
128         // If we have an even parentheses count and we see a left parentheses,
129         // then stop processing.
130         if (!ParenCount && StackOp == IC_LPAREN)
131           break;
132         
133         if (StackOp == IC_RPAREN) {
134           ++ParenCount;
135           InfixOperatorStack.pop_back();
136         } else if (StackOp == IC_LPAREN) {
137           --ParenCount;
138           InfixOperatorStack.pop_back();
139         } else {
140           InfixOperatorStack.pop_back();
141           PostfixStack.push_back(std::make_pair(StackOp, 0));
142         }
143       }
144       // Push the new operator.
145       InfixOperatorStack.push_back(Op);
146     }
147     int64_t execute() {
148       // Push any remaining operators onto the postfix stack.
149       while (!InfixOperatorStack.empty()) {
150         InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
151         if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
152           PostfixStack.push_back(std::make_pair(StackOp, 0));
153       }
154       
155       if (PostfixStack.empty())
156         return 0;
157       
158       SmallVector<ICToken, 16> OperandStack;
159       for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
160         ICToken Op = PostfixStack[i];
161         if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
162           OperandStack.push_back(Op);
163         } else {
164           assert (OperandStack.size() > 1 && "Too few operands.");
165           int64_t Val;
166           ICToken Op2 = OperandStack.pop_back_val();
167           ICToken Op1 = OperandStack.pop_back_val();
168           switch (Op.first) {
169           default:
170             report_fatal_error("Unexpected operator!");
171             break;
172           case IC_PLUS:
173             Val = Op1.second + Op2.second;
174             OperandStack.push_back(std::make_pair(IC_IMM, Val));
175             break;
176           case IC_MINUS:
177             Val = Op1.second - Op2.second;
178             OperandStack.push_back(std::make_pair(IC_IMM, Val));
179             break;
180           case IC_MULTIPLY:
181             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
182                     "Multiply operation with an immediate and a register!");
183             Val = Op1.second * Op2.second;
184             OperandStack.push_back(std::make_pair(IC_IMM, Val));
185             break;
186           case IC_DIVIDE:
187             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
188                     "Divide operation with an immediate and a register!");
189             assert (Op2.second != 0 && "Division by zero!");
190             Val = Op1.second / Op2.second;
191             OperandStack.push_back(std::make_pair(IC_IMM, Val));
192             break;
193           case IC_OR:
194             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
195                     "Or operation with an immediate and a register!");
196             Val = Op1.second | Op2.second;
197             OperandStack.push_back(std::make_pair(IC_IMM, Val));
198             break;
199           case IC_AND:
200             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
201                     "And operation with an immediate and a register!");
202             Val = Op1.second & Op2.second;
203             OperandStack.push_back(std::make_pair(IC_IMM, Val));
204             break;
205           case IC_LSHIFT:
206             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
207                     "Left shift operation with an immediate and a register!");
208             Val = Op1.second << Op2.second;
209             OperandStack.push_back(std::make_pair(IC_IMM, Val));
210             break;
211           case IC_RSHIFT:
212             assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
213                     "Right shift operation with an immediate and a register!");
214             Val = Op1.second >> Op2.second;
215             OperandStack.push_back(std::make_pair(IC_IMM, Val));
216             break;
217           }
218         }
219       }
220       assert (OperandStack.size() == 1 && "Expected a single result.");
221       return OperandStack.pop_back_val().second;
222     }
223   };
224
225   enum IntelExprState {
226     IES_OR,
227     IES_AND,
228     IES_LSHIFT,
229     IES_RSHIFT,
230     IES_PLUS,
231     IES_MINUS,
232     IES_MULTIPLY,
233     IES_DIVIDE,
234     IES_LBRAC,
235     IES_RBRAC,
236     IES_LPAREN,
237     IES_RPAREN,
238     IES_REGISTER,
239     IES_INTEGER,
240     IES_IDENTIFIER,
241     IES_ERROR
242   };
243
244   class IntelExprStateMachine {
245     IntelExprState State, PrevState;
246     unsigned BaseReg, IndexReg, TmpReg, Scale;
247     int64_t Imm;
248     const MCExpr *Sym;
249     StringRef SymName;
250     bool StopOnLBrac, AddImmPrefix;
251     InfixCalculator IC;
252     InlineAsmIdentifierInfo Info;
253   public:
254     IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
255       State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
256       Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac),
257       AddImmPrefix(addimmprefix) { Info.clear(); }
258     
259     unsigned getBaseReg() { return BaseReg; }
260     unsigned getIndexReg() { return IndexReg; }
261     unsigned getScale() { return Scale; }
262     const MCExpr *getSym() { return Sym; }
263     StringRef getSymName() { return SymName; }
264     int64_t getImm() { return Imm + IC.execute(); }
265     bool isValidEndState() {
266       return State == IES_RBRAC || State == IES_INTEGER;
267     }
268     bool getStopOnLBrac() { return StopOnLBrac; }
269     bool getAddImmPrefix() { return AddImmPrefix; }
270     bool hadError() { return State == IES_ERROR; }
271
272     InlineAsmIdentifierInfo &getIdentifierInfo() {
273       return Info;
274     }
275
276     void onOr() {
277       IntelExprState CurrState = State;
278       switch (State) {
279       default:
280         State = IES_ERROR;
281         break;
282       case IES_INTEGER:
283       case IES_RPAREN:
284       case IES_REGISTER:
285         State = IES_OR;
286         IC.pushOperator(IC_OR);
287         break;
288       }
289       PrevState = CurrState;
290     }
291     void onAnd() {
292       IntelExprState CurrState = State;
293       switch (State) {
294       default:
295         State = IES_ERROR;
296         break;
297       case IES_INTEGER:
298       case IES_RPAREN:
299       case IES_REGISTER:
300         State = IES_AND;
301         IC.pushOperator(IC_AND);
302         break;
303       }
304       PrevState = CurrState;
305     }
306     void onLShift() {
307       IntelExprState CurrState = State;
308       switch (State) {
309       default:
310         State = IES_ERROR;
311         break;
312       case IES_INTEGER:
313       case IES_RPAREN:
314       case IES_REGISTER:
315         State = IES_LSHIFT;
316         IC.pushOperator(IC_LSHIFT);
317         break;
318       }
319       PrevState = CurrState;
320     }
321     void onRShift() {
322       IntelExprState CurrState = State;
323       switch (State) {
324       default:
325         State = IES_ERROR;
326         break;
327       case IES_INTEGER:
328       case IES_RPAREN:
329       case IES_REGISTER:
330         State = IES_RSHIFT;
331         IC.pushOperator(IC_RSHIFT);
332         break;
333       }
334       PrevState = CurrState;
335     }
336     void onPlus() {
337       IntelExprState CurrState = State;
338       switch (State) {
339       default:
340         State = IES_ERROR;
341         break;
342       case IES_INTEGER:
343       case IES_RPAREN:
344       case IES_REGISTER:
345         State = IES_PLUS;
346         IC.pushOperator(IC_PLUS);
347         if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
348           // If we already have a BaseReg, then assume this is the IndexReg with
349           // a scale of 1.
350           if (!BaseReg) {
351             BaseReg = TmpReg;
352           } else {
353             assert (!IndexReg && "BaseReg/IndexReg already set!");
354             IndexReg = TmpReg;
355             Scale = 1;
356           }
357         }
358         break;
359       }
360       PrevState = CurrState;
361     }
362     void onMinus() {
363       IntelExprState CurrState = State;
364       switch (State) {
365       default:
366         State = IES_ERROR;
367         break;
368       case IES_PLUS:
369       case IES_MULTIPLY:
370       case IES_DIVIDE:
371       case IES_LPAREN:
372       case IES_RPAREN:
373       case IES_LBRAC:
374       case IES_RBRAC:
375       case IES_INTEGER:
376       case IES_REGISTER:
377         State = IES_MINUS;
378         // Only push the minus operator if it is not a unary operator.
379         if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
380               CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
381               CurrState == IES_LPAREN || CurrState == IES_LBRAC))
382           IC.pushOperator(IC_MINUS);
383         if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
384           // If we already have a BaseReg, then assume this is the IndexReg with
385           // a scale of 1.
386           if (!BaseReg) {
387             BaseReg = TmpReg;
388           } else {
389             assert (!IndexReg && "BaseReg/IndexReg already set!");
390             IndexReg = TmpReg;
391             Scale = 1;
392           }
393         }
394         break;
395       }
396       PrevState = CurrState;
397     }
398     void onRegister(unsigned Reg) {
399       IntelExprState CurrState = State;
400       switch (State) {
401       default:
402         State = IES_ERROR;
403         break;
404       case IES_PLUS:
405       case IES_LPAREN:
406         State = IES_REGISTER;
407         TmpReg = Reg;
408         IC.pushOperand(IC_REGISTER);
409         break;
410       case IES_MULTIPLY:
411         // Index Register - Scale * Register
412         if (PrevState == IES_INTEGER) {
413           assert (!IndexReg && "IndexReg already set!");
414           State = IES_REGISTER;
415           IndexReg = Reg;
416           // Get the scale and replace the 'Scale * Register' with '0'.
417           Scale = IC.popOperand();
418           IC.pushOperand(IC_IMM);
419           IC.popOperator();
420         } else {
421           State = IES_ERROR;
422         }
423         break;
424       }
425       PrevState = CurrState;
426     }
427     void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
428       PrevState = State;
429       switch (State) {
430       default:
431         State = IES_ERROR;
432         break;
433       case IES_PLUS:
434       case IES_MINUS:
435         State = IES_INTEGER;
436         Sym = SymRef;
437         SymName = SymRefName;
438         IC.pushOperand(IC_IMM);
439         break;
440       }
441     }
442     bool onInteger(int64_t TmpInt, StringRef &ErrMsg) {
443       IntelExprState CurrState = State;
444       switch (State) {
445       default:
446         State = IES_ERROR;
447         break;
448       case IES_PLUS:
449       case IES_MINUS:
450       case IES_OR:
451       case IES_AND:
452       case IES_LSHIFT:
453       case IES_RSHIFT:
454       case IES_DIVIDE:
455       case IES_MULTIPLY:
456       case IES_LPAREN:
457         State = IES_INTEGER;
458         if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
459           // Index Register - Register * Scale
460           assert (!IndexReg && "IndexReg already set!");
461           IndexReg = TmpReg;
462           Scale = TmpInt;
463           if(Scale != 1 && Scale != 2 && Scale != 4 && Scale != 8) {
464             ErrMsg = "scale factor in address must be 1, 2, 4 or 8";
465             return true;
466           }
467           // Get the scale and replace the 'Register * Scale' with '0'.
468           IC.popOperator();
469         } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
470                     PrevState == IES_OR || PrevState == IES_AND ||
471                     PrevState == IES_LSHIFT || PrevState == IES_RSHIFT ||
472                     PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
473                     PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
474                    CurrState == IES_MINUS) {
475           // Unary minus.  No need to pop the minus operand because it was never
476           // pushed.
477           IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
478         } else {
479           IC.pushOperand(IC_IMM, TmpInt);
480         }
481         break;
482       }
483       PrevState = CurrState;
484       return false;
485     }
486     void onStar() {
487       PrevState = State;
488       switch (State) {
489       default:
490         State = IES_ERROR;
491         break;
492       case IES_INTEGER:
493       case IES_REGISTER:
494       case IES_RPAREN:
495         State = IES_MULTIPLY;
496         IC.pushOperator(IC_MULTIPLY);
497         break;
498       }
499     }
500     void onDivide() {
501       PrevState = State;
502       switch (State) {
503       default:
504         State = IES_ERROR;
505         break;
506       case IES_INTEGER:
507       case IES_RPAREN:
508         State = IES_DIVIDE;
509         IC.pushOperator(IC_DIVIDE);
510         break;
511       }
512     }
513     void onLBrac() {
514       PrevState = State;
515       switch (State) {
516       default:
517         State = IES_ERROR;
518         break;
519       case IES_RBRAC:
520         State = IES_PLUS;
521         IC.pushOperator(IC_PLUS);
522         break;
523       }
524     }
525     void onRBrac() {
526       IntelExprState CurrState = State;
527       switch (State) {
528       default:
529         State = IES_ERROR;
530         break;
531       case IES_INTEGER:
532       case IES_REGISTER:
533       case IES_RPAREN:
534         State = IES_RBRAC;
535         if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
536           // If we already have a BaseReg, then assume this is the IndexReg with
537           // a scale of 1.
538           if (!BaseReg) {
539             BaseReg = TmpReg;
540           } else {
541             assert (!IndexReg && "BaseReg/IndexReg already set!");
542             IndexReg = TmpReg;
543             Scale = 1;
544           }
545         }
546         break;
547       }
548       PrevState = CurrState;
549     }
550     void onLParen() {
551       IntelExprState CurrState = State;
552       switch (State) {
553       default:
554         State = IES_ERROR;
555         break;
556       case IES_PLUS:
557       case IES_MINUS:
558       case IES_OR:
559       case IES_AND:
560       case IES_LSHIFT:
561       case IES_RSHIFT:
562       case IES_MULTIPLY:
563       case IES_DIVIDE:
564       case IES_LPAREN:
565         // FIXME: We don't handle this type of unary minus, yet.
566         if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
567             PrevState == IES_OR || PrevState == IES_AND ||
568             PrevState == IES_LSHIFT || PrevState == IES_RSHIFT ||
569             PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
570             PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
571             CurrState == IES_MINUS) {
572           State = IES_ERROR;
573           break;
574         }
575         State = IES_LPAREN;
576         IC.pushOperator(IC_LPAREN);
577         break;
578       }
579       PrevState = CurrState;
580     }
581     void onRParen() {
582       PrevState = State;
583       switch (State) {
584       default:
585         State = IES_ERROR;
586         break;
587       case IES_INTEGER:
588       case IES_REGISTER:
589       case IES_RPAREN:
590         State = IES_RPAREN;
591         IC.pushOperator(IC_RPAREN);
592         break;
593       }
594     }
595   };
596
597   MCAsmParser &getParser() const { return Parser; }
598
599   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
600
601   bool Error(SMLoc L, const Twine &Msg,
602              ArrayRef<SMRange> Ranges = None,
603              bool MatchingInlineAsm = false) {
604     if (MatchingInlineAsm) return true;
605     return Parser.Error(L, Msg, Ranges);
606   }
607
608   X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
609     Error(Loc, Msg);
610     return 0;
611   }
612
613   X86Operand *DefaultMemSIOperand(SMLoc Loc);
614   X86Operand *DefaultMemDIOperand(SMLoc Loc);
615   X86Operand *ParseOperand();
616   X86Operand *ParseATTOperand();
617   X86Operand *ParseIntelOperand();
618   X86Operand *ParseIntelOffsetOfOperator();
619   bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
620   X86Operand *ParseIntelOperator(unsigned OpKind);
621   X86Operand *ParseIntelSegmentOverride(unsigned SegReg, SMLoc Start, unsigned Size);
622   X86Operand *ParseIntelMemOperand(int64_t ImmDisp, SMLoc StartLoc,
623                                    unsigned Size);
624   bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
625   X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
626                                        int64_t ImmDisp, unsigned Size);
627   bool ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
628                             InlineAsmIdentifierInfo &Info,
629                             bool IsUnevaluatedOperand, SMLoc &End);
630
631   X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
632
633   X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
634                                     unsigned BaseReg, unsigned IndexReg,
635                                     unsigned Scale, SMLoc Start, SMLoc End,
636                                     unsigned Size, StringRef Identifier,
637                                     InlineAsmIdentifierInfo &Info);
638
639   bool ParseDirectiveWord(unsigned Size, SMLoc L);
640   bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
641
642   bool processInstruction(MCInst &Inst,
643                           const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
644
645   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
646                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
647                                MCStreamer &Out, unsigned &ErrorInfo,
648                                bool MatchingInlineAsm);
649
650   /// doSrcDstMatch - Returns true if operands are matching in their
651   /// word size (%si and %di, %esi and %edi, etc.). Order depends on
652   /// the parsing mode (Intel vs. AT&T).
653   bool doSrcDstMatch(X86Operand &Op1, X86Operand &Op2);
654
655   bool is64BitMode() const {
656     // FIXME: Can tablegen auto-generate this?
657     return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
658   }
659   bool is32BitMode() const {
660     // FIXME: Can tablegen auto-generate this?
661     return (STI.getFeatureBits() & X86::Mode32Bit) != 0;
662   }
663   bool is16BitMode() const {
664     // FIXME: Can tablegen auto-generate this?
665     return (STI.getFeatureBits() & X86::Mode16Bit) != 0;
666   }
667   void SwitchMode(uint64_t mode) {
668     uint64_t oldMode = STI.getFeatureBits() &
669         (X86::Mode64Bit | X86::Mode32Bit | X86::Mode16Bit);
670     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(oldMode | mode));
671     setAvailableFeatures(FB);
672     assert(mode == (STI.getFeatureBits() &
673                     (X86::Mode64Bit | X86::Mode32Bit | X86::Mode16Bit)));
674   }
675
676   bool isParsingIntelSyntax() {
677     return getParser().getAssemblerDialect();
678   }
679
680   /// @name Auto-generated Matcher Functions
681   /// {
682
683 #define GET_ASSEMBLER_HEADER
684 #include "X86GenAsmMatcher.inc"
685
686   /// }
687
688 public:
689   X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
690                const MCInstrInfo &MII)
691       : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
692
693     // Initialize the set of available features.
694     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
695   }
696   virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
697
698   virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
699                                 SMLoc NameLoc,
700                                 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
701
702   virtual bool ParseDirective(AsmToken DirectiveID);
703 };
704 } // end anonymous namespace
705
706 /// @name Auto-generated Match Functions
707 /// {
708
709 static unsigned MatchRegisterName(StringRef Name);
710
711 /// }
712
713 static bool isImmSExti16i8Value(uint64_t Value) {
714   return ((                                  Value <= 0x000000000000007FULL)||
715           (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
716           (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
717 }
718
719 static bool isImmSExti32i8Value(uint64_t Value) {
720   return ((                                  Value <= 0x000000000000007FULL)||
721           (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
722           (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
723 }
724
725 static bool isImmZExtu32u8Value(uint64_t Value) {
726     return (Value <= 0x00000000000000FFULL);
727 }
728
729 static bool isImmSExti64i8Value(uint64_t Value) {
730   return ((                                  Value <= 0x000000000000007FULL)||
731           (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
732 }
733
734 static bool isImmSExti64i32Value(uint64_t Value) {
735   return ((                                  Value <= 0x000000007FFFFFFFULL)||
736           (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
737 }
738 namespace {
739
740 /// X86Operand - Instances of this class represent a parsed X86 machine
741 /// instruction.
742 struct X86Operand : public MCParsedAsmOperand {
743   enum KindTy {
744     Token,
745     Register,
746     Immediate,
747     Memory
748   } Kind;
749
750   SMLoc StartLoc, EndLoc;
751   SMLoc OffsetOfLoc;
752   StringRef SymName;
753   void *OpDecl;
754   bool AddressOf;
755
756   struct TokOp {
757     const char *Data;
758     unsigned Length;
759   };
760
761   struct RegOp {
762     unsigned RegNo;
763   };
764
765   struct ImmOp {
766     const MCExpr *Val;
767   };
768
769   struct MemOp {
770     unsigned SegReg;
771     const MCExpr *Disp;
772     unsigned BaseReg;
773     unsigned IndexReg;
774     unsigned Scale;
775     unsigned Size;
776   };
777
778   union {
779     struct TokOp Tok;
780     struct RegOp Reg;
781     struct ImmOp Imm;
782     struct MemOp Mem;
783   };
784
785   X86Operand(KindTy K, SMLoc Start, SMLoc End)
786     : Kind(K), StartLoc(Start), EndLoc(End) {}
787
788   StringRef getSymName() { return SymName; }
789   void *getOpDecl() { return OpDecl; }
790
791   /// getStartLoc - Get the location of the first token of this operand.
792   SMLoc getStartLoc() const { return StartLoc; }
793   /// getEndLoc - Get the location of the last token of this operand.
794   SMLoc getEndLoc() const { return EndLoc; }
795   /// getLocRange - Get the range between the first and last token of this
796   /// operand.
797   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
798   /// getOffsetOfLoc - Get the location of the offset operator.
799   SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
800
801   virtual void print(raw_ostream &OS) const {}
802
803   StringRef getToken() const {
804     assert(Kind == Token && "Invalid access!");
805     return StringRef(Tok.Data, Tok.Length);
806   }
807   void setTokenValue(StringRef Value) {
808     assert(Kind == Token && "Invalid access!");
809     Tok.Data = Value.data();
810     Tok.Length = Value.size();
811   }
812
813   unsigned getReg() const {
814     assert(Kind == Register && "Invalid access!");
815     return Reg.RegNo;
816   }
817
818   const MCExpr *getImm() const {
819     assert(Kind == Immediate && "Invalid access!");
820     return Imm.Val;
821   }
822
823   const MCExpr *getMemDisp() const {
824     assert(Kind == Memory && "Invalid access!");
825     return Mem.Disp;
826   }
827   unsigned getMemSegReg() const {
828     assert(Kind == Memory && "Invalid access!");
829     return Mem.SegReg;
830   }
831   unsigned getMemBaseReg() const {
832     assert(Kind == Memory && "Invalid access!");
833     return Mem.BaseReg;
834   }
835   unsigned getMemIndexReg() const {
836     assert(Kind == Memory && "Invalid access!");
837     return Mem.IndexReg;
838   }
839   unsigned getMemScale() const {
840     assert(Kind == Memory && "Invalid access!");
841     return Mem.Scale;
842   }
843
844   bool isToken() const {return Kind == Token; }
845
846   bool isImm() const { return Kind == Immediate; }
847
848   bool isImmSExti16i8() const {
849     if (!isImm())
850       return false;
851
852     // If this isn't a constant expr, just assume it fits and let relaxation
853     // handle it.
854     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
855     if (!CE)
856       return true;
857
858     // Otherwise, check the value is in a range that makes sense for this
859     // extension.
860     return isImmSExti16i8Value(CE->getValue());
861   }
862   bool isImmSExti32i8() const {
863     if (!isImm())
864       return false;
865
866     // If this isn't a constant expr, just assume it fits and let relaxation
867     // handle it.
868     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
869     if (!CE)
870       return true;
871
872     // Otherwise, check the value is in a range that makes sense for this
873     // extension.
874     return isImmSExti32i8Value(CE->getValue());
875   }
876   bool isImmZExtu32u8() const {
877     if (!isImm())
878       return false;
879
880     // If this isn't a constant expr, just assume it fits and let relaxation
881     // handle it.
882     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
883     if (!CE)
884       return true;
885
886     // Otherwise, check the value is in a range that makes sense for this
887     // extension.
888     return isImmZExtu32u8Value(CE->getValue());
889   }
890   bool isImmSExti64i8() const {
891     if (!isImm())
892       return false;
893
894     // If this isn't a constant expr, just assume it fits and let relaxation
895     // handle it.
896     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
897     if (!CE)
898       return true;
899
900     // Otherwise, check the value is in a range that makes sense for this
901     // extension.
902     return isImmSExti64i8Value(CE->getValue());
903   }
904   bool isImmSExti64i32() const {
905     if (!isImm())
906       return false;
907
908     // If this isn't a constant expr, just assume it fits and let relaxation
909     // handle it.
910     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
911     if (!CE)
912       return true;
913
914     // Otherwise, check the value is in a range that makes sense for this
915     // extension.
916     return isImmSExti64i32Value(CE->getValue());
917   }
918
919   bool isOffsetOf() const {
920     return OffsetOfLoc.getPointer();
921   }
922
923   bool needAddressOf() const {
924     return AddressOf;
925   }
926
927   bool isMem() const { return Kind == Memory; }
928   bool isMem8() const {
929     return Kind == Memory && (!Mem.Size || Mem.Size == 8);
930   }
931   bool isMem16() const {
932     return Kind == Memory && (!Mem.Size || Mem.Size == 16);
933   }
934   bool isMem32() const {
935     return Kind == Memory && (!Mem.Size || Mem.Size == 32);
936   }
937   bool isMem64() const {
938     return Kind == Memory && (!Mem.Size || Mem.Size == 64);
939   }
940   bool isMem80() const {
941     return Kind == Memory && (!Mem.Size || Mem.Size == 80);
942   }
943   bool isMem128() const {
944     return Kind == Memory && (!Mem.Size || Mem.Size == 128);
945   }
946   bool isMem256() const {
947     return Kind == Memory && (!Mem.Size || Mem.Size == 256);
948   }
949   bool isMem512() const {
950     return Kind == Memory && (!Mem.Size || Mem.Size == 512);
951   }
952
953   bool isMemVX32() const {
954     return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
955       getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
956   }
957   bool isMemVY32() const {
958     return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
959       getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
960   }
961   bool isMemVX64() const {
962     return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
963       getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
964   }
965   bool isMemVY64() const {
966     return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
967       getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
968   }
969   bool isMemVZ32() const {
970     return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
971       getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
972   }
973   bool isMemVZ64() const {
974     return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
975       getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
976   }
977
978   bool isAbsMem() const {
979     return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
980       !getMemIndexReg() && getMemScale() == 1;
981   }
982
983   bool isSrcIdx() const {
984     return !getMemIndexReg() && getMemScale() == 1 &&
985       (getMemBaseReg() == X86::RSI || getMemBaseReg() == X86::ESI ||
986        getMemBaseReg() == X86::SI) && isa<MCConstantExpr>(getMemDisp()) &&
987       cast<MCConstantExpr>(getMemDisp())->getValue() == 0;
988   }
989   bool isSrcIdx8() const {
990     return isMem8() && isSrcIdx();
991   }
992   bool isSrcIdx16() const {
993     return isMem16() && isSrcIdx();
994   }
995   bool isSrcIdx32() const {
996     return isMem32() && isSrcIdx();
997   }
998   bool isSrcIdx64() const {
999     return isMem64() && isSrcIdx();
1000   }
1001
1002   bool isDstIdx() const {
1003     return !getMemIndexReg() && getMemScale() == 1 &&
1004       (getMemSegReg() == 0 || getMemSegReg() == X86::ES) &&
1005       (getMemBaseReg() == X86::RDI || getMemBaseReg() == X86::EDI ||
1006        getMemBaseReg() == X86::DI) && isa<MCConstantExpr>(getMemDisp()) &&
1007       cast<MCConstantExpr>(getMemDisp())->getValue() == 0;
1008   }
1009   bool isDstIdx8() const {
1010     return isMem8() && isDstIdx();
1011   }
1012   bool isDstIdx16() const {
1013     return isMem16() && isDstIdx();
1014   }
1015   bool isDstIdx32() const {
1016     return isMem32() && isDstIdx();
1017   }
1018   bool isDstIdx64() const {
1019     return isMem64() && isDstIdx();
1020   }
1021
1022   bool isMemOffs8() const {
1023     return Kind == Memory && !getMemBaseReg() &&
1024       !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 8);
1025   }
1026   bool isMemOffs16() const {
1027     return Kind == Memory && !getMemBaseReg() &&
1028       !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 16);
1029   }
1030   bool isMemOffs32() const {
1031     return Kind == Memory && !getMemBaseReg() &&
1032       !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 32);
1033   }
1034   bool isMemOffs64() const {
1035     return Kind == Memory && !getMemBaseReg() &&
1036       !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 64);
1037   }
1038
1039   bool isReg() const { return Kind == Register; }
1040
1041   bool isGR32orGR64() const {
1042     return Kind == Register &&
1043       (X86MCRegisterClasses[X86::GR32RegClassID].contains(getReg()) ||
1044       X86MCRegisterClasses[X86::GR64RegClassID].contains(getReg()));
1045   }
1046
1047   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1048     // Add as immediates when possible.
1049     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1050       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1051     else
1052       Inst.addOperand(MCOperand::CreateExpr(Expr));
1053   }
1054
1055   void addRegOperands(MCInst &Inst, unsigned N) const {
1056     assert(N == 1 && "Invalid number of operands!");
1057     Inst.addOperand(MCOperand::CreateReg(getReg()));
1058   }
1059
1060   static unsigned getGR32FromGR64(unsigned RegNo) {
1061     switch (RegNo) {
1062     default: llvm_unreachable("Unexpected register");
1063     case X86::RAX: return X86::EAX;
1064     case X86::RCX: return X86::ECX;
1065     case X86::RDX: return X86::EDX;
1066     case X86::RBX: return X86::EBX;
1067     case X86::RBP: return X86::EBP;
1068     case X86::RSP: return X86::ESP;
1069     case X86::RSI: return X86::ESI;
1070     case X86::RDI: return X86::EDI;
1071     case X86::R8: return X86::R8D;
1072     case X86::R9: return X86::R9D;
1073     case X86::R10: return X86::R10D;
1074     case X86::R11: return X86::R11D;
1075     case X86::R12: return X86::R12D;
1076     case X86::R13: return X86::R13D;
1077     case X86::R14: return X86::R14D;
1078     case X86::R15: return X86::R15D;
1079     case X86::RIP: return X86::EIP;
1080     }
1081   }
1082
1083   void addGR32orGR64Operands(MCInst &Inst, unsigned N) const {
1084     assert(N == 1 && "Invalid number of operands!");
1085     unsigned RegNo = getReg();
1086     if (X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo))
1087       RegNo = getGR32FromGR64(RegNo);
1088     Inst.addOperand(MCOperand::CreateReg(RegNo));
1089   }
1090
1091   void addImmOperands(MCInst &Inst, unsigned N) const {
1092     assert(N == 1 && "Invalid number of operands!");
1093     addExpr(Inst, getImm());
1094   }
1095
1096   void addMemOperands(MCInst &Inst, unsigned N) const {
1097     assert((N == 5) && "Invalid number of operands!");
1098     Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
1099     Inst.addOperand(MCOperand::CreateImm(getMemScale()));
1100     Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
1101     addExpr(Inst, getMemDisp());
1102     Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
1103   }
1104
1105   void addAbsMemOperands(MCInst &Inst, unsigned N) const {
1106     assert((N == 1) && "Invalid number of operands!");
1107     // Add as immediates when possible.
1108     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
1109       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1110     else
1111       Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
1112   }
1113
1114   void addSrcIdxOperands(MCInst &Inst, unsigned N) const {
1115     assert((N == 2) && "Invalid number of operands!");
1116     Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
1117     Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
1118   }
1119   void addDstIdxOperands(MCInst &Inst, unsigned N) const {
1120     assert((N == 1) && "Invalid number of operands!");
1121     Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
1122   }
1123
1124   void addMemOffsOperands(MCInst &Inst, unsigned N) const {
1125     assert((N == 2) && "Invalid number of operands!");
1126     // Add as immediates when possible.
1127     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
1128       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1129     else
1130       Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
1131     Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
1132   }
1133
1134   static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
1135     SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
1136     X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
1137     Res->Tok.Data = Str.data();
1138     Res->Tok.Length = Str.size();
1139     return Res;
1140   }
1141
1142   static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
1143                                bool AddressOf = false,
1144                                SMLoc OffsetOfLoc = SMLoc(),
1145                                StringRef SymName = StringRef(),
1146                                void *OpDecl = 0) {
1147     X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
1148     Res->Reg.RegNo = RegNo;
1149     Res->AddressOf = AddressOf;
1150     Res->OffsetOfLoc = OffsetOfLoc;
1151     Res->SymName = SymName;
1152     Res->OpDecl = OpDecl;
1153     return Res;
1154   }
1155
1156   static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
1157     X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
1158     Res->Imm.Val = Val;
1159     return Res;
1160   }
1161
1162   /// Create an absolute memory operand.
1163   static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
1164                                unsigned Size = 0, StringRef SymName = StringRef(),
1165                                void *OpDecl = 0) {
1166     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1167     Res->Mem.SegReg   = 0;
1168     Res->Mem.Disp     = Disp;
1169     Res->Mem.BaseReg  = 0;
1170     Res->Mem.IndexReg = 0;
1171     Res->Mem.Scale    = 1;
1172     Res->Mem.Size     = Size;
1173     Res->SymName      = SymName;
1174     Res->OpDecl       = OpDecl;
1175     Res->AddressOf    = false;
1176     return Res;
1177   }
1178
1179   /// Create a generalized memory operand.
1180   static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
1181                                unsigned BaseReg, unsigned IndexReg,
1182                                unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
1183                                unsigned Size = 0,
1184                                StringRef SymName = StringRef(),
1185                                void *OpDecl = 0) {
1186     // We should never just have a displacement, that should be parsed as an
1187     // absolute memory operand.
1188     assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
1189
1190     // The scale should always be one of {1,2,4,8}.
1191     assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
1192            "Invalid scale!");
1193     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1194     Res->Mem.SegReg   = SegReg;
1195     Res->Mem.Disp     = Disp;
1196     Res->Mem.BaseReg  = BaseReg;
1197     Res->Mem.IndexReg = IndexReg;
1198     Res->Mem.Scale    = Scale;
1199     Res->Mem.Size     = Size;
1200     Res->SymName      = SymName;
1201     Res->OpDecl       = OpDecl;
1202     Res->AddressOf    = false;
1203     return Res;
1204   }
1205 };
1206
1207 } // end anonymous namespace.
1208
1209 static bool CheckBaseRegAndIndexReg(unsigned BaseReg, unsigned IndexReg,
1210                                     StringRef &ErrMsg) {
1211   // If we have both a base register and an index register make sure they are
1212   // both 64-bit or 32-bit registers.
1213   // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1214   if (BaseReg != 0 && IndexReg != 0) {
1215     if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1216         (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1217          X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1218         IndexReg != X86::RIZ) {
1219       ErrMsg = "base register is 64-bit, but index register is not";
1220       return true;
1221     }
1222     if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1223         (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1224          X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1225         IndexReg != X86::EIZ){
1226       ErrMsg = "base register is 32-bit, but index register is not";
1227       return true;
1228     }
1229     if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg)) {
1230       if (X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) ||
1231           X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) {
1232         ErrMsg = "base register is 16-bit, but index register is not";
1233         return true;
1234       }
1235       if (((BaseReg == X86::BX || BaseReg == X86::BP) &&
1236            IndexReg != X86::SI && IndexReg != X86::DI) ||
1237           ((BaseReg == X86::SI || BaseReg == X86::DI) &&
1238            IndexReg != X86::BX && IndexReg != X86::BP)) {
1239         ErrMsg = "invalid 16-bit base/index register combination";
1240         return true;
1241       }
1242     }
1243   }
1244   return false;
1245 }
1246
1247 bool X86AsmParser::doSrcDstMatch(X86Operand &Op1, X86Operand &Op2)
1248 {
1249   // Return true and let a normal complaint about bogus operands happen.
1250   if (!Op1.isMem() || !Op2.isMem())
1251     return true;
1252
1253   // Actually these might be the other way round if Intel syntax is
1254   // being used. It doesn't matter.
1255   unsigned diReg = Op1.Mem.BaseReg;
1256   unsigned siReg = Op2.Mem.BaseReg;
1257
1258   if (X86MCRegisterClasses[X86::GR16RegClassID].contains(siReg))
1259     return X86MCRegisterClasses[X86::GR16RegClassID].contains(diReg);
1260   if (X86MCRegisterClasses[X86::GR32RegClassID].contains(siReg))
1261     return X86MCRegisterClasses[X86::GR32RegClassID].contains(diReg);
1262   if (X86MCRegisterClasses[X86::GR64RegClassID].contains(siReg))
1263     return X86MCRegisterClasses[X86::GR64RegClassID].contains(diReg);
1264   // Again, return true and let another error happen.
1265   return true;
1266 }
1267
1268 bool X86AsmParser::ParseRegister(unsigned &RegNo,
1269                                  SMLoc &StartLoc, SMLoc &EndLoc) {
1270   RegNo = 0;
1271   const AsmToken &PercentTok = Parser.getTok();
1272   StartLoc = PercentTok.getLoc();
1273
1274   // If we encounter a %, ignore it. This code handles registers with and
1275   // without the prefix, unprefixed registers can occur in cfi directives.
1276   if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1277     Parser.Lex(); // Eat percent token.
1278
1279   const AsmToken &Tok = Parser.getTok();
1280   EndLoc = Tok.getEndLoc();
1281
1282   if (Tok.isNot(AsmToken::Identifier)) {
1283     if (isParsingIntelSyntax()) return true;
1284     return Error(StartLoc, "invalid register name",
1285                  SMRange(StartLoc, EndLoc));
1286   }
1287
1288   RegNo = MatchRegisterName(Tok.getString());
1289
1290   // If the match failed, try the register name as lowercase.
1291   if (RegNo == 0)
1292     RegNo = MatchRegisterName(Tok.getString().lower());
1293
1294   if (!is64BitMode()) {
1295     // FIXME: This should be done using Requires<Not64BitMode> and
1296     // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1297     // checked.
1298     // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1299     // REX prefix.
1300     if (RegNo == X86::RIZ ||
1301         X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1302         X86II::isX86_64NonExtLowByteReg(RegNo) ||
1303         X86II::isX86_64ExtendedReg(RegNo))
1304       return Error(StartLoc, "register %"
1305                    + Tok.getString() + " is only available in 64-bit mode",
1306                    SMRange(StartLoc, EndLoc));
1307   }
1308
1309   // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1310   if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1311     RegNo = X86::ST0;
1312     Parser.Lex(); // Eat 'st'
1313
1314     // Check to see if we have '(4)' after %st.
1315     if (getLexer().isNot(AsmToken::LParen))
1316       return false;
1317     // Lex the paren.
1318     getParser().Lex();
1319
1320     const AsmToken &IntTok = Parser.getTok();
1321     if (IntTok.isNot(AsmToken::Integer))
1322       return Error(IntTok.getLoc(), "expected stack index");
1323     switch (IntTok.getIntVal()) {
1324     case 0: RegNo = X86::ST0; break;
1325     case 1: RegNo = X86::ST1; break;
1326     case 2: RegNo = X86::ST2; break;
1327     case 3: RegNo = X86::ST3; break;
1328     case 4: RegNo = X86::ST4; break;
1329     case 5: RegNo = X86::ST5; break;
1330     case 6: RegNo = X86::ST6; break;
1331     case 7: RegNo = X86::ST7; break;
1332     default: return Error(IntTok.getLoc(), "invalid stack index");
1333     }
1334
1335     if (getParser().Lex().isNot(AsmToken::RParen))
1336       return Error(Parser.getTok().getLoc(), "expected ')'");
1337
1338     EndLoc = Parser.getTok().getEndLoc();
1339     Parser.Lex(); // Eat ')'
1340     return false;
1341   }
1342
1343   EndLoc = Parser.getTok().getEndLoc();
1344
1345   // If this is "db[0-7]", match it as an alias
1346   // for dr[0-7].
1347   if (RegNo == 0 && Tok.getString().size() == 3 &&
1348       Tok.getString().startswith("db")) {
1349     switch (Tok.getString()[2]) {
1350     case '0': RegNo = X86::DR0; break;
1351     case '1': RegNo = X86::DR1; break;
1352     case '2': RegNo = X86::DR2; break;
1353     case '3': RegNo = X86::DR3; break;
1354     case '4': RegNo = X86::DR4; break;
1355     case '5': RegNo = X86::DR5; break;
1356     case '6': RegNo = X86::DR6; break;
1357     case '7': RegNo = X86::DR7; break;
1358     }
1359
1360     if (RegNo != 0) {
1361       EndLoc = Parser.getTok().getEndLoc();
1362       Parser.Lex(); // Eat it.
1363       return false;
1364     }
1365   }
1366
1367   if (RegNo == 0) {
1368     if (isParsingIntelSyntax()) return true;
1369     return Error(StartLoc, "invalid register name",
1370                  SMRange(StartLoc, EndLoc));
1371   }
1372
1373   Parser.Lex(); // Eat identifier token.
1374   return false;
1375 }
1376
1377 X86Operand *X86AsmParser::DefaultMemSIOperand(SMLoc Loc) {
1378   unsigned basereg =
1379     is64BitMode() ? X86::RSI : (is32BitMode() ? X86::ESI : X86::SI);
1380   const MCExpr *Disp = MCConstantExpr::Create(0, getContext());
1381   return X86Operand::CreateMem(/*SegReg=*/0, Disp, /*BaseReg=*/basereg,
1382                                /*IndexReg=*/0, /*Scale=*/1, Loc, Loc, 0);
1383 }
1384
1385 X86Operand *X86AsmParser::DefaultMemDIOperand(SMLoc Loc) {
1386   unsigned basereg =
1387     is64BitMode() ? X86::RDI : (is32BitMode() ? X86::EDI : X86::DI);
1388   const MCExpr *Disp = MCConstantExpr::Create(0, getContext());
1389   return X86Operand::CreateMem(/*SegReg=*/0, Disp, /*BaseReg=*/basereg,
1390                                /*IndexReg=*/0, /*Scale=*/1, Loc, Loc, 0);
1391 }
1392
1393 X86Operand *X86AsmParser::ParseOperand() {
1394   if (isParsingIntelSyntax())
1395     return ParseIntelOperand();
1396   return ParseATTOperand();
1397 }
1398
1399 /// getIntelMemOperandSize - Return intel memory operand size.
1400 static unsigned getIntelMemOperandSize(StringRef OpStr) {
1401   unsigned Size = StringSwitch<unsigned>(OpStr)
1402     .Cases("BYTE", "byte", 8)
1403     .Cases("WORD", "word", 16)
1404     .Cases("DWORD", "dword", 32)
1405     .Cases("QWORD", "qword", 64)
1406     .Cases("XWORD", "xword", 80)
1407     .Cases("XMMWORD", "xmmword", 128)
1408     .Cases("YMMWORD", "ymmword", 256)
1409     .Cases("ZMMWORD", "zmmword", 512)
1410     .Cases("OPAQUE", "opaque", -1U) // needs to be non-zero, but doesn't matter
1411     .Default(0);
1412   return Size;
1413 }
1414
1415 X86Operand *
1416 X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1417                                     unsigned BaseReg, unsigned IndexReg,
1418                                     unsigned Scale, SMLoc Start, SMLoc End,
1419                                     unsigned Size, StringRef Identifier,
1420                                     InlineAsmIdentifierInfo &Info){
1421   if (isa<MCSymbolRefExpr>(Disp)) {
1422     // If this is not a VarDecl then assume it is a FuncDecl or some other label
1423     // reference.  We need an 'r' constraint here, so we need to create register
1424     // operand to ensure proper matching.  Just pick a GPR based on the size of
1425     // a pointer.
1426     if (!Info.IsVarDecl) {
1427       unsigned RegNo =
1428           is64BitMode() ? X86::RBX : (is32BitMode() ? X86::EBX : X86::BX);
1429       return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1430                                    SMLoc(), Identifier, Info.OpDecl);
1431     }
1432     if (!Size) {
1433       Size = Info.Type * 8; // Size is in terms of bits in this context.
1434       if (Size)
1435         InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1436                                                     /*Len=*/0, Size));
1437     }
1438   }
1439
1440   // When parsing inline assembly we set the base register to a non-zero value
1441   // if we don't know the actual value at this time.  This is necessary to
1442   // get the matching correct in some cases.
1443   BaseReg = BaseReg ? BaseReg : 1;
1444   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1445                                End, Size, Identifier, Info.OpDecl);
1446 }
1447
1448 static void
1449 RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1450                            StringRef SymName, int64_t ImmDisp,
1451                            int64_t FinalImmDisp, SMLoc &BracLoc,
1452                            SMLoc &StartInBrac, SMLoc &End) {
1453   // Remove the '[' and ']' from the IR string.
1454   AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1455   AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1456
1457   // If ImmDisp is non-zero, then we parsed a displacement before the
1458   // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1459   // If ImmDisp doesn't match the displacement computed by the state machine
1460   // then we have an additional displacement in the bracketed expression.
1461   if (ImmDisp != FinalImmDisp) {
1462     if (ImmDisp) {
1463       // We have an immediate displacement before the bracketed expression.
1464       // Adjust this to match the final immediate displacement.
1465       bool Found = false;
1466       for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1467              E = AsmRewrites->end(); I != E; ++I) {
1468         if ((*I).Loc.getPointer() > BracLoc.getPointer())
1469           continue;
1470         if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1471           assert (!Found && "ImmDisp already rewritten.");
1472           (*I).Kind = AOK_Imm;
1473           (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1474           (*I).Val = FinalImmDisp;
1475           Found = true;
1476           break;
1477         }
1478       }
1479       assert (Found && "Unable to rewrite ImmDisp.");
1480       (void)Found;
1481     } else {
1482       // We have a symbolic and an immediate displacement, but no displacement
1483       // before the bracketed expression.  Put the immediate displacement
1484       // before the bracketed expression.
1485       AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1486     }
1487   }
1488   // Remove all the ImmPrefix rewrites within the brackets.
1489   for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1490          E = AsmRewrites->end(); I != E; ++I) {
1491     if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1492       continue;
1493     if ((*I).Kind == AOK_ImmPrefix)
1494       (*I).Kind = AOK_Delete;
1495   }
1496   const char *SymLocPtr = SymName.data();
1497   // Skip everything before the symbol.        
1498   if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1499     assert(Len > 0 && "Expected a non-negative length.");
1500     AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1501   }
1502   // Skip everything after the symbol.
1503   if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1504     SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1505     assert(Len > 0 && "Expected a non-negative length.");
1506     AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1507   }
1508 }
1509
1510 bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1511   const AsmToken &Tok = Parser.getTok();
1512
1513   bool Done = false;
1514   while (!Done) {
1515     bool UpdateLocLex = true;
1516
1517     // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1518     // identifier.  Don't try an parse it as a register.
1519     if (Tok.getString().startswith("."))
1520       break;
1521     
1522     // If we're parsing an immediate expression, we don't expect a '['.
1523     if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1524       break;
1525
1526     switch (getLexer().getKind()) {
1527     default: {
1528       if (SM.isValidEndState()) {
1529         Done = true;
1530         break;
1531       }
1532       return Error(Tok.getLoc(), "unknown token in expression");
1533     }
1534     case AsmToken::EndOfStatement: {
1535       Done = true;
1536       break;
1537     }
1538     case AsmToken::Identifier: {
1539       // This could be a register or a symbolic displacement.
1540       unsigned TmpReg;
1541       const MCExpr *Val;
1542       SMLoc IdentLoc = Tok.getLoc();
1543       StringRef Identifier = Tok.getString();
1544       if(!ParseRegister(TmpReg, IdentLoc, End)) {
1545         SM.onRegister(TmpReg);
1546         UpdateLocLex = false;
1547         break;
1548       } else {
1549         if (!isParsingInlineAsm()) {
1550           if (getParser().parsePrimaryExpr(Val, End))
1551             return Error(Tok.getLoc(), "Unexpected identifier!");
1552         } else {
1553           InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1554           if (ParseIntelIdentifier(Val, Identifier, Info,
1555                                    /*Unevaluated=*/false, End))
1556             return true;
1557         }
1558         SM.onIdentifierExpr(Val, Identifier);
1559         UpdateLocLex = false;
1560         break;
1561       }
1562       return Error(Tok.getLoc(), "Unexpected identifier!");
1563     }
1564     case AsmToken::Integer: {
1565       StringRef ErrMsg;
1566       if (isParsingInlineAsm() && SM.getAddImmPrefix())
1567         InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1568                                                     Tok.getLoc()));
1569       // Look for 'b' or 'f' following an Integer as a directional label
1570       SMLoc Loc = getTok().getLoc();
1571       int64_t IntVal = getTok().getIntVal();
1572       End = consumeToken();
1573       UpdateLocLex = false;
1574       if (getLexer().getKind() == AsmToken::Identifier) {
1575         StringRef IDVal = getTok().getString();
1576         if (IDVal == "f" || IDVal == "b") {
1577           MCSymbol *Sym =
1578             getContext().GetDirectionalLocalSymbol(IntVal,
1579                                                    IDVal == "f" ? 1 : 0);
1580           MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1581           const MCExpr *Val = 
1582             MCSymbolRefExpr::Create(Sym, Variant, getContext());
1583           if (IDVal == "b" && Sym->isUndefined())
1584             return Error(Loc, "invalid reference to undefined symbol");
1585           StringRef Identifier = Sym->getName();
1586           SM.onIdentifierExpr(Val, Identifier);
1587           End = consumeToken();
1588         } else {
1589           if (SM.onInteger(IntVal, ErrMsg))
1590             return Error(Loc, ErrMsg);
1591         }
1592       } else {
1593         if (SM.onInteger(IntVal, ErrMsg))
1594           return Error(Loc, ErrMsg);
1595       }
1596       break;
1597     }
1598     case AsmToken::Plus:    SM.onPlus(); break;
1599     case AsmToken::Minus:   SM.onMinus(); break;
1600     case AsmToken::Star:    SM.onStar(); break;
1601     case AsmToken::Slash:   SM.onDivide(); break;
1602     case AsmToken::Pipe:    SM.onOr(); break;
1603     case AsmToken::Amp:     SM.onAnd(); break;
1604     case AsmToken::LessLess:
1605                             SM.onLShift(); break;
1606     case AsmToken::GreaterGreater:
1607                             SM.onRShift(); break;
1608     case AsmToken::LBrac:   SM.onLBrac(); break;
1609     case AsmToken::RBrac:   SM.onRBrac(); break;
1610     case AsmToken::LParen:  SM.onLParen(); break;
1611     case AsmToken::RParen:  SM.onRParen(); break;
1612     }
1613     if (SM.hadError())
1614       return Error(Tok.getLoc(), "unknown token in expression");
1615
1616     if (!Done && UpdateLocLex)
1617       End = consumeToken();
1618   }
1619   return false;
1620 }
1621
1622 X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1623                                                    int64_t ImmDisp,
1624                                                    unsigned Size) {
1625   const AsmToken &Tok = Parser.getTok();
1626   SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1627   if (getLexer().isNot(AsmToken::LBrac))
1628     return ErrorOperand(BracLoc, "Expected '[' token!");
1629   Parser.Lex(); // Eat '['
1630
1631   SMLoc StartInBrac = Tok.getLoc();
1632   // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ].  We
1633   // may have already parsed an immediate displacement before the bracketed
1634   // expression.
1635   IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1636   if (ParseIntelExpression(SM, End))
1637     return 0;
1638
1639   const MCExpr *Disp;
1640   if (const MCExpr *Sym = SM.getSym()) {
1641     // A symbolic displacement.
1642     Disp = Sym;
1643     if (isParsingInlineAsm())
1644       RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1645                                  ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1646                                  End);
1647   } else {
1648     // An immediate displacement only.   
1649     Disp = MCConstantExpr::Create(SM.getImm(), getContext());
1650   }
1651
1652   // Parse the dot operator (e.g., [ebx].foo.bar).
1653   if (Tok.getString().startswith(".")) {
1654     const MCExpr *NewDisp;
1655     if (ParseIntelDotOperator(Disp, NewDisp))
1656       return 0;
1657     
1658     End = Tok.getEndLoc();
1659     Parser.Lex();  // Eat the field.
1660     Disp = NewDisp;
1661   }
1662
1663   int BaseReg = SM.getBaseReg();
1664   int IndexReg = SM.getIndexReg();
1665   int Scale = SM.getScale();
1666   if (!isParsingInlineAsm()) {
1667     // handle [-42]
1668     if (!BaseReg && !IndexReg) {
1669       if (!SegReg)
1670         return X86Operand::CreateMem(Disp, Start, End, Size);
1671       else
1672         return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1673     }
1674     StringRef ErrMsg;
1675     if (CheckBaseRegAndIndexReg(BaseReg, IndexReg, ErrMsg)) {
1676       Error(StartInBrac, ErrMsg);
1677       return 0;
1678     }
1679     return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1680                                  End, Size);
1681   }
1682
1683   InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1684   return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1685                                End, Size, SM.getSymName(), Info);
1686 }
1687
1688 // Inline assembly may use variable names with namespace alias qualifiers.
1689 bool X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1690                                         StringRef &Identifier,
1691                                         InlineAsmIdentifierInfo &Info,
1692                                         bool IsUnevaluatedOperand, SMLoc &End) {
1693   assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1694   Val = 0;
1695
1696   StringRef LineBuf(Identifier.data());
1697   SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
1698
1699   const AsmToken &Tok = Parser.getTok();
1700
1701   // Advance the token stream until the end of the current token is
1702   // after the end of what the frontend claimed.
1703   const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
1704   while (true) {
1705     End = Tok.getEndLoc();
1706     getLexer().Lex();
1707
1708     assert(End.getPointer() <= EndPtr && "frontend claimed part of a token?");
1709     if (End.getPointer() == EndPtr) break;
1710   }
1711
1712   // Create the symbol reference.
1713   Identifier = LineBuf;
1714   MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1715   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1716   Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1717   return false;
1718 }
1719
1720 /// \brief Parse intel style segment override.
1721 X86Operand *X86AsmParser::ParseIntelSegmentOverride(unsigned SegReg,
1722                                                     SMLoc Start,
1723                                                     unsigned Size) {
1724   assert(SegReg != 0 && "Tried to parse a segment override without a segment!");
1725   const AsmToken &Tok = Parser.getTok(); // Eat colon.
1726   if (Tok.isNot(AsmToken::Colon))
1727     return ErrorOperand(Tok.getLoc(), "Expected ':' token!");
1728   Parser.Lex(); // Eat ':'
1729
1730   int64_t ImmDisp = 0;
1731   if (getLexer().is(AsmToken::Integer)) {
1732     ImmDisp = Tok.getIntVal();
1733     AsmToken ImmDispToken = Parser.Lex(); // Eat the integer.
1734
1735     if (isParsingInlineAsm())
1736       InstInfo->AsmRewrites->push_back(
1737           AsmRewrite(AOK_ImmPrefix, ImmDispToken.getLoc()));
1738
1739     if (getLexer().isNot(AsmToken::LBrac)) {
1740       // An immediate following a 'segment register', 'colon' token sequence can
1741       // be followed by a bracketed expression.  If it isn't we know we have our
1742       // final segment override.
1743       const MCExpr *Disp = MCConstantExpr::Create(ImmDisp, getContext());
1744       return X86Operand::CreateMem(SegReg, Disp, /*BaseReg=*/0, /*IndexReg=*/0,
1745                                    /*Scale=*/1, Start, ImmDispToken.getEndLoc(),
1746                                    Size);
1747     }
1748   }
1749
1750   if (getLexer().is(AsmToken::LBrac))
1751     return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1752
1753   const MCExpr *Val;
1754   SMLoc End;
1755   if (!isParsingInlineAsm()) {
1756     if (getParser().parsePrimaryExpr(Val, End))
1757       return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1758
1759     return X86Operand::CreateMem(Val, Start, End, Size);
1760   }
1761
1762   InlineAsmIdentifierInfo Info;
1763   StringRef Identifier = Tok.getString();
1764   if (ParseIntelIdentifier(Val, Identifier, Info,
1765                            /*Unevaluated=*/false, End))
1766     return 0;
1767   return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1768                                /*Scale=*/1, Start, End, Size, Identifier, Info);
1769 }
1770
1771 /// ParseIntelMemOperand - Parse intel style memory operand.
1772 X86Operand *X86AsmParser::ParseIntelMemOperand(int64_t ImmDisp, SMLoc Start,
1773                                                unsigned Size) {
1774   const AsmToken &Tok = Parser.getTok();
1775   SMLoc End;
1776
1777   // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1778   if (getLexer().is(AsmToken::LBrac))
1779     return ParseIntelBracExpression(/*SegReg=*/0, Start, ImmDisp, Size);
1780
1781   const MCExpr *Val;
1782   if (!isParsingInlineAsm()) {
1783     if (getParser().parsePrimaryExpr(Val, End))
1784       return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1785
1786     return X86Operand::CreateMem(Val, Start, End, Size);
1787   }
1788
1789   InlineAsmIdentifierInfo Info;
1790   StringRef Identifier = Tok.getString();
1791   if (ParseIntelIdentifier(Val, Identifier, Info,
1792                            /*Unevaluated=*/false, End))
1793     return 0;
1794   return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0, /*IndexReg=*/0,
1795                                /*Scale=*/1, Start, End, Size, Identifier, Info);
1796 }
1797
1798 /// Parse the '.' operator.
1799 bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1800                                                 const MCExpr *&NewDisp) {
1801   const AsmToken &Tok = Parser.getTok();
1802   int64_t OrigDispVal, DotDispVal;
1803
1804   // FIXME: Handle non-constant expressions.
1805   if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1806     OrigDispVal = OrigDisp->getValue();
1807   else
1808     return Error(Tok.getLoc(), "Non-constant offsets are not supported!");
1809
1810   // Drop the '.'.
1811   StringRef DotDispStr = Tok.getString().drop_front(1);
1812
1813   // .Imm gets lexed as a real.
1814   if (Tok.is(AsmToken::Real)) {
1815     APInt DotDisp;
1816     DotDispStr.getAsInteger(10, DotDisp);
1817     DotDispVal = DotDisp.getZExtValue();
1818   } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1819     unsigned DotDisp;
1820     std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1821     if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1822                                            DotDisp))
1823       return Error(Tok.getLoc(), "Unable to lookup field reference!");
1824     DotDispVal = DotDisp;
1825   } else
1826     return Error(Tok.getLoc(), "Unexpected token type!");
1827
1828   if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1829     SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1830     unsigned Len = DotDispStr.size();
1831     unsigned Val = OrigDispVal + DotDispVal;
1832     InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1833                                                 Val));
1834   }
1835
1836   NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1837   return false;
1838 }
1839
1840 /// Parse the 'offset' operator.  This operator is used to specify the
1841 /// location rather then the content of a variable.
1842 X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1843   const AsmToken &Tok = Parser.getTok();
1844   SMLoc OffsetOfLoc = Tok.getLoc();
1845   Parser.Lex(); // Eat offset.
1846
1847   const MCExpr *Val;
1848   InlineAsmIdentifierInfo Info;
1849   SMLoc Start = Tok.getLoc(), End;
1850   StringRef Identifier = Tok.getString();
1851   if (ParseIntelIdentifier(Val, Identifier, Info,
1852                            /*Unevaluated=*/false, End))
1853     return 0;
1854
1855   // Don't emit the offset operator.
1856   InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1857
1858   // The offset operator will have an 'r' constraint, thus we need to create
1859   // register operand to ensure proper matching.  Just pick a GPR based on
1860   // the size of a pointer.
1861   unsigned RegNo =
1862       is64BitMode() ? X86::RBX : (is32BitMode() ? X86::EBX : X86::BX);
1863   return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1864                                OffsetOfLoc, Identifier, Info.OpDecl);
1865 }
1866
1867 enum IntelOperatorKind {
1868   IOK_LENGTH,
1869   IOK_SIZE,
1870   IOK_TYPE
1871 };
1872
1873 /// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators.  The LENGTH operator
1874 /// returns the number of elements in an array.  It returns the value 1 for
1875 /// non-array variables.  The SIZE operator returns the size of a C or C++
1876 /// variable.  A variable's size is the product of its LENGTH and TYPE.  The
1877 /// TYPE operator returns the size of a C or C++ type or variable. If the
1878 /// variable is an array, TYPE returns the size of a single element.
1879 X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1880   const AsmToken &Tok = Parser.getTok();
1881   SMLoc TypeLoc = Tok.getLoc();
1882   Parser.Lex(); // Eat operator.
1883
1884   const MCExpr *Val = 0;
1885   InlineAsmIdentifierInfo Info;
1886   SMLoc Start = Tok.getLoc(), End;
1887   StringRef Identifier = Tok.getString();
1888   if (ParseIntelIdentifier(Val, Identifier, Info,
1889                            /*Unevaluated=*/true, End))
1890     return 0;
1891
1892   if (!Info.OpDecl)
1893     return ErrorOperand(Start, "unable to lookup expression");
1894
1895   unsigned CVal = 0;
1896   switch(OpKind) {
1897   default: llvm_unreachable("Unexpected operand kind!");
1898   case IOK_LENGTH: CVal = Info.Length; break;
1899   case IOK_SIZE: CVal = Info.Size; break;
1900   case IOK_TYPE: CVal = Info.Type; break;
1901   }
1902
1903   // Rewrite the type operator and the C or C++ type or variable in terms of an
1904   // immediate.  E.g. TYPE foo -> $$4
1905   unsigned Len = End.getPointer() - TypeLoc.getPointer();
1906   InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1907
1908   const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1909   return X86Operand::CreateImm(Imm, Start, End);
1910 }
1911
1912 X86Operand *X86AsmParser::ParseIntelOperand() {
1913   const AsmToken &Tok = Parser.getTok();
1914   SMLoc Start, End;
1915
1916   // Offset, length, type and size operators.
1917   if (isParsingInlineAsm()) {
1918     StringRef AsmTokStr = Tok.getString();
1919     if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1920       return ParseIntelOffsetOfOperator();
1921     if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1922       return ParseIntelOperator(IOK_LENGTH);
1923     if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1924       return ParseIntelOperator(IOK_SIZE);
1925     if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1926       return ParseIntelOperator(IOK_TYPE);
1927   }
1928
1929   unsigned Size = getIntelMemOperandSize(Tok.getString());
1930   if (Size) {
1931     Parser.Lex(); // Eat operand size (e.g., byte, word).
1932     if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1933       return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1934     Parser.Lex(); // Eat ptr.
1935   }
1936   Start = Tok.getLoc();
1937
1938   // Immediate.
1939   if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1940       getLexer().is(AsmToken::LParen)) {    
1941     AsmToken StartTok = Tok;
1942     IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1943                              /*AddImmPrefix=*/false);
1944     if (ParseIntelExpression(SM, End))
1945       return 0;
1946
1947     int64_t Imm = SM.getImm();
1948     if (isParsingInlineAsm()) {
1949       unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1950       if (StartTok.getString().size() == Len)
1951         // Just add a prefix if this wasn't a complex immediate expression.
1952         InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1953       else
1954         // Otherwise, rewrite the complex expression as a single immediate.
1955         InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1956     }
1957
1958     if (getLexer().isNot(AsmToken::LBrac)) {
1959       // If a directional label (ie. 1f or 2b) was parsed above from
1960       // ParseIntelExpression() then SM.getSym() was set to a pointer to
1961       // to the MCExpr with the directional local symbol and this is a
1962       // memory operand not an immediate operand.
1963       if (SM.getSym())
1964         return X86Operand::CreateMem(SM.getSym(), Start, End, Size);
1965
1966       const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1967       return X86Operand::CreateImm(ImmExpr, Start, End);
1968     }
1969
1970     // Only positive immediates are valid.
1971     if (Imm < 0)
1972       return ErrorOperand(Start, "expected a positive immediate displacement "
1973                           "before bracketed expr.");
1974
1975     // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1976     return ParseIntelMemOperand(Imm, Start, Size);
1977   }
1978
1979   // Register.
1980   unsigned RegNo = 0;
1981   if (!ParseRegister(RegNo, Start, End)) {
1982     // If this is a segment register followed by a ':', then this is the start
1983     // of a segment override, otherwise this is a normal register reference.
1984     if (getLexer().isNot(AsmToken::Colon))
1985       return X86Operand::CreateReg(RegNo, Start, End);
1986
1987     return ParseIntelSegmentOverride(/*SegReg=*/RegNo, Start, Size);
1988   }
1989
1990   // Memory operand.
1991   return ParseIntelMemOperand(/*Disp=*/0, Start, Size);
1992 }
1993
1994 X86Operand *X86AsmParser::ParseATTOperand() {
1995   switch (getLexer().getKind()) {
1996   default:
1997     // Parse a memory operand with no segment register.
1998     return ParseMemOperand(0, Parser.getTok().getLoc());
1999   case AsmToken::Percent: {
2000     // Read the register.
2001     unsigned RegNo;
2002     SMLoc Start, End;
2003     if (ParseRegister(RegNo, Start, End)) return 0;
2004     if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
2005       Error(Start, "%eiz and %riz can only be used as index registers",
2006             SMRange(Start, End));
2007       return 0;
2008     }
2009
2010     // If this is a segment register followed by a ':', then this is the start
2011     // of a memory reference, otherwise this is a normal register reference.
2012     if (getLexer().isNot(AsmToken::Colon))
2013       return X86Operand::CreateReg(RegNo, Start, End);
2014
2015     getParser().Lex(); // Eat the colon.
2016     return ParseMemOperand(RegNo, Start);
2017   }
2018   case AsmToken::Dollar: {
2019     // $42 -> immediate.
2020     SMLoc Start = Parser.getTok().getLoc(), End;
2021     Parser.Lex();
2022     const MCExpr *Val;
2023     if (getParser().parseExpression(Val, End))
2024       return 0;
2025     return X86Operand::CreateImm(Val, Start, End);
2026   }
2027   }
2028 }
2029
2030 /// ParseMemOperand: segment: disp(basereg, indexreg, scale).  The '%ds:' prefix
2031 /// has already been parsed if present.
2032 X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
2033
2034   // We have to disambiguate a parenthesized expression "(4+5)" from the start
2035   // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)".  The
2036   // only way to do this without lookahead is to eat the '(' and see what is
2037   // after it.
2038   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
2039   if (getLexer().isNot(AsmToken::LParen)) {
2040     SMLoc ExprEnd;
2041     if (getParser().parseExpression(Disp, ExprEnd)) return 0;
2042
2043     // After parsing the base expression we could either have a parenthesized
2044     // memory address or not.  If not, return now.  If so, eat the (.
2045     if (getLexer().isNot(AsmToken::LParen)) {
2046       // Unless we have a segment register, treat this as an immediate.
2047       if (SegReg == 0)
2048         return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
2049       return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
2050     }
2051
2052     // Eat the '('.
2053     Parser.Lex();
2054   } else {
2055     // Okay, we have a '('.  We don't know if this is an expression or not, but
2056     // so we have to eat the ( to see beyond it.
2057     SMLoc LParenLoc = Parser.getTok().getLoc();
2058     Parser.Lex(); // Eat the '('.
2059
2060     if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
2061       // Nothing to do here, fall into the code below with the '(' part of the
2062       // memory operand consumed.
2063     } else {
2064       SMLoc ExprEnd;
2065
2066       // It must be an parenthesized expression, parse it now.
2067       if (getParser().parseParenExpression(Disp, ExprEnd))
2068         return 0;
2069
2070       // After parsing the base expression we could either have a parenthesized
2071       // memory address or not.  If not, return now.  If so, eat the (.
2072       if (getLexer().isNot(AsmToken::LParen)) {
2073         // Unless we have a segment register, treat this as an immediate.
2074         if (SegReg == 0)
2075           return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
2076         return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
2077       }
2078
2079       // Eat the '('.
2080       Parser.Lex();
2081     }
2082   }
2083
2084   // If we reached here, then we just ate the ( of the memory operand.  Process
2085   // the rest of the memory operand.
2086   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
2087   SMLoc IndexLoc, BaseLoc;
2088
2089   if (getLexer().is(AsmToken::Percent)) {
2090     SMLoc StartLoc, EndLoc;
2091     BaseLoc = Parser.getTok().getLoc();
2092     if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
2093     if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
2094       Error(StartLoc, "eiz and riz can only be used as index registers",
2095             SMRange(StartLoc, EndLoc));
2096       return 0;
2097     }
2098   }
2099
2100   if (getLexer().is(AsmToken::Comma)) {
2101     Parser.Lex(); // Eat the comma.
2102     IndexLoc = Parser.getTok().getLoc();
2103
2104     // Following the comma we should have either an index register, or a scale
2105     // value. We don't support the later form, but we want to parse it
2106     // correctly.
2107     //
2108     // Not that even though it would be completely consistent to support syntax
2109     // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
2110     if (getLexer().is(AsmToken::Percent)) {
2111       SMLoc L;
2112       if (ParseRegister(IndexReg, L, L)) return 0;
2113
2114       if (getLexer().isNot(AsmToken::RParen)) {
2115         // Parse the scale amount:
2116         //  ::= ',' [scale-expression]
2117         if (getLexer().isNot(AsmToken::Comma)) {
2118           Error(Parser.getTok().getLoc(),
2119                 "expected comma in scale expression");
2120           return 0;
2121         }
2122         Parser.Lex(); // Eat the comma.
2123
2124         if (getLexer().isNot(AsmToken::RParen)) {
2125           SMLoc Loc = Parser.getTok().getLoc();
2126
2127           int64_t ScaleVal;
2128           if (getParser().parseAbsoluteExpression(ScaleVal)){
2129             Error(Loc, "expected scale expression");
2130             return 0;
2131           }
2132
2133           // Validate the scale amount.
2134           if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) &&
2135               ScaleVal != 1) {
2136             Error(Loc, "scale factor in 16-bit address must be 1");
2137             return 0;
2138           }
2139           if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
2140             Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
2141             return 0;
2142           }
2143           Scale = (unsigned)ScaleVal;
2144         }
2145       }
2146     } else if (getLexer().isNot(AsmToken::RParen)) {
2147       // A scale amount without an index is ignored.
2148       // index.
2149       SMLoc Loc = Parser.getTok().getLoc();
2150
2151       int64_t Value;
2152       if (getParser().parseAbsoluteExpression(Value))
2153         return 0;
2154
2155       if (Value != 1)
2156         Warning(Loc, "scale factor without index register is ignored");
2157       Scale = 1;
2158     }
2159   }
2160
2161   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
2162   if (getLexer().isNot(AsmToken::RParen)) {
2163     Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
2164     return 0;
2165   }
2166   SMLoc MemEnd = Parser.getTok().getEndLoc();
2167   Parser.Lex(); // Eat the ')'.
2168
2169   // Check for use of invalid 16-bit registers. Only BX/BP/SI/DI are allowed,
2170   // and then only in non-64-bit modes. Except for DX, which is a special case
2171   // because an unofficial form of in/out instructions uses it.
2172   if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) &&
2173       (is64BitMode() || (BaseReg != X86::BX && BaseReg != X86::BP &&
2174                          BaseReg != X86::SI && BaseReg != X86::DI)) &&
2175       BaseReg != X86::DX) {
2176     Error(BaseLoc, "invalid 16-bit base register");
2177     return 0;
2178   }
2179   if (BaseReg == 0 &&
2180       X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)) {
2181     Error(IndexLoc, "16-bit memory operand may not include only index register");
2182     return 0;
2183   }
2184
2185   StringRef ErrMsg;
2186   if (CheckBaseRegAndIndexReg(BaseReg, IndexReg, ErrMsg)) {
2187     Error(BaseLoc, ErrMsg);
2188     return 0;
2189   }
2190
2191   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
2192                                MemStart, MemEnd);
2193 }
2194
2195 bool X86AsmParser::
2196 ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
2197                  SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2198   InstInfo = &Info;
2199   StringRef PatchedName = Name;
2200
2201   // FIXME: Hack to recognize setneb as setne.
2202   if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
2203       PatchedName != "setb" && PatchedName != "setnb")
2204     PatchedName = PatchedName.substr(0, Name.size()-1);
2205
2206   // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
2207   const MCExpr *ExtraImmOp = 0;
2208   if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
2209       (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
2210        PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
2211     bool IsVCMP = PatchedName[0] == 'v';
2212     unsigned SSECCIdx = IsVCMP ? 4 : 3;
2213     unsigned SSEComparisonCode = StringSwitch<unsigned>(
2214       PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
2215       .Case("eq",       0x00)
2216       .Case("lt",       0x01)
2217       .Case("le",       0x02)
2218       .Case("unord",    0x03)
2219       .Case("neq",      0x04)
2220       .Case("nlt",      0x05)
2221       .Case("nle",      0x06)
2222       .Case("ord",      0x07)
2223       /* AVX only from here */
2224       .Case("eq_uq",    0x08)
2225       .Case("nge",      0x09)
2226       .Case("ngt",      0x0A)
2227       .Case("false",    0x0B)
2228       .Case("neq_oq",   0x0C)
2229       .Case("ge",       0x0D)
2230       .Case("gt",       0x0E)
2231       .Case("true",     0x0F)
2232       .Case("eq_os",    0x10)
2233       .Case("lt_oq",    0x11)
2234       .Case("le_oq",    0x12)
2235       .Case("unord_s",  0x13)
2236       .Case("neq_us",   0x14)
2237       .Case("nlt_uq",   0x15)
2238       .Case("nle_uq",   0x16)
2239       .Case("ord_s",    0x17)
2240       .Case("eq_us",    0x18)
2241       .Case("nge_uq",   0x19)
2242       .Case("ngt_uq",   0x1A)
2243       .Case("false_os", 0x1B)
2244       .Case("neq_os",   0x1C)
2245       .Case("ge_oq",    0x1D)
2246       .Case("gt_oq",    0x1E)
2247       .Case("true_us",  0x1F)
2248       .Default(~0U);
2249     if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
2250       ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
2251                                           getParser().getContext());
2252       if (PatchedName.endswith("ss")) {
2253         PatchedName = IsVCMP ? "vcmpss" : "cmpss";
2254       } else if (PatchedName.endswith("sd")) {
2255         PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
2256       } else if (PatchedName.endswith("ps")) {
2257         PatchedName = IsVCMP ? "vcmpps" : "cmpps";
2258       } else {
2259         assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
2260         PatchedName = IsVCMP ? "vcmppd" : "cmppd";
2261       }
2262     }
2263   }
2264
2265   Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
2266
2267   if (ExtraImmOp && !isParsingIntelSyntax())
2268     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
2269
2270   // Determine whether this is an instruction prefix.
2271   bool isPrefix =
2272     Name == "lock" || Name == "rep" ||
2273     Name == "repe" || Name == "repz" ||
2274     Name == "repne" || Name == "repnz" ||
2275     Name == "rex64" || Name == "data16";
2276
2277
2278   // This does the actual operand parsing.  Don't parse any more if we have a
2279   // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
2280   // just want to parse the "lock" as the first instruction and the "incl" as
2281   // the next one.
2282   if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
2283
2284     // Parse '*' modifier.
2285     if (getLexer().is(AsmToken::Star))
2286       Operands.push_back(X86Operand::CreateToken("*", consumeToken()));
2287
2288     // Read the first operand.
2289     if (X86Operand *Op = ParseOperand())
2290       Operands.push_back(Op);
2291     else {
2292       Parser.eatToEndOfStatement();
2293       return true;
2294     }
2295
2296     while (getLexer().is(AsmToken::Comma)) {
2297       Parser.Lex();  // Eat the comma.
2298
2299       // Parse and remember the operand.
2300       if (X86Operand *Op = ParseOperand())
2301         Operands.push_back(Op);
2302       else {
2303         Parser.eatToEndOfStatement();
2304         return true;
2305       }
2306     }
2307
2308     if (STI.getFeatureBits() & X86::FeatureAVX512) {
2309       // Parse mask register {%k1}
2310       if (getLexer().is(AsmToken::LCurly)) {
2311         Operands.push_back(X86Operand::CreateToken("{", consumeToken()));
2312         if (X86Operand *Op = ParseOperand()) {
2313           Operands.push_back(Op);
2314           if (!getLexer().is(AsmToken::RCurly)) {
2315             SMLoc Loc = getLexer().getLoc();
2316             Parser.eatToEndOfStatement();
2317             return Error(Loc, "Expected } at this point");
2318           }
2319           Operands.push_back(X86Operand::CreateToken("}", consumeToken()));
2320         } else {
2321           Parser.eatToEndOfStatement();
2322           return true;
2323         }
2324       }
2325       // TODO: add parsing of broadcasts {1to8}, {1to16}
2326       // Parse "zeroing non-masked" semantic {z}
2327       if (getLexer().is(AsmToken::LCurly)) {
2328         Operands.push_back(X86Operand::CreateToken("{z}", consumeToken()));
2329         if (!getLexer().is(AsmToken::Identifier) || getLexer().getTok().getIdentifier() != "z") {
2330           SMLoc Loc = getLexer().getLoc();
2331           Parser.eatToEndOfStatement();
2332           return Error(Loc, "Expected z at this point");
2333         }
2334         Parser.Lex();  // Eat the z
2335         if (!getLexer().is(AsmToken::RCurly)) {
2336             SMLoc Loc = getLexer().getLoc();
2337             Parser.eatToEndOfStatement();
2338             return Error(Loc, "Expected } at this point");
2339         }
2340         Parser.Lex();  // Eat the }
2341       }
2342     }
2343
2344     if (getLexer().isNot(AsmToken::EndOfStatement)) {
2345       SMLoc Loc = getLexer().getLoc();
2346       Parser.eatToEndOfStatement();
2347       return Error(Loc, "unexpected token in argument list");
2348     }
2349   }
2350
2351   if (getLexer().is(AsmToken::EndOfStatement))
2352     Parser.Lex(); // Consume the EndOfStatement
2353   else if (isPrefix && getLexer().is(AsmToken::Slash))
2354     Parser.Lex(); // Consume the prefix separator Slash
2355
2356   if (ExtraImmOp && isParsingIntelSyntax())
2357     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
2358
2359   // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
2360   // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
2361   // documented form in various unofficial manuals, so a lot of code uses it.
2362   if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
2363       Operands.size() == 3) {
2364     X86Operand &Op = *(X86Operand*)Operands.back();
2365     if (Op.isMem() && Op.Mem.SegReg == 0 &&
2366         isa<MCConstantExpr>(Op.Mem.Disp) &&
2367         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2368         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2369       SMLoc Loc = Op.getEndLoc();
2370       Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2371       delete &Op;
2372     }
2373   }
2374   // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
2375   if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
2376       Operands.size() == 3) {
2377     X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2378     if (Op.isMem() && Op.Mem.SegReg == 0 &&
2379         isa<MCConstantExpr>(Op.Mem.Disp) &&
2380         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2381         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2382       SMLoc Loc = Op.getEndLoc();
2383       Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2384       delete &Op;
2385     }
2386   }
2387
2388   // Append default arguments to "ins[bwld]"
2389   if (Name.startswith("ins") && Operands.size() == 1 &&
2390       (Name == "insb" || Name == "insw" || Name == "insl" ||
2391        Name == "insd" )) {
2392     if (isParsingIntelSyntax()) {
2393       Operands.push_back(X86Operand::CreateReg(X86::DX, NameLoc, NameLoc));
2394       Operands.push_back(DefaultMemDIOperand(NameLoc));
2395     } else {
2396       Operands.push_back(X86Operand::CreateReg(X86::DX, NameLoc, NameLoc));
2397       Operands.push_back(DefaultMemDIOperand(NameLoc));
2398     }
2399   }
2400
2401   // Append default arguments to "outs[bwld]"
2402   if (Name.startswith("outs") && Operands.size() == 1 &&
2403       (Name == "outsb" || Name == "outsw" || Name == "outsl" ||
2404        Name == "outsd" )) {
2405     if (isParsingIntelSyntax()) {
2406       Operands.push_back(DefaultMemSIOperand(NameLoc));
2407       Operands.push_back(X86Operand::CreateReg(X86::DX, NameLoc, NameLoc));
2408     } else {
2409       Operands.push_back(DefaultMemSIOperand(NameLoc));
2410       Operands.push_back(X86Operand::CreateReg(X86::DX, NameLoc, NameLoc));
2411     }
2412   }
2413
2414   // Transform "lods[bwlq]" into "lods[bwlq] ($SIREG)" for appropriate
2415   // values of $SIREG according to the mode. It would be nice if this
2416   // could be achieved with InstAlias in the tables.
2417   if (Name.startswith("lods") && Operands.size() == 1 &&
2418       (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2419        Name == "lodsl" || Name == "lodsd" || Name == "lodsq"))
2420     Operands.push_back(DefaultMemSIOperand(NameLoc));
2421
2422   // Transform "stos[bwlq]" into "stos[bwlq] ($DIREG)" for appropriate
2423   // values of $DIREG according to the mode. It would be nice if this
2424   // could be achieved with InstAlias in the tables.
2425   if (Name.startswith("stos") && Operands.size() == 1 &&
2426       (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2427        Name == "stosl" || Name == "stosd" || Name == "stosq"))
2428     Operands.push_back(DefaultMemDIOperand(NameLoc));
2429
2430   // Transform "scas[bwlq]" into "scas[bwlq] ($DIREG)" for appropriate
2431   // values of $DIREG according to the mode. It would be nice if this
2432   // could be achieved with InstAlias in the tables.
2433   if (Name.startswith("scas") && Operands.size() == 1 &&
2434       (Name == "scas" || Name == "scasb" || Name == "scasw" ||
2435        Name == "scasl" || Name == "scasd" || Name == "scasq"))
2436     Operands.push_back(DefaultMemDIOperand(NameLoc));
2437
2438   // Add default SI and DI operands to "cmps[bwlq]".
2439   if (Name.startswith("cmps") &&
2440       (Name == "cmps" || Name == "cmpsb" || Name == "cmpsw" ||
2441        Name == "cmpsl" || Name == "cmpsd" || Name == "cmpsq")) {
2442     if (Operands.size() == 1) {
2443       if (isParsingIntelSyntax()) {
2444         Operands.push_back(DefaultMemSIOperand(NameLoc));
2445         Operands.push_back(DefaultMemDIOperand(NameLoc));
2446       } else {
2447         Operands.push_back(DefaultMemDIOperand(NameLoc));
2448         Operands.push_back(DefaultMemSIOperand(NameLoc));
2449       }
2450     } else if (Operands.size() == 3) {
2451       X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2452       X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2453       if (!doSrcDstMatch(Op, Op2))
2454         return Error(Op.getStartLoc(),
2455                      "mismatching source and destination index registers");
2456     }
2457   }
2458
2459   // Add default SI and DI operands to "movs[bwlq]".
2460   if ((Name.startswith("movs") &&
2461       (Name == "movs" || Name == "movsb" || Name == "movsw" ||
2462        Name == "movsl" || Name == "movsd" || Name == "movsq")) ||
2463       (Name.startswith("smov") &&
2464       (Name == "smov" || Name == "smovb" || Name == "smovw" ||
2465        Name == "smovl" || Name == "smovd" || Name == "smovq"))) {
2466     if (Operands.size() == 1) {
2467       if (Name == "movsd")
2468         Operands.back() = X86Operand::CreateToken("movsl", NameLoc);
2469       if (isParsingIntelSyntax()) {
2470         Operands.push_back(DefaultMemDIOperand(NameLoc));
2471         Operands.push_back(DefaultMemSIOperand(NameLoc));
2472       } else {
2473         Operands.push_back(DefaultMemSIOperand(NameLoc));
2474         Operands.push_back(DefaultMemDIOperand(NameLoc));
2475       }
2476     } else if (Operands.size() == 3) {
2477       X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2478       X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2479       if (!doSrcDstMatch(Op, Op2))
2480         return Error(Op.getStartLoc(),
2481                      "mismatching source and destination index registers");
2482     }
2483   }
2484
2485   // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>.  Canonicalize to
2486   // "shift <op>".
2487   if ((Name.startswith("shr") || Name.startswith("sar") ||
2488        Name.startswith("shl") || Name.startswith("sal") ||
2489        Name.startswith("rcl") || Name.startswith("rcr") ||
2490        Name.startswith("rol") || Name.startswith("ror")) &&
2491       Operands.size() == 3) {
2492     if (isParsingIntelSyntax()) {
2493       // Intel syntax
2494       X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2495       if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2496           cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2497         delete Operands[2];
2498         Operands.pop_back();
2499       }
2500     } else {
2501       X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2502       if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2503           cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2504         delete Operands[1];
2505         Operands.erase(Operands.begin() + 1);
2506       }
2507     }
2508   }
2509
2510   // Transforms "int $3" into "int3" as a size optimization.  We can't write an
2511   // instalias with an immediate operand yet.
2512   if (Name == "int" && Operands.size() == 2) {
2513     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2514     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2515         cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2516       delete Operands[1];
2517       Operands.erase(Operands.begin() + 1);
2518       static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2519     }
2520   }
2521
2522   return false;
2523 }
2524
2525 static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2526                             bool isCmp) {
2527   MCInst TmpInst;
2528   TmpInst.setOpcode(Opcode);
2529   if (!isCmp)
2530     TmpInst.addOperand(MCOperand::CreateReg(Reg));
2531   TmpInst.addOperand(MCOperand::CreateReg(Reg));
2532   TmpInst.addOperand(Inst.getOperand(0));
2533   Inst = TmpInst;
2534   return true;
2535 }
2536
2537 static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2538                                 bool isCmp = false) {
2539   if (!Inst.getOperand(0).isImm() ||
2540       !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2541     return false;
2542
2543   return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2544 }
2545
2546 static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2547                                 bool isCmp = false) {
2548   if (!Inst.getOperand(0).isImm() ||
2549       !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2550     return false;
2551
2552   return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2553 }
2554
2555 static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2556                                 bool isCmp = false) {
2557   if (!Inst.getOperand(0).isImm() ||
2558       !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2559     return false;
2560
2561   return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2562 }
2563
2564 bool X86AsmParser::
2565 processInstruction(MCInst &Inst,
2566                    const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2567   switch (Inst.getOpcode()) {
2568   default: return false;
2569   case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2570   case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2571   case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2572   case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2573   case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2574   case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2575   case X86::OR16i16:  return convert16i16to16ri8(Inst, X86::OR16ri8);
2576   case X86::OR32i32:  return convert32i32to32ri8(Inst, X86::OR32ri8);
2577   case X86::OR64i32:  return convert64i32to64ri8(Inst, X86::OR64ri8);
2578   case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2579   case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2580   case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2581   case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2582   case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2583   case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2584   case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2585   case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2586   case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2587   case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2588   case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2589   case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2590   case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2591   case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2592   case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2593   case X86::VMOVAPDrr:
2594   case X86::VMOVAPDYrr:
2595   case X86::VMOVAPSrr:
2596   case X86::VMOVAPSYrr:
2597   case X86::VMOVDQArr:
2598   case X86::VMOVDQAYrr:
2599   case X86::VMOVDQUrr:
2600   case X86::VMOVDQUYrr:
2601   case X86::VMOVUPDrr:
2602   case X86::VMOVUPDYrr:
2603   case X86::VMOVUPSrr:
2604   case X86::VMOVUPSYrr: {
2605     if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) ||
2606         !X86II::isX86_64ExtendedReg(Inst.getOperand(1).getReg()))
2607       return false;
2608
2609     unsigned NewOpc;
2610     switch (Inst.getOpcode()) {
2611     default: llvm_unreachable("Invalid opcode");
2612     case X86::VMOVAPDrr:  NewOpc = X86::VMOVAPDrr_REV;  break;
2613     case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
2614     case X86::VMOVAPSrr:  NewOpc = X86::VMOVAPSrr_REV;  break;
2615     case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
2616     case X86::VMOVDQArr:  NewOpc = X86::VMOVDQArr_REV;  break;
2617     case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
2618     case X86::VMOVDQUrr:  NewOpc = X86::VMOVDQUrr_REV;  break;
2619     case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
2620     case X86::VMOVUPDrr:  NewOpc = X86::VMOVUPDrr_REV;  break;
2621     case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
2622     case X86::VMOVUPSrr:  NewOpc = X86::VMOVUPSrr_REV;  break;
2623     case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
2624     }
2625     Inst.setOpcode(NewOpc);
2626     return true;
2627   }
2628   case X86::VMOVSDrr:
2629   case X86::VMOVSSrr: {
2630     if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) ||
2631         !X86II::isX86_64ExtendedReg(Inst.getOperand(2).getReg()))
2632       return false;
2633     unsigned NewOpc;
2634     switch (Inst.getOpcode()) {
2635     default: llvm_unreachable("Invalid opcode");
2636     case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV;   break;
2637     case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV;   break;
2638     }
2639     Inst.setOpcode(NewOpc);
2640     return true;
2641   }
2642   }
2643 }
2644
2645 static const char *getSubtargetFeatureName(unsigned Val);
2646 bool X86AsmParser::
2647 MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2648                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2649                         MCStreamer &Out, unsigned &ErrorInfo,
2650                         bool MatchingInlineAsm) {
2651   assert(!Operands.empty() && "Unexpect empty operand list!");
2652   X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2653   assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2654   ArrayRef<SMRange> EmptyRanges = None;
2655
2656   // First, handle aliases that expand to multiple instructions.
2657   // FIXME: This should be replaced with a real .td file alias mechanism.
2658   // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2659   // call.
2660   if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2661       Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2662       Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2663       Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2664     MCInst Inst;
2665     Inst.setOpcode(X86::WAIT);
2666     Inst.setLoc(IDLoc);
2667     if (!MatchingInlineAsm)
2668       Out.EmitInstruction(Inst, STI);
2669
2670     const char *Repl =
2671       StringSwitch<const char*>(Op->getToken())
2672         .Case("finit",  "fninit")
2673         .Case("fsave",  "fnsave")
2674         .Case("fstcw",  "fnstcw")
2675         .Case("fstcww",  "fnstcw")
2676         .Case("fstenv", "fnstenv")
2677         .Case("fstsw",  "fnstsw")
2678         .Case("fstsww", "fnstsw")
2679         .Case("fclex",  "fnclex")
2680         .Default(0);
2681     assert(Repl && "Unknown wait-prefixed instruction");
2682     delete Operands[0];
2683     Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2684   }
2685
2686   bool WasOriginallyInvalidOperand = false;
2687   MCInst Inst;
2688
2689   // First, try a direct match.
2690   switch (MatchInstructionImpl(Operands, Inst,
2691                                ErrorInfo, MatchingInlineAsm,
2692                                isParsingIntelSyntax())) {
2693   default: break;
2694   case Match_Success:
2695     // Some instructions need post-processing to, for example, tweak which
2696     // encoding is selected. Loop on it while changes happen so the
2697     // individual transformations can chain off each other.
2698     if (!MatchingInlineAsm)
2699       while (processInstruction(Inst, Operands))
2700         ;
2701
2702     Inst.setLoc(IDLoc);
2703     if (!MatchingInlineAsm)
2704       Out.EmitInstruction(Inst, STI);
2705     Opcode = Inst.getOpcode();
2706     return false;
2707   case Match_MissingFeature: {
2708     assert(ErrorInfo && "Unknown missing feature!");
2709     // Special case the error message for the very common case where only
2710     // a single subtarget feature is missing.
2711     std::string Msg = "instruction requires:";
2712     unsigned Mask = 1;
2713     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2714       if (ErrorInfo & Mask) {
2715         Msg += " ";
2716         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2717       }
2718       Mask <<= 1;
2719     }
2720     return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2721   }
2722   case Match_InvalidOperand:
2723     WasOriginallyInvalidOperand = true;
2724     break;
2725   case Match_MnemonicFail:
2726     break;
2727   }
2728
2729   // FIXME: Ideally, we would only attempt suffix matches for things which are
2730   // valid prefixes, and we could just infer the right unambiguous
2731   // type. However, that requires substantially more matcher support than the
2732   // following hack.
2733
2734   // Change the operand to point to a temporary token.
2735   StringRef Base = Op->getToken();
2736   SmallString<16> Tmp;
2737   Tmp += Base;
2738   Tmp += ' ';
2739   Op->setTokenValue(Tmp.str());
2740
2741   // If this instruction starts with an 'f', then it is a floating point stack
2742   // instruction.  These come in up to three forms for 32-bit, 64-bit, and
2743   // 80-bit floating point, which use the suffixes s,l,t respectively.
2744   //
2745   // Otherwise, we assume that this may be an integer instruction, which comes
2746   // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2747   const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2748
2749   // Check for the various suffix matches.
2750   Tmp[Base.size()] = Suffixes[0];
2751   unsigned ErrorInfoIgnore;
2752   unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2753   unsigned Match1, Match2, Match3, Match4;
2754
2755   Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2756                                 MatchingInlineAsm, isParsingIntelSyntax());
2757   // If this returned as a missing feature failure, remember that.
2758   if (Match1 == Match_MissingFeature)
2759     ErrorInfoMissingFeature = ErrorInfoIgnore;
2760   Tmp[Base.size()] = Suffixes[1];
2761   Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2762                                 MatchingInlineAsm, isParsingIntelSyntax());
2763   // If this returned as a missing feature failure, remember that.
2764   if (Match2 == Match_MissingFeature)
2765     ErrorInfoMissingFeature = ErrorInfoIgnore;
2766   Tmp[Base.size()] = Suffixes[2];
2767   Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2768                                 MatchingInlineAsm, isParsingIntelSyntax());
2769   // If this returned as a missing feature failure, remember that.
2770   if (Match3 == Match_MissingFeature)
2771     ErrorInfoMissingFeature = ErrorInfoIgnore;
2772   Tmp[Base.size()] = Suffixes[3];
2773   Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2774                                 MatchingInlineAsm, isParsingIntelSyntax());
2775   // If this returned as a missing feature failure, remember that.
2776   if (Match4 == Match_MissingFeature)
2777     ErrorInfoMissingFeature = ErrorInfoIgnore;
2778
2779   // Restore the old token.
2780   Op->setTokenValue(Base);
2781
2782   // If exactly one matched, then we treat that as a successful match (and the
2783   // instruction will already have been filled in correctly, since the failing
2784   // matches won't have modified it).
2785   unsigned NumSuccessfulMatches =
2786     (Match1 == Match_Success) + (Match2 == Match_Success) +
2787     (Match3 == Match_Success) + (Match4 == Match_Success);
2788   if (NumSuccessfulMatches == 1) {
2789     Inst.setLoc(IDLoc);
2790     if (!MatchingInlineAsm)
2791       Out.EmitInstruction(Inst, STI);
2792     Opcode = Inst.getOpcode();
2793     return false;
2794   }
2795
2796   // Otherwise, the match failed, try to produce a decent error message.
2797
2798   // If we had multiple suffix matches, then identify this as an ambiguous
2799   // match.
2800   if (NumSuccessfulMatches > 1) {
2801     char MatchChars[4];
2802     unsigned NumMatches = 0;
2803     if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2804     if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2805     if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2806     if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2807
2808     SmallString<126> Msg;
2809     raw_svector_ostream OS(Msg);
2810     OS << "ambiguous instructions require an explicit suffix (could be ";
2811     for (unsigned i = 0; i != NumMatches; ++i) {
2812       if (i != 0)
2813         OS << ", ";
2814       if (i + 1 == NumMatches)
2815         OS << "or ";
2816       OS << "'" << Base << MatchChars[i] << "'";
2817     }
2818     OS << ")";
2819     Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2820     return true;
2821   }
2822
2823   // Okay, we know that none of the variants matched successfully.
2824
2825   // If all of the instructions reported an invalid mnemonic, then the original
2826   // mnemonic was invalid.
2827   if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2828       (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2829     if (!WasOriginallyInvalidOperand) {
2830       ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2831         Op->getLocRange();
2832       return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2833                    Ranges, MatchingInlineAsm);
2834     }
2835
2836     // Recover location info for the operand if we know which was the problem.
2837     if (ErrorInfo != ~0U) {
2838       if (ErrorInfo >= Operands.size())
2839         return Error(IDLoc, "too few operands for instruction",
2840                      EmptyRanges, MatchingInlineAsm);
2841
2842       X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2843       if (Operand->getStartLoc().isValid()) {
2844         SMRange OperandRange = Operand->getLocRange();
2845         return Error(Operand->getStartLoc(), "invalid operand for instruction",
2846                      OperandRange, MatchingInlineAsm);
2847       }
2848     }
2849
2850     return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2851                  MatchingInlineAsm);
2852   }
2853
2854   // If one instruction matched with a missing feature, report this as a
2855   // missing feature.
2856   if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2857       (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2858     std::string Msg = "instruction requires:";
2859     unsigned Mask = 1;
2860     for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2861       if (ErrorInfoMissingFeature & Mask) {
2862         Msg += " ";
2863         Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2864       }
2865       Mask <<= 1;
2866     }
2867     return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2868   }
2869
2870   // If one instruction matched with an invalid operand, report this as an
2871   // operand failure.
2872   if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2873       (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2874     Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2875           MatchingInlineAsm);
2876     return true;
2877   }
2878
2879   // If all of these were an outright failure, report it in a useless way.
2880   Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2881         EmptyRanges, MatchingInlineAsm);
2882   return true;
2883 }
2884
2885
2886 bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2887   StringRef IDVal = DirectiveID.getIdentifier();
2888   if (IDVal == ".word")
2889     return ParseDirectiveWord(2, DirectiveID.getLoc());
2890   else if (IDVal.startswith(".code"))
2891     return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2892   else if (IDVal.startswith(".att_syntax")) {
2893     getParser().setAssemblerDialect(0);
2894     return false;
2895   } else if (IDVal.startswith(".intel_syntax")) {
2896     getParser().setAssemblerDialect(1);
2897     if (getLexer().isNot(AsmToken::EndOfStatement)) {
2898       // FIXME: Handle noprefix
2899       if (Parser.getTok().getString() == "noprefix")
2900         Parser.Lex();
2901     }
2902     return false;
2903   }
2904   return true;
2905 }
2906
2907 /// ParseDirectiveWord
2908 ///  ::= .word [ expression (, expression)* ]
2909 bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2910   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2911     for (;;) {
2912       const MCExpr *Value;
2913       if (getParser().parseExpression(Value))
2914         return false;
2915
2916       getParser().getStreamer().EmitValue(Value, Size);
2917
2918       if (getLexer().is(AsmToken::EndOfStatement))
2919         break;
2920
2921       // FIXME: Improve diagnostic.
2922       if (getLexer().isNot(AsmToken::Comma)) {
2923         Error(L, "unexpected token in directive");
2924         return false;
2925       }
2926       Parser.Lex();
2927     }
2928   }
2929
2930   Parser.Lex();
2931   return false;
2932 }
2933
2934 /// ParseDirectiveCode
2935 ///  ::= .code16 | .code32 | .code64
2936 bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2937   if (IDVal == ".code16") {
2938     Parser.Lex();
2939     if (!is16BitMode()) {
2940       SwitchMode(X86::Mode16Bit);
2941       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
2942     }
2943   } else if (IDVal == ".code32") {
2944     Parser.Lex();
2945     if (!is32BitMode()) {
2946       SwitchMode(X86::Mode32Bit);
2947       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2948     }
2949   } else if (IDVal == ".code64") {
2950     Parser.Lex();
2951     if (!is64BitMode()) {
2952       SwitchMode(X86::Mode64Bit);
2953       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2954     }
2955   } else {
2956     Error(L, "unknown directive " + IDVal);
2957     return false;
2958   }
2959
2960   return false;
2961 }
2962
2963 // Force static initialization.
2964 extern "C" void LLVMInitializeX86AsmParser() {
2965   RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2966   RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2967 }
2968
2969 #define GET_REGISTER_MATCHER
2970 #define GET_MATCHER_IMPLEMENTATION
2971 #define GET_SUBTARGET_FEATURE_NAME
2972 #include "X86GenAsmMatcher.inc"