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