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