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