ARM64: Refactor away a few redundant helpers.
[oota-llvm.git] / lib / Target / ARM64 / AsmParser / ARM64AsmParser.cpp
1 //===-- ARM64AsmParser.cpp - Parse ARM64 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/ARM64AddressingModes.h"
11 #include "MCTargetDesc/ARM64MCExpr.h"
12 #include "Utils/ARM64BaseInfo.h"
13 #include "llvm/MC/MCParser/MCAsmLexer.h"
14 #include "llvm/MC/MCParser/MCAsmParser.h"
15 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCExpr.h"
18 #include "llvm/MC/MCInst.h"
19 #include "llvm/MC/MCRegisterInfo.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/MC/MCSubtargetInfo.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/MC/MCTargetAsmParser.h"
24 #include "llvm/Support/SourceMgr.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include <cstdio>
34 using namespace llvm;
35
36 namespace {
37
38 class ARM64Operand;
39
40 class ARM64AsmParser : public MCTargetAsmParser {
41 public:
42   typedef SmallVectorImpl<MCParsedAsmOperand *> OperandVector;
43
44 private:
45   StringRef Mnemonic; ///< Instruction mnemonic.
46   MCSubtargetInfo &STI;
47   MCAsmParser &Parser;
48
49   MCAsmParser &getParser() const { return Parser; }
50   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
51
52   SMLoc getLoc() const { return Parser.getTok().getLoc(); }
53
54   bool parseSysAlias(StringRef Name, SMLoc NameLoc, OperandVector &Operands);
55   unsigned parseCondCodeString(StringRef Cond);
56   bool parseCondCode(OperandVector &Operands, bool invertCondCode);
57   int tryParseRegister();
58   int tryMatchVectorRegister(StringRef &Kind, bool expected);
59   bool parseOptionalShift(OperandVector &Operands);
60   bool parseOptionalExtend(OperandVector &Operands);
61   bool parseRegister(OperandVector &Operands);
62   bool parseMemory(OperandVector &Operands);
63   bool parseSymbolicImmVal(const MCExpr *&ImmVal);
64   bool parseVectorList(OperandVector &Operands);
65   bool parseOperand(OperandVector &Operands, bool isCondCode,
66                     bool invertCondCode);
67
68   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
69   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
70   bool showMatchError(SMLoc Loc, unsigned ErrCode);
71
72   bool parseDirectiveWord(unsigned Size, SMLoc L);
73   bool parseDirectiveTLSDescCall(SMLoc L);
74
75   bool parseDirectiveLOH(StringRef LOH, SMLoc L);
76
77   bool validateInstruction(MCInst &Inst, SmallVectorImpl<SMLoc> &Loc);
78   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
79                                OperandVector &Operands, MCStreamer &Out,
80                                unsigned &ErrorInfo, bool MatchingInlineAsm);
81 /// @name Auto-generated Match Functions
82 /// {
83
84 #define GET_ASSEMBLER_HEADER
85 #include "ARM64GenAsmMatcher.inc"
86
87   /// }
88
89   OperandMatchResultTy tryParseNoIndexMemory(OperandVector &Operands);
90   OperandMatchResultTy tryParseBarrierOperand(OperandVector &Operands);
91   OperandMatchResultTy tryParseMRSSystemRegister(OperandVector &Operands);
92   OperandMatchResultTy tryParseSysReg(OperandVector &Operands);
93   OperandMatchResultTy tryParseSysCROperand(OperandVector &Operands);
94   OperandMatchResultTy tryParsePrefetch(OperandVector &Operands);
95   OperandMatchResultTy tryParseAdrpLabel(OperandVector &Operands);
96   OperandMatchResultTy tryParseAdrLabel(OperandVector &Operands);
97   OperandMatchResultTy tryParseFPImm(OperandVector &Operands);
98   bool tryParseVectorRegister(OperandVector &Operands);
99
100 public:
101   enum ARM64MatchResultTy {
102     Match_InvalidSuffix = FIRST_TARGET_MATCH_RESULT_TY,
103 #define GET_OPERAND_DIAGNOSTIC_TYPES
104 #include "ARM64GenAsmMatcher.inc"
105   };
106   ARM64AsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser,
107                  const MCInstrInfo &MII)
108       : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
109     MCAsmParserExtension::Initialize(_Parser);
110   }
111
112   virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
113                                 SMLoc NameLoc, OperandVector &Operands);
114   virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
115   virtual bool ParseDirective(AsmToken DirectiveID);
116   unsigned validateTargetOperandClass(MCParsedAsmOperand *Op, unsigned Kind);
117
118   static bool classifySymbolRef(const MCExpr *Expr,
119                                 ARM64MCExpr::VariantKind &ELFRefKind,
120                                 MCSymbolRefExpr::VariantKind &DarwinRefKind,
121                                 const MCConstantExpr *&Addend);
122 };
123 } // end anonymous namespace
124
125 namespace {
126
127 /// ARM64Operand - Instances of this class represent a parsed ARM64 machine
128 /// instruction.
129 class ARM64Operand : public MCParsedAsmOperand {
130 public:
131   enum MemIdxKindTy {
132     ImmediateOffset, // pre-indexed, no writeback
133     RegisterOffset   // register offset, with optional extend
134   };
135
136 private:
137   enum KindTy {
138     k_Immediate,
139     k_Memory,
140     k_Register,
141     k_VectorList,
142     k_VectorIndex,
143     k_Token,
144     k_SysReg,
145     k_SysCR,
146     k_Prefetch,
147     k_Shifter,
148     k_Extend,
149     k_FPImm,
150     k_Barrier
151   } Kind;
152
153   SMLoc StartLoc, EndLoc, OffsetLoc;
154
155   struct TokOp {
156     const char *Data;
157     unsigned Length;
158     bool IsSuffix; // Is the operand actually a suffix on the mnemonic.
159   };
160
161   struct RegOp {
162     unsigned RegNum;
163     bool isVector;
164   };
165
166   struct VectorListOp {
167     unsigned RegNum;
168     unsigned Count;
169     unsigned NumElements;
170     unsigned ElementKind;
171   };
172
173   struct VectorIndexOp {
174     unsigned Val;
175   };
176
177   struct ImmOp {
178     const MCExpr *Val;
179   };
180
181   struct FPImmOp {
182     unsigned Val; // Encoded 8-bit representation.
183   };
184
185   struct BarrierOp {
186     unsigned Val; // Not the enum since not all values have names.
187   };
188
189   struct SysRegOp {
190     const char *Data;
191     unsigned Length;
192   };
193
194   struct SysCRImmOp {
195     unsigned Val;
196   };
197
198   struct PrefetchOp {
199     unsigned Val;
200   };
201
202   struct ShifterOp {
203     unsigned Val;
204   };
205
206   struct ExtendOp {
207     unsigned Val;
208   };
209
210   // This is for all forms of ARM64 address expressions
211   struct MemOp {
212     unsigned BaseRegNum, OffsetRegNum;
213     ARM64_AM::ExtendType ExtType;
214     unsigned ShiftVal;
215     bool ExplicitShift;
216     const MCExpr *OffsetImm;
217     MemIdxKindTy Mode;
218   };
219
220   union {
221     struct TokOp Tok;
222     struct RegOp Reg;
223     struct VectorListOp VectorList;
224     struct VectorIndexOp VectorIndex;
225     struct ImmOp Imm;
226     struct FPImmOp FPImm;
227     struct BarrierOp Barrier;
228     struct SysRegOp SysReg;
229     struct SysCRImmOp SysCRImm;
230     struct PrefetchOp Prefetch;
231     struct ShifterOp Shifter;
232     struct ExtendOp Extend;
233     struct MemOp Mem;
234   };
235
236   // Keep the MCContext around as the MCExprs may need manipulated during
237   // the add<>Operands() calls.
238   MCContext &Ctx;
239
240   ARM64Operand(KindTy K, MCContext &_Ctx)
241       : MCParsedAsmOperand(), Kind(K), Ctx(_Ctx) {}
242
243 public:
244   ARM64Operand(const ARM64Operand &o) : MCParsedAsmOperand(), Ctx(o.Ctx) {
245     Kind = o.Kind;
246     StartLoc = o.StartLoc;
247     EndLoc = o.EndLoc;
248     switch (Kind) {
249     case k_Token:
250       Tok = o.Tok;
251       break;
252     case k_Immediate:
253       Imm = o.Imm;
254       break;
255     case k_FPImm:
256       FPImm = o.FPImm;
257       break;
258     case k_Barrier:
259       Barrier = o.Barrier;
260       break;
261     case k_Register:
262       Reg = o.Reg;
263       break;
264     case k_VectorList:
265       VectorList = o.VectorList;
266       break;
267     case k_VectorIndex:
268       VectorIndex = o.VectorIndex;
269       break;
270     case k_SysReg:
271       SysReg = o.SysReg;
272       break;
273     case k_SysCR:
274       SysCRImm = o.SysCRImm;
275       break;
276     case k_Prefetch:
277       Prefetch = o.Prefetch;
278       break;
279     case k_Memory:
280       Mem = o.Mem;
281       break;
282     case k_Shifter:
283       Shifter = o.Shifter;
284       break;
285     case k_Extend:
286       Extend = o.Extend;
287       break;
288     }
289   }
290
291   /// getStartLoc - Get the location of the first token of this operand.
292   SMLoc getStartLoc() const { return StartLoc; }
293   /// getEndLoc - Get the location of the last token of this operand.
294   SMLoc getEndLoc() const { return EndLoc; }
295   /// getOffsetLoc - Get the location of the offset of this memory operand.
296   SMLoc getOffsetLoc() const { return OffsetLoc; }
297
298   StringRef getToken() const {
299     assert(Kind == k_Token && "Invalid access!");
300     return StringRef(Tok.Data, Tok.Length);
301   }
302
303   bool isTokenSuffix() const {
304     assert(Kind == k_Token && "Invalid access!");
305     return Tok.IsSuffix;
306   }
307
308   const MCExpr *getImm() const {
309     assert(Kind == k_Immediate && "Invalid access!");
310     return Imm.Val;
311   }
312
313   unsigned getFPImm() const {
314     assert(Kind == k_FPImm && "Invalid access!");
315     return FPImm.Val;
316   }
317
318   unsigned getBarrier() const {
319     assert(Kind == k_Barrier && "Invalid access!");
320     return Barrier.Val;
321   }
322
323   unsigned getReg() const {
324     assert(Kind == k_Register && "Invalid access!");
325     return Reg.RegNum;
326   }
327
328   unsigned getVectorListStart() const {
329     assert(Kind == k_VectorList && "Invalid access!");
330     return VectorList.RegNum;
331   }
332
333   unsigned getVectorListCount() const {
334     assert(Kind == k_VectorList && "Invalid access!");
335     return VectorList.Count;
336   }
337
338   unsigned getVectorIndex() const {
339     assert(Kind == k_VectorIndex && "Invalid access!");
340     return VectorIndex.Val;
341   }
342
343   StringRef getSysReg() const {
344     assert(Kind == k_SysReg && "Invalid access!");
345     return StringRef(SysReg.Data, SysReg.Length);
346   }
347
348   unsigned getSysCR() const {
349     assert(Kind == k_SysCR && "Invalid access!");
350     return SysCRImm.Val;
351   }
352
353   unsigned getPrefetch() const {
354     assert(Kind == k_Prefetch && "Invalid access!");
355     return Prefetch.Val;
356   }
357
358   unsigned getShifter() const {
359     assert(Kind == k_Shifter && "Invalid access!");
360     return Shifter.Val;
361   }
362
363   unsigned getExtend() const {
364     assert(Kind == k_Extend && "Invalid access!");
365     return Extend.Val;
366   }
367
368   bool isImm() const { return Kind == k_Immediate; }
369   bool isSImm9() const {
370     if (!isImm())
371       return false;
372     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
373     if (!MCE)
374       return false;
375     int64_t Val = MCE->getValue();
376     return (Val >= -256 && Val < 256);
377   }
378   bool isSImm7s4() const {
379     if (!isImm())
380       return false;
381     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
382     if (!MCE)
383       return false;
384     int64_t Val = MCE->getValue();
385     return (Val >= -256 && Val <= 252 && (Val & 3) == 0);
386   }
387   bool isSImm7s8() const {
388     if (!isImm())
389       return false;
390     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
391     if (!MCE)
392       return false;
393     int64_t Val = MCE->getValue();
394     return (Val >= -512 && Val <= 504 && (Val & 7) == 0);
395   }
396   bool isSImm7s16() const {
397     if (!isImm())
398       return false;
399     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
400     if (!MCE)
401       return false;
402     int64_t Val = MCE->getValue();
403     return (Val >= -1024 && Val <= 1008 && (Val & 15) == 0);
404   }
405   bool isImm0_7() const {
406     if (!isImm())
407       return false;
408     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
409     if (!MCE)
410       return false;
411     int64_t Val = MCE->getValue();
412     return (Val >= 0 && Val < 8);
413   }
414   bool isImm1_8() const {
415     if (!isImm())
416       return false;
417     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
418     if (!MCE)
419       return false;
420     int64_t Val = MCE->getValue();
421     return (Val > 0 && Val < 9);
422   }
423   bool isImm0_15() const {
424     if (!isImm())
425       return false;
426     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
427     if (!MCE)
428       return false;
429     int64_t Val = MCE->getValue();
430     return (Val >= 0 && Val < 16);
431   }
432   bool isImm1_16() const {
433     if (!isImm())
434       return false;
435     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
436     if (!MCE)
437       return false;
438     int64_t Val = MCE->getValue();
439     return (Val > 0 && Val < 17);
440   }
441   bool isImm0_31() const {
442     if (!isImm())
443       return false;
444     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
445     if (!MCE)
446       return false;
447     int64_t Val = MCE->getValue();
448     return (Val >= 0 && Val < 32);
449   }
450   bool isImm1_31() const {
451     if (!isImm())
452       return false;
453     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
454     if (!MCE)
455       return false;
456     int64_t Val = MCE->getValue();
457     return (Val >= 1 && Val < 32);
458   }
459   bool isImm1_32() const {
460     if (!isImm())
461       return false;
462     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
463     if (!MCE)
464       return false;
465     int64_t Val = MCE->getValue();
466     return (Val >= 1 && Val < 33);
467   }
468   bool isImm0_63() const {
469     if (!isImm())
470       return false;
471     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
472     if (!MCE)
473       return false;
474     int64_t Val = MCE->getValue();
475     return (Val >= 0 && Val < 64);
476   }
477   bool isImm1_63() const {
478     if (!isImm())
479       return false;
480     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
481     if (!MCE)
482       return false;
483     int64_t Val = MCE->getValue();
484     return (Val >= 1 && Val < 64);
485   }
486   bool isImm1_64() const {
487     if (!isImm())
488       return false;
489     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
490     if (!MCE)
491       return false;
492     int64_t Val = MCE->getValue();
493     return (Val >= 1 && Val < 65);
494   }
495   bool isImm0_127() const {
496     if (!isImm())
497       return false;
498     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
499     if (!MCE)
500       return false;
501     int64_t Val = MCE->getValue();
502     return (Val >= 0 && Val < 128);
503   }
504   bool isImm0_255() const {
505     if (!isImm())
506       return false;
507     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
508     if (!MCE)
509       return false;
510     int64_t Val = MCE->getValue();
511     return (Val >= 0 && Val < 256);
512   }
513   bool isImm0_65535() const {
514     if (!isImm())
515       return false;
516     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
517     if (!MCE)
518       return false;
519     int64_t Val = MCE->getValue();
520     return (Val >= 0 && Val < 65536);
521   }
522   bool isLogicalImm32() const {
523     if (!isImm())
524       return false;
525     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
526     if (!MCE)
527       return false;
528     return ARM64_AM::isLogicalImmediate(MCE->getValue(), 32);
529   }
530   bool isLogicalImm64() const {
531     if (!isImm())
532       return false;
533     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
534     if (!MCE)
535       return false;
536     return ARM64_AM::isLogicalImmediate(MCE->getValue(), 64);
537   }
538   bool isSIMDImmType10() const {
539     if (!isImm())
540       return false;
541     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
542     if (!MCE)
543       return false;
544     return ARM64_AM::isAdvSIMDModImmType10(MCE->getValue());
545   }
546   bool isBranchTarget26() const {
547     if (!isImm())
548       return false;
549     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
550     if (!MCE)
551       return true;
552     int64_t Val = MCE->getValue();
553     if (Val & 0x3)
554       return false;
555     return (Val >= -(0x2000000 << 2) && Val <= (0x1ffffff << 2));
556   }
557   bool isBranchTarget19() const {
558     if (!isImm())
559       return false;
560     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
561     if (!MCE)
562       return true;
563     int64_t Val = MCE->getValue();
564     if (Val & 0x3)
565       return false;
566     return (Val >= -(0x40000 << 2) && Val <= (0x3ffff << 2));
567   }
568   bool isBranchTarget14() const {
569     if (!isImm())
570       return false;
571     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
572     if (!MCE)
573       return true;
574     int64_t Val = MCE->getValue();
575     if (Val & 0x3)
576       return false;
577     return (Val >= -(0x2000 << 2) && Val <= (0x1fff << 2));
578   }
579
580   bool isMovWSymbol(ArrayRef<ARM64MCExpr::VariantKind> AllowedModifiers) const {
581     if (!isImm())
582       return false;
583
584     ARM64MCExpr::VariantKind ELFRefKind;
585     MCSymbolRefExpr::VariantKind DarwinRefKind;
586     const MCConstantExpr *Addend;
587     if (!ARM64AsmParser::classifySymbolRef(getImm(), ELFRefKind, DarwinRefKind,
588                                            Addend)) {
589       return false;
590     }
591     if (DarwinRefKind != MCSymbolRefExpr::VK_None)
592       return false;
593
594     for (unsigned i = 0; i != AllowedModifiers.size(); ++i) {
595       if (ELFRefKind == AllowedModifiers[i])
596         return Addend == 0;
597     }
598
599     return false;
600   }
601
602   bool isMovZSymbolG3() const {
603     static ARM64MCExpr::VariantKind Variants[] = { ARM64MCExpr::VK_ABS_G3 };
604     return isMovWSymbol(Variants);
605   }
606
607   bool isMovZSymbolG2() const {
608     static ARM64MCExpr::VariantKind Variants[] = { ARM64MCExpr::VK_ABS_G2,
609                                                    ARM64MCExpr::VK_TPREL_G2,
610                                                    ARM64MCExpr::VK_DTPREL_G2 };
611     return isMovWSymbol(Variants);
612   }
613
614   bool isMovZSymbolG1() const {
615     static ARM64MCExpr::VariantKind Variants[] = { ARM64MCExpr::VK_ABS_G1,
616                                                    ARM64MCExpr::VK_GOTTPREL_G1,
617                                                    ARM64MCExpr::VK_TPREL_G1,
618                                                    ARM64MCExpr::VK_DTPREL_G1, };
619     return isMovWSymbol(Variants);
620   }
621
622   bool isMovZSymbolG0() const {
623     static ARM64MCExpr::VariantKind Variants[] = { ARM64MCExpr::VK_ABS_G0,
624                                                    ARM64MCExpr::VK_TPREL_G0,
625                                                    ARM64MCExpr::VK_DTPREL_G0 };
626     return isMovWSymbol(Variants);
627   }
628
629   bool isMovKSymbolG2() const {
630     static ARM64MCExpr::VariantKind Variants[] = { ARM64MCExpr::VK_ABS_G2_NC };
631     return isMovWSymbol(Variants);
632   }
633
634   bool isMovKSymbolG1() const {
635     static ARM64MCExpr::VariantKind Variants[] = {
636       ARM64MCExpr::VK_ABS_G1_NC, ARM64MCExpr::VK_TPREL_G1_NC,
637       ARM64MCExpr::VK_DTPREL_G1_NC
638     };
639     return isMovWSymbol(Variants);
640   }
641
642   bool isMovKSymbolG0() const {
643     static ARM64MCExpr::VariantKind Variants[] = {
644       ARM64MCExpr::VK_ABS_G0_NC,   ARM64MCExpr::VK_GOTTPREL_G0_NC,
645       ARM64MCExpr::VK_TPREL_G0_NC, ARM64MCExpr::VK_DTPREL_G0_NC
646     };
647     return isMovWSymbol(Variants);
648   }
649
650   bool isFPImm() const { return Kind == k_FPImm; }
651   bool isBarrier() const { return Kind == k_Barrier; }
652   bool isSysReg() const { return Kind == k_SysReg; }
653   bool isMRSSystemRegister() const {
654     if (!isSysReg()) return false;
655
656     bool IsKnownRegister;
657     ARM64SysReg::MRSMapper().fromString(getSysReg(), IsKnownRegister);
658
659     return IsKnownRegister;
660   }
661   bool isMSRSystemRegister() const {
662     if (!isSysReg()) return false;
663
664     bool IsKnownRegister;
665     ARM64SysReg::MSRMapper().fromString(getSysReg(), IsKnownRegister);
666
667     return IsKnownRegister;
668   }
669   bool isSystemCPSRField() const {
670     if (!isSysReg()) return false;
671
672     bool IsKnownRegister;
673     ARM64PState::PStateMapper().fromString(getSysReg(), IsKnownRegister);
674
675     return IsKnownRegister;
676   }
677   bool isReg() const { return Kind == k_Register && !Reg.isVector; }
678   bool isVectorReg() const { return Kind == k_Register && Reg.isVector; }
679
680   /// Is this a vector list with the type implicit (presumably attached to the
681   /// instruction itself)?
682   template <unsigned NumRegs> bool isImplicitlyTypedVectorList() const {
683     return Kind == k_VectorList && VectorList.Count == NumRegs &&
684            !VectorList.ElementKind;
685   }
686
687   template <unsigned NumRegs, unsigned NumElements, char ElementKind>
688   bool isTypedVectorList() const {
689     if (Kind != k_VectorList)
690       return false;
691     if (VectorList.Count != NumRegs)
692       return false;
693     if (VectorList.ElementKind != ElementKind)
694       return false;
695     return VectorList.NumElements == NumElements;
696   }
697
698   bool isVectorIndexB() const {
699     return Kind == k_VectorIndex && VectorIndex.Val < 16;
700   }
701   bool isVectorIndexH() const {
702     return Kind == k_VectorIndex && VectorIndex.Val < 8;
703   }
704   bool isVectorIndexS() const {
705     return Kind == k_VectorIndex && VectorIndex.Val < 4;
706   }
707   bool isVectorIndexD() const {
708     return Kind == k_VectorIndex && VectorIndex.Val < 2;
709   }
710   bool isToken() const { return Kind == k_Token; }
711   bool isTokenEqual(StringRef Str) const {
712     return Kind == k_Token && getToken() == Str;
713   }
714   bool isMem() const { return Kind == k_Memory; }
715   bool isSysCR() const { return Kind == k_SysCR; }
716   bool isPrefetch() const { return Kind == k_Prefetch; }
717   bool isShifter() const { return Kind == k_Shifter; }
718   bool isExtend() const {
719     // lsl is an alias for UXTW but will be a parsed as a k_Shifter operand.
720     if (isShifter()) {
721       ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(Shifter.Val);
722       return ST == ARM64_AM::LSL;
723     }
724     return Kind == k_Extend;
725   }
726   bool isExtend64() const {
727     if (Kind != k_Extend)
728       return false;
729     // UXTX and SXTX require a 64-bit source register (the ExtendLSL64 class).
730     ARM64_AM::ExtendType ET = ARM64_AM::getArithExtendType(Extend.Val);
731     return ET != ARM64_AM::UXTX && ET != ARM64_AM::SXTX;
732   }
733   bool isExtendLSL64() const {
734     // lsl is an alias for UXTX but will be a parsed as a k_Shifter operand.
735     if (isShifter()) {
736       ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(Shifter.Val);
737       return ST == ARM64_AM::LSL;
738     }
739     if (Kind != k_Extend)
740       return false;
741     ARM64_AM::ExtendType ET = ARM64_AM::getArithExtendType(Extend.Val);
742     return ET == ARM64_AM::UXTX || ET == ARM64_AM::SXTX;
743   }
744
745   bool isArithmeticShifter() const {
746     if (!isShifter())
747       return false;
748
749     // An arithmetic shifter is LSL, LSR, or ASR.
750     ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(Shifter.Val);
751     return ST == ARM64_AM::LSL || ST == ARM64_AM::LSR || ST == ARM64_AM::ASR;
752   }
753
754   bool isMovImm32Shifter() const {
755     if (!isShifter())
756       return false;
757
758     // A MOVi shifter is LSL of 0, 16, 32, or 48.
759     ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(Shifter.Val);
760     if (ST != ARM64_AM::LSL)
761       return false;
762     uint64_t Val = ARM64_AM::getShiftValue(Shifter.Val);
763     return (Val == 0 || Val == 16);
764   }
765
766   bool isMovImm64Shifter() const {
767     if (!isShifter())
768       return false;
769
770     // A MOVi shifter is LSL of 0 or 16.
771     ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(Shifter.Val);
772     if (ST != ARM64_AM::LSL)
773       return false;
774     uint64_t Val = ARM64_AM::getShiftValue(Shifter.Val);
775     return (Val == 0 || Val == 16 || Val == 32 || Val == 48);
776   }
777
778   bool isAddSubShifter() const {
779     if (!isShifter())
780       return false;
781
782     // An ADD/SUB shifter is either 'lsl #0' or 'lsl #12'.
783     unsigned Val = Shifter.Val;
784     return ARM64_AM::getShiftType(Val) == ARM64_AM::LSL &&
785            (ARM64_AM::getShiftValue(Val) == 0 ||
786             ARM64_AM::getShiftValue(Val) == 12);
787   }
788
789   bool isLogicalVecShifter() const {
790     if (!isShifter())
791       return false;
792
793     // A logical vector shifter is a left shift by 0, 8, 16, or 24.
794     unsigned Val = Shifter.Val;
795     unsigned Shift = ARM64_AM::getShiftValue(Val);
796     return ARM64_AM::getShiftType(Val) == ARM64_AM::LSL &&
797            (Shift == 0 || Shift == 8 || Shift == 16 || Shift == 24);
798   }
799
800   bool isLogicalVecHalfWordShifter() const {
801     if (!isLogicalVecShifter())
802       return false;
803
804     // A logical vector shifter is a left shift by 0 or 8.
805     unsigned Val = Shifter.Val;
806     unsigned Shift = ARM64_AM::getShiftValue(Val);
807     return ARM64_AM::getShiftType(Val) == ARM64_AM::LSL &&
808            (Shift == 0 || Shift == 8);
809   }
810
811   bool isMoveVecShifter() const {
812     if (!isShifter())
813       return false;
814
815     // A logical vector shifter is a left shift by 8 or 16.
816     unsigned Val = Shifter.Val;
817     unsigned Shift = ARM64_AM::getShiftValue(Val);
818     return ARM64_AM::getShiftType(Val) == ARM64_AM::MSL &&
819            (Shift == 8 || Shift == 16);
820   }
821
822   bool isMemoryRegisterOffset8() const {
823     return isMem() && Mem.Mode == RegisterOffset && Mem.ShiftVal == 0;
824   }
825
826   bool isMemoryRegisterOffset16() const {
827     return isMem() && Mem.Mode == RegisterOffset &&
828            (Mem.ShiftVal == 0 || Mem.ShiftVal == 1);
829   }
830
831   bool isMemoryRegisterOffset32() const {
832     return isMem() && Mem.Mode == RegisterOffset &&
833            (Mem.ShiftVal == 0 || Mem.ShiftVal == 2);
834   }
835
836   bool isMemoryRegisterOffset64() const {
837     return isMem() && Mem.Mode == RegisterOffset &&
838            (Mem.ShiftVal == 0 || Mem.ShiftVal == 3);
839   }
840
841   bool isMemoryRegisterOffset128() const {
842     return isMem() && Mem.Mode == RegisterOffset &&
843            (Mem.ShiftVal == 0 || Mem.ShiftVal == 4);
844   }
845
846   bool isMemoryUnscaled() const {
847     if (!isMem())
848       return false;
849     if (Mem.Mode != ImmediateOffset)
850       return false;
851     if (!Mem.OffsetImm)
852       return true;
853     // Make sure the immediate value is valid.
854     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
855     if (!CE)
856       return false;
857     // The offset must fit in a signed 9-bit unscaled immediate.
858     int64_t Value = CE->getValue();
859     return (Value >= -256 && Value < 256);
860   }
861   // Fallback unscaled operands are for aliases of LDR/STR that fall back
862   // to LDUR/STUR when the offset is not legal for the former but is for
863   // the latter. As such, in addition to checking for being a legal unscaled
864   // address, also check that it is not a legal scaled address. This avoids
865   // ambiguity in the matcher.
866   bool isMemoryUnscaledFB8() const {
867     return isMemoryUnscaled() && !isMemoryIndexed8();
868   }
869   bool isMemoryUnscaledFB16() const {
870     return isMemoryUnscaled() && !isMemoryIndexed16();
871   }
872   bool isMemoryUnscaledFB32() const {
873     return isMemoryUnscaled() && !isMemoryIndexed32();
874   }
875   bool isMemoryUnscaledFB64() const {
876     return isMemoryUnscaled() && !isMemoryIndexed64();
877   }
878   bool isMemoryUnscaledFB128() const {
879     return isMemoryUnscaled() && !isMemoryIndexed128();
880   }
881   bool isMemoryIndexed(unsigned Scale) const {
882     if (!isMem())
883       return false;
884     if (Mem.Mode != ImmediateOffset)
885       return false;
886     if (!Mem.OffsetImm)
887       return true;
888     // Make sure the immediate value is valid.
889     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
890
891     if (CE) {
892       // The offset must be a positive multiple of the scale and in range of
893       // encoding with a 12-bit immediate.
894       int64_t Value = CE->getValue();
895       return (Value >= 0 && (Value % Scale) == 0 && Value <= (4095 * Scale));
896     }
897
898     // If it's not a constant, check for some expressions we know.
899     const MCExpr *Expr = Mem.OffsetImm;
900     ARM64MCExpr::VariantKind ELFRefKind;
901     MCSymbolRefExpr::VariantKind DarwinRefKind;
902     const MCConstantExpr *Addend;
903     if (!ARM64AsmParser::classifySymbolRef(Expr, ELFRefKind, DarwinRefKind,
904                                            Addend)) {
905       // If we don't understand the expression, assume the best and
906       // let the fixup and relocation code deal with it.
907       return true;
908     }
909
910     if (DarwinRefKind == MCSymbolRefExpr::VK_PAGEOFF ||
911         ELFRefKind == ARM64MCExpr::VK_LO12 ||
912         ELFRefKind == ARM64MCExpr::VK_GOT_LO12 ||
913         ELFRefKind == ARM64MCExpr::VK_DTPREL_LO12 ||
914         ELFRefKind == ARM64MCExpr::VK_DTPREL_LO12_NC ||
915         ELFRefKind == ARM64MCExpr::VK_TPREL_LO12 ||
916         ELFRefKind == ARM64MCExpr::VK_TPREL_LO12_NC ||
917         ELFRefKind == ARM64MCExpr::VK_GOTTPREL_LO12_NC ||
918         ELFRefKind == ARM64MCExpr::VK_TLSDESC_LO12) {
919       // Note that we don't range-check the addend. It's adjusted modulo page
920       // size when converted, so there is no "out of range" condition when using
921       // @pageoff.
922       int64_t Value = Addend ? Addend->getValue() : 0;
923       return Value >= 0 && (Value % Scale) == 0;
924     } else if (DarwinRefKind == MCSymbolRefExpr::VK_GOTPAGEOFF ||
925                DarwinRefKind == MCSymbolRefExpr::VK_TLVPPAGEOFF) {
926       // @gotpageoff/@tlvppageoff can only be used directly, not with an addend.
927       return Addend == 0;
928     }
929
930     return false;
931   }
932   bool isMemoryIndexed128() const { return isMemoryIndexed(16); }
933   bool isMemoryIndexed64() const { return isMemoryIndexed(8); }
934   bool isMemoryIndexed32() const { return isMemoryIndexed(4); }
935   bool isMemoryIndexed16() const { return isMemoryIndexed(2); }
936   bool isMemoryIndexed8() const { return isMemoryIndexed(1); }
937   bool isMemoryNoIndex() const {
938     if (!isMem())
939       return false;
940     if (Mem.Mode != ImmediateOffset)
941       return false;
942     if (!Mem.OffsetImm)
943       return true;
944
945     // Make sure the immediate value is valid. Only zero is allowed.
946     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
947     if (!CE || CE->getValue() != 0)
948       return false;
949     return true;
950   }
951   bool isMemorySIMDNoIndex() const {
952     if (!isMem())
953       return false;
954     if (Mem.Mode != ImmediateOffset)
955       return false;
956     return Mem.OffsetImm == 0;
957   }
958   bool isMemoryIndexedSImm9() const {
959     if (!isMem() || Mem.Mode != ImmediateOffset)
960       return false;
961     if (!Mem.OffsetImm)
962       return true;
963     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
964     assert(CE && "Non-constant pre-indexed offset!");
965     int64_t Value = CE->getValue();
966     return Value >= -256 && Value <= 255;
967   }
968   bool isMemoryIndexed32SImm7() const {
969     if (!isMem() || Mem.Mode != ImmediateOffset)
970       return false;
971     if (!Mem.OffsetImm)
972       return true;
973     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
974     assert(CE && "Non-constant pre-indexed offset!");
975     int64_t Value = CE->getValue();
976     return ((Value % 4) == 0) && Value >= -256 && Value <= 252;
977   }
978   bool isMemoryIndexed64SImm7() const {
979     if (!isMem() || Mem.Mode != ImmediateOffset)
980       return false;
981     if (!Mem.OffsetImm)
982       return true;
983     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
984     assert(CE && "Non-constant pre-indexed offset!");
985     int64_t Value = CE->getValue();
986     return ((Value % 8) == 0) && Value >= -512 && Value <= 504;
987   }
988   bool isMemoryIndexed128SImm7() const {
989     if (!isMem() || Mem.Mode != ImmediateOffset)
990       return false;
991     if (!Mem.OffsetImm)
992       return true;
993     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
994     assert(CE && "Non-constant pre-indexed offset!");
995     int64_t Value = CE->getValue();
996     return ((Value % 16) == 0) && Value >= -1024 && Value <= 1008;
997   }
998
999   bool isAdrpLabel() const {
1000     // Validation was handled during parsing, so we just sanity check that
1001     // something didn't go haywire.
1002     if (!isImm())
1003         return false;
1004
1005     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1006       int64_t Val = CE->getValue();
1007       int64_t Min = - (4096 * (1LL << (21 - 1)));
1008       int64_t Max = 4096 * ((1LL << (21 - 1)) - 1);
1009       return (Val % 4096) == 0 && Val >= Min && Val <= Max;
1010     }
1011
1012     return true;
1013   }
1014
1015   bool isAdrLabel() const {
1016     // Validation was handled during parsing, so we just sanity check that
1017     // something didn't go haywire.
1018     if (!isImm())
1019         return false;
1020
1021     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1022       int64_t Val = CE->getValue();
1023       int64_t Min = - (1LL << (21 - 1));
1024       int64_t Max = ((1LL << (21 - 1)) - 1);
1025       return Val >= Min && Val <= Max;
1026     }
1027
1028     return true;
1029   }
1030
1031   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1032     // Add as immediates when possible.  Null MCExpr = 0.
1033     if (Expr == 0)
1034       Inst.addOperand(MCOperand::CreateImm(0));
1035     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1036       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1037     else
1038       Inst.addOperand(MCOperand::CreateExpr(Expr));
1039   }
1040
1041   void addRegOperands(MCInst &Inst, unsigned N) const {
1042     assert(N == 1 && "Invalid number of operands!");
1043     Inst.addOperand(MCOperand::CreateReg(getReg()));
1044   }
1045
1046   void addVectorRegOperands(MCInst &Inst, unsigned N) const {
1047     assert(N == 1 && "Invalid number of operands!");
1048     Inst.addOperand(MCOperand::CreateReg(getReg()));
1049   }
1050
1051   template <unsigned NumRegs>
1052   void addVectorList64Operands(MCInst &Inst, unsigned N) const {
1053     assert(N == 1 && "Invalid number of operands!");
1054     static unsigned FirstRegs[] = { ARM64::D0,       ARM64::D0_D1,
1055                                     ARM64::D0_D1_D2, ARM64::D0_D1_D2_D3 };
1056     unsigned FirstReg = FirstRegs[NumRegs - 1];
1057
1058     Inst.addOperand(
1059         MCOperand::CreateReg(FirstReg + getVectorListStart() - ARM64::Q0));
1060   }
1061
1062   template <unsigned NumRegs>
1063   void addVectorList128Operands(MCInst &Inst, unsigned N) const {
1064     assert(N == 1 && "Invalid number of operands!");
1065     static unsigned FirstRegs[] = { ARM64::Q0,       ARM64::Q0_Q1,
1066                                     ARM64::Q0_Q1_Q2, ARM64::Q0_Q1_Q2_Q3 };
1067     unsigned FirstReg = FirstRegs[NumRegs - 1];
1068
1069     Inst.addOperand(
1070         MCOperand::CreateReg(FirstReg + getVectorListStart() - ARM64::Q0));
1071   }
1072
1073   void addVectorIndexBOperands(MCInst &Inst, unsigned N) const {
1074     assert(N == 1 && "Invalid number of operands!");
1075     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1076   }
1077
1078   void addVectorIndexHOperands(MCInst &Inst, unsigned N) const {
1079     assert(N == 1 && "Invalid number of operands!");
1080     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1081   }
1082
1083   void addVectorIndexSOperands(MCInst &Inst, unsigned N) const {
1084     assert(N == 1 && "Invalid number of operands!");
1085     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1086   }
1087
1088   void addVectorIndexDOperands(MCInst &Inst, unsigned N) const {
1089     assert(N == 1 && "Invalid number of operands!");
1090     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
1091   }
1092
1093   void addImmOperands(MCInst &Inst, unsigned N) const {
1094     assert(N == 1 && "Invalid number of operands!");
1095     // If this is a pageoff symrefexpr with an addend, adjust the addend
1096     // to be only the page-offset portion. Otherwise, just add the expr
1097     // as-is.
1098     addExpr(Inst, getImm());
1099   }
1100
1101   void addAdrpLabelOperands(MCInst &Inst, unsigned N) const {
1102     assert(N == 1 && "Invalid number of operands!");
1103     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1104     if (!MCE)
1105       addExpr(Inst, getImm());
1106     else
1107       Inst.addOperand(MCOperand::CreateImm(MCE->getValue() >> 12));
1108   }
1109
1110   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
1111     addImmOperands(Inst, N);
1112   }
1113
1114   void addSImm9Operands(MCInst &Inst, unsigned N) const {
1115     assert(N == 1 && "Invalid number of operands!");
1116     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1117     assert(MCE && "Invalid constant immediate operand!");
1118     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1119   }
1120
1121   void addSImm7s4Operands(MCInst &Inst, unsigned N) const {
1122     assert(N == 1 && "Invalid number of operands!");
1123     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1124     assert(MCE && "Invalid constant immediate operand!");
1125     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() / 4));
1126   }
1127
1128   void addSImm7s8Operands(MCInst &Inst, unsigned N) const {
1129     assert(N == 1 && "Invalid number of operands!");
1130     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1131     assert(MCE && "Invalid constant immediate operand!");
1132     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() / 8));
1133   }
1134
1135   void addSImm7s16Operands(MCInst &Inst, unsigned N) const {
1136     assert(N == 1 && "Invalid number of operands!");
1137     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1138     assert(MCE && "Invalid constant immediate operand!");
1139     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() / 16));
1140   }
1141
1142   void addImm0_7Operands(MCInst &Inst, unsigned N) const {
1143     assert(N == 1 && "Invalid number of operands!");
1144     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1145     assert(MCE && "Invalid constant immediate operand!");
1146     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1147   }
1148
1149   void addImm1_8Operands(MCInst &Inst, unsigned N) const {
1150     assert(N == 1 && "Invalid number of operands!");
1151     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1152     assert(MCE && "Invalid constant immediate operand!");
1153     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1154   }
1155
1156   void addImm0_15Operands(MCInst &Inst, unsigned N) const {
1157     assert(N == 1 && "Invalid number of operands!");
1158     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1159     assert(MCE && "Invalid constant immediate operand!");
1160     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1161   }
1162
1163   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1164     assert(N == 1 && "Invalid number of operands!");
1165     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1166     assert(MCE && "Invalid constant immediate operand!");
1167     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1168   }
1169
1170   void addImm0_31Operands(MCInst &Inst, unsigned N) const {
1171     assert(N == 1 && "Invalid number of operands!");
1172     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1173     assert(MCE && "Invalid constant immediate operand!");
1174     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1175   }
1176
1177   void addImm1_31Operands(MCInst &Inst, unsigned N) const {
1178     assert(N == 1 && "Invalid number of operands!");
1179     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1180     assert(MCE && "Invalid constant immediate operand!");
1181     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1182   }
1183
1184   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1185     assert(N == 1 && "Invalid number of operands!");
1186     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1187     assert(MCE && "Invalid constant immediate operand!");
1188     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1189   }
1190
1191   void addImm0_63Operands(MCInst &Inst, unsigned N) const {
1192     assert(N == 1 && "Invalid number of operands!");
1193     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1194     assert(MCE && "Invalid constant immediate operand!");
1195     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1196   }
1197
1198   void addImm1_63Operands(MCInst &Inst, unsigned N) const {
1199     assert(N == 1 && "Invalid number of operands!");
1200     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1201     assert(MCE && "Invalid constant immediate operand!");
1202     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1203   }
1204
1205   void addImm1_64Operands(MCInst &Inst, unsigned N) const {
1206     assert(N == 1 && "Invalid number of operands!");
1207     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1208     assert(MCE && "Invalid constant immediate operand!");
1209     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1210   }
1211
1212   void addImm0_127Operands(MCInst &Inst, unsigned N) const {
1213     assert(N == 1 && "Invalid number of operands!");
1214     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1215     assert(MCE && "Invalid constant immediate operand!");
1216     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1217   }
1218
1219   void addImm0_255Operands(MCInst &Inst, unsigned N) const {
1220     assert(N == 1 && "Invalid number of operands!");
1221     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1222     assert(MCE && "Invalid constant immediate operand!");
1223     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1224   }
1225
1226   void addImm0_65535Operands(MCInst &Inst, unsigned N) const {
1227     assert(N == 1 && "Invalid number of operands!");
1228     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1229     assert(MCE && "Invalid constant immediate operand!");
1230     Inst.addOperand(MCOperand::CreateImm(MCE->getValue()));
1231   }
1232
1233   void addLogicalImm32Operands(MCInst &Inst, unsigned N) const {
1234     assert(N == 1 && "Invalid number of operands!");
1235     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1236     assert(MCE && "Invalid logical immediate operand!");
1237     uint64_t encoding = ARM64_AM::encodeLogicalImmediate(MCE->getValue(), 32);
1238     Inst.addOperand(MCOperand::CreateImm(encoding));
1239   }
1240
1241   void addLogicalImm64Operands(MCInst &Inst, unsigned N) const {
1242     assert(N == 1 && "Invalid number of operands!");
1243     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1244     assert(MCE && "Invalid logical immediate operand!");
1245     uint64_t encoding = ARM64_AM::encodeLogicalImmediate(MCE->getValue(), 64);
1246     Inst.addOperand(MCOperand::CreateImm(encoding));
1247   }
1248
1249   void addSIMDImmType10Operands(MCInst &Inst, unsigned N) const {
1250     assert(N == 1 && "Invalid number of operands!");
1251     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1252     assert(MCE && "Invalid immediate operand!");
1253     uint64_t encoding = ARM64_AM::encodeAdvSIMDModImmType10(MCE->getValue());
1254     Inst.addOperand(MCOperand::CreateImm(encoding));
1255   }
1256
1257   void addBranchTarget26Operands(MCInst &Inst, unsigned N) const {
1258     // Branch operands don't encode the low bits, so shift them off
1259     // here. If it's a label, however, just put it on directly as there's
1260     // not enough information now to do anything.
1261     assert(N == 1 && "Invalid number of operands!");
1262     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1263     if (!MCE) {
1264       addExpr(Inst, getImm());
1265       return;
1266     }
1267     assert(MCE && "Invalid constant immediate operand!");
1268     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() >> 2));
1269   }
1270
1271   void addBranchTarget19Operands(MCInst &Inst, unsigned N) const {
1272     // Branch operands don't encode the low bits, so shift them off
1273     // here. If it's a label, however, just put it on directly as there's
1274     // not enough information now to do anything.
1275     assert(N == 1 && "Invalid number of operands!");
1276     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1277     if (!MCE) {
1278       addExpr(Inst, getImm());
1279       return;
1280     }
1281     assert(MCE && "Invalid constant immediate operand!");
1282     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() >> 2));
1283   }
1284
1285   void addBranchTarget14Operands(MCInst &Inst, unsigned N) const {
1286     // Branch operands don't encode the low bits, so shift them off
1287     // here. If it's a label, however, just put it on directly as there's
1288     // not enough information now to do anything.
1289     assert(N == 1 && "Invalid number of operands!");
1290     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(getImm());
1291     if (!MCE) {
1292       addExpr(Inst, getImm());
1293       return;
1294     }
1295     assert(MCE && "Invalid constant immediate operand!");
1296     Inst.addOperand(MCOperand::CreateImm(MCE->getValue() >> 2));
1297   }
1298
1299   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1300     assert(N == 1 && "Invalid number of operands!");
1301     Inst.addOperand(MCOperand::CreateImm(getFPImm()));
1302   }
1303
1304   void addBarrierOperands(MCInst &Inst, unsigned N) const {
1305     assert(N == 1 && "Invalid number of operands!");
1306     Inst.addOperand(MCOperand::CreateImm(getBarrier()));
1307   }
1308
1309   void addMRSSystemRegisterOperands(MCInst &Inst, unsigned N) const {
1310     assert(N == 1 && "Invalid number of operands!");
1311
1312     bool Valid;
1313     uint32_t Bits = ARM64SysReg::MRSMapper().fromString(getSysReg(), Valid);
1314
1315     Inst.addOperand(MCOperand::CreateImm(Bits));
1316   }
1317
1318   void addMSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
1319     assert(N == 1 && "Invalid number of operands!");
1320
1321     bool Valid;
1322     uint32_t Bits = ARM64SysReg::MSRMapper().fromString(getSysReg(), Valid);
1323
1324     Inst.addOperand(MCOperand::CreateImm(Bits));
1325   }
1326
1327   void addSystemCPSRFieldOperands(MCInst &Inst, unsigned N) const {
1328     assert(N == 1 && "Invalid number of operands!");
1329
1330     bool Valid;
1331     uint32_t Bits = ARM64PState::PStateMapper().fromString(getSysReg(), Valid);
1332
1333     Inst.addOperand(MCOperand::CreateImm(Bits));
1334   }
1335
1336   void addSysCROperands(MCInst &Inst, unsigned N) const {
1337     assert(N == 1 && "Invalid number of operands!");
1338     Inst.addOperand(MCOperand::CreateImm(getSysCR()));
1339   }
1340
1341   void addPrefetchOperands(MCInst &Inst, unsigned N) const {
1342     assert(N == 1 && "Invalid number of operands!");
1343     Inst.addOperand(MCOperand::CreateImm(getPrefetch()));
1344   }
1345
1346   void addShifterOperands(MCInst &Inst, unsigned N) const {
1347     assert(N == 1 && "Invalid number of operands!");
1348     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1349   }
1350
1351   void addArithmeticShifterOperands(MCInst &Inst, unsigned N) const {
1352     assert(N == 1 && "Invalid number of operands!");
1353     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1354   }
1355
1356   void addMovImm32ShifterOperands(MCInst &Inst, unsigned N) const {
1357     assert(N == 1 && "Invalid number of operands!");
1358     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1359   }
1360
1361   void addMovImm64ShifterOperands(MCInst &Inst, unsigned N) const {
1362     assert(N == 1 && "Invalid number of operands!");
1363     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1364   }
1365
1366   void addAddSubShifterOperands(MCInst &Inst, unsigned N) const {
1367     assert(N == 1 && "Invalid number of operands!");
1368     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1369   }
1370
1371   void addLogicalVecShifterOperands(MCInst &Inst, unsigned N) const {
1372     assert(N == 1 && "Invalid number of operands!");
1373     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1374   }
1375
1376   void addLogicalVecHalfWordShifterOperands(MCInst &Inst, unsigned N) const {
1377     assert(N == 1 && "Invalid number of operands!");
1378     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1379   }
1380
1381   void addMoveVecShifterOperands(MCInst &Inst, unsigned N) const {
1382     assert(N == 1 && "Invalid number of operands!");
1383     Inst.addOperand(MCOperand::CreateImm(getShifter()));
1384   }
1385
1386   void addExtendOperands(MCInst &Inst, unsigned N) const {
1387     assert(N == 1 && "Invalid number of operands!");
1388     // lsl is an alias for UXTW but will be a parsed as a k_Shifter operand.
1389     if (isShifter()) {
1390       assert(ARM64_AM::getShiftType(getShifter()) == ARM64_AM::LSL);
1391       unsigned imm = getArithExtendImm(ARM64_AM::UXTW,
1392                                        ARM64_AM::getShiftValue(getShifter()));
1393       Inst.addOperand(MCOperand::CreateImm(imm));
1394     } else
1395       Inst.addOperand(MCOperand::CreateImm(getExtend()));
1396   }
1397
1398   void addExtend64Operands(MCInst &Inst, unsigned N) const {
1399     assert(N == 1 && "Invalid number of operands!");
1400     Inst.addOperand(MCOperand::CreateImm(getExtend()));
1401   }
1402
1403   void addExtendLSL64Operands(MCInst &Inst, unsigned N) const {
1404     assert(N == 1 && "Invalid number of operands!");
1405     // lsl is an alias for UXTX but will be a parsed as a k_Shifter operand.
1406     if (isShifter()) {
1407       assert(ARM64_AM::getShiftType(getShifter()) == ARM64_AM::LSL);
1408       unsigned imm = getArithExtendImm(ARM64_AM::UXTX,
1409                                        ARM64_AM::getShiftValue(getShifter()));
1410       Inst.addOperand(MCOperand::CreateImm(imm));
1411     } else
1412       Inst.addOperand(MCOperand::CreateImm(getExtend()));
1413   }
1414
1415   void addMemoryRegisterOffsetOperands(MCInst &Inst, unsigned N, bool DoShift) {
1416     assert(N == 3 && "Invalid number of operands!");
1417
1418     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1419     Inst.addOperand(MCOperand::CreateReg(getXRegFromWReg(Mem.OffsetRegNum)));
1420     unsigned ExtendImm = ARM64_AM::getMemExtendImm(Mem.ExtType, DoShift);
1421     Inst.addOperand(MCOperand::CreateImm(ExtendImm));
1422   }
1423
1424   void addMemoryRegisterOffset8Operands(MCInst &Inst, unsigned N) {
1425     addMemoryRegisterOffsetOperands(Inst, N, Mem.ExplicitShift);
1426   }
1427
1428   void addMemoryRegisterOffset16Operands(MCInst &Inst, unsigned N) {
1429     addMemoryRegisterOffsetOperands(Inst, N, Mem.ShiftVal == 1);
1430   }
1431
1432   void addMemoryRegisterOffset32Operands(MCInst &Inst, unsigned N) {
1433     addMemoryRegisterOffsetOperands(Inst, N, Mem.ShiftVal == 2);
1434   }
1435
1436   void addMemoryRegisterOffset64Operands(MCInst &Inst, unsigned N) {
1437     addMemoryRegisterOffsetOperands(Inst, N, Mem.ShiftVal == 3);
1438   }
1439
1440   void addMemoryRegisterOffset128Operands(MCInst &Inst, unsigned N) {
1441     addMemoryRegisterOffsetOperands(Inst, N, Mem.ShiftVal == 4);
1442   }
1443
1444   void addMemoryIndexedOperands(MCInst &Inst, unsigned N,
1445                                 unsigned Scale) const {
1446     // Add the base register operand.
1447     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1448
1449     if (!Mem.OffsetImm) {
1450       // There isn't an offset.
1451       Inst.addOperand(MCOperand::CreateImm(0));
1452       return;
1453     }
1454
1455     // Add the offset operand.
1456     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm)) {
1457       assert(CE->getValue() % Scale == 0 &&
1458              "Offset operand must be multiple of the scale!");
1459
1460       // The MCInst offset operand doesn't include the low bits (like the
1461       // instruction encoding).
1462       Inst.addOperand(MCOperand::CreateImm(CE->getValue() / Scale));
1463     }
1464
1465     // If this is a pageoff symrefexpr with an addend, the linker will
1466     // do the scaling of the addend.
1467     //
1468     // Otherwise we don't know what this is, so just add the scaling divide to
1469     // the expression and let the MC fixup evaluation code deal with it.
1470     const MCExpr *Expr = Mem.OffsetImm;
1471     ARM64MCExpr::VariantKind ELFRefKind;
1472     MCSymbolRefExpr::VariantKind DarwinRefKind;
1473     const MCConstantExpr *Addend;
1474     if (Scale > 1 &&
1475         (!ARM64AsmParser::classifySymbolRef(Expr, ELFRefKind, DarwinRefKind,
1476                                             Addend) ||
1477          (Addend != 0 && DarwinRefKind != MCSymbolRefExpr::VK_PAGEOFF))) {
1478       Expr = MCBinaryExpr::CreateDiv(Expr, MCConstantExpr::Create(Scale, Ctx),
1479                                      Ctx);
1480     }
1481
1482     Inst.addOperand(MCOperand::CreateExpr(Expr));
1483   }
1484
1485   void addMemoryUnscaledOperands(MCInst &Inst, unsigned N) const {
1486     assert(N == 2 && isMemoryUnscaled() && "Invalid number of operands!");
1487     // Add the base register operand.
1488     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1489
1490     // Add the offset operand.
1491     if (!Mem.OffsetImm)
1492       Inst.addOperand(MCOperand::CreateImm(0));
1493     else {
1494       // Only constant offsets supported.
1495       const MCConstantExpr *CE = cast<MCConstantExpr>(Mem.OffsetImm);
1496       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1497     }
1498   }
1499
1500   void addMemoryIndexed128Operands(MCInst &Inst, unsigned N) const {
1501     assert(N == 2 && isMemoryIndexed128() && "Invalid number of operands!");
1502     addMemoryIndexedOperands(Inst, N, 16);
1503   }
1504
1505   void addMemoryIndexed64Operands(MCInst &Inst, unsigned N) const {
1506     assert(N == 2 && isMemoryIndexed64() && "Invalid number of operands!");
1507     addMemoryIndexedOperands(Inst, N, 8);
1508   }
1509
1510   void addMemoryIndexed32Operands(MCInst &Inst, unsigned N) const {
1511     assert(N == 2 && isMemoryIndexed32() && "Invalid number of operands!");
1512     addMemoryIndexedOperands(Inst, N, 4);
1513   }
1514
1515   void addMemoryIndexed16Operands(MCInst &Inst, unsigned N) const {
1516     assert(N == 2 && isMemoryIndexed16() && "Invalid number of operands!");
1517     addMemoryIndexedOperands(Inst, N, 2);
1518   }
1519
1520   void addMemoryIndexed8Operands(MCInst &Inst, unsigned N) const {
1521     assert(N == 2 && isMemoryIndexed8() && "Invalid number of operands!");
1522     addMemoryIndexedOperands(Inst, N, 1);
1523   }
1524
1525   void addMemoryNoIndexOperands(MCInst &Inst, unsigned N) const {
1526     assert(N == 1 && isMemoryNoIndex() && "Invalid number of operands!");
1527     // Add the base register operand (the offset is always zero, so ignore it).
1528     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1529   }
1530
1531   void addMemorySIMDNoIndexOperands(MCInst &Inst, unsigned N) const {
1532     assert(N == 1 && isMemorySIMDNoIndex() && "Invalid number of operands!");
1533     // Add the base register operand (the offset is always zero, so ignore it).
1534     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1535   }
1536
1537   void addMemoryWritebackIndexedOperands(MCInst &Inst, unsigned N,
1538                                          unsigned Scale) const {
1539     assert(N == 2 && "Invalid number of operands!");
1540
1541     // Add the base register operand.
1542     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1543
1544     // Add the offset operand.
1545     int64_t Offset = 0;
1546     if (Mem.OffsetImm) {
1547       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Mem.OffsetImm);
1548       assert(CE && "Non-constant indexed offset operand!");
1549       Offset = CE->getValue();
1550     }
1551
1552     if (Scale != 1) {
1553       assert(Offset % Scale == 0 &&
1554              "Offset operand must be a multiple of the scale!");
1555       Offset /= Scale;
1556     }
1557
1558     Inst.addOperand(MCOperand::CreateImm(Offset));
1559   }
1560
1561   void addMemoryIndexedSImm9Operands(MCInst &Inst, unsigned N) const {
1562     addMemoryWritebackIndexedOperands(Inst, N, 1);
1563   }
1564
1565   void addMemoryIndexed32SImm7Operands(MCInst &Inst, unsigned N) const {
1566     addMemoryWritebackIndexedOperands(Inst, N, 4);
1567   }
1568
1569   void addMemoryIndexed64SImm7Operands(MCInst &Inst, unsigned N) const {
1570     addMemoryWritebackIndexedOperands(Inst, N, 8);
1571   }
1572
1573   void addMemoryIndexed128SImm7Operands(MCInst &Inst, unsigned N) const {
1574     addMemoryWritebackIndexedOperands(Inst, N, 16);
1575   }
1576
1577   virtual void print(raw_ostream &OS) const;
1578
1579   static ARM64Operand *CreateToken(StringRef Str, bool IsSuffix, SMLoc S,
1580                                    MCContext &Ctx) {
1581     ARM64Operand *Op = new ARM64Operand(k_Token, Ctx);
1582     Op->Tok.Data = Str.data();
1583     Op->Tok.Length = Str.size();
1584     Op->Tok.IsSuffix = IsSuffix;
1585     Op->StartLoc = S;
1586     Op->EndLoc = S;
1587     return Op;
1588   }
1589
1590   static ARM64Operand *CreateReg(unsigned RegNum, bool isVector, SMLoc S,
1591                                  SMLoc E, MCContext &Ctx) {
1592     ARM64Operand *Op = new ARM64Operand(k_Register, Ctx);
1593     Op->Reg.RegNum = RegNum;
1594     Op->Reg.isVector = isVector;
1595     Op->StartLoc = S;
1596     Op->EndLoc = E;
1597     return Op;
1598   }
1599
1600   static ARM64Operand *CreateVectorList(unsigned RegNum, unsigned Count,
1601                                         unsigned NumElements, char ElementKind,
1602                                         SMLoc S, SMLoc E, MCContext &Ctx) {
1603     ARM64Operand *Op = new ARM64Operand(k_VectorList, Ctx);
1604     Op->VectorList.RegNum = RegNum;
1605     Op->VectorList.Count = Count;
1606     Op->VectorList.NumElements = NumElements;
1607     Op->VectorList.ElementKind = ElementKind;
1608     Op->StartLoc = S;
1609     Op->EndLoc = E;
1610     return Op;
1611   }
1612
1613   static ARM64Operand *CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E,
1614                                          MCContext &Ctx) {
1615     ARM64Operand *Op = new ARM64Operand(k_VectorIndex, Ctx);
1616     Op->VectorIndex.Val = Idx;
1617     Op->StartLoc = S;
1618     Op->EndLoc = E;
1619     return Op;
1620   }
1621
1622   static ARM64Operand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E,
1623                                  MCContext &Ctx) {
1624     ARM64Operand *Op = new ARM64Operand(k_Immediate, Ctx);
1625     Op->Imm.Val = Val;
1626     Op->StartLoc = S;
1627     Op->EndLoc = E;
1628     return Op;
1629   }
1630
1631   static ARM64Operand *CreateFPImm(unsigned Val, SMLoc S, MCContext &Ctx) {
1632     ARM64Operand *Op = new ARM64Operand(k_FPImm, Ctx);
1633     Op->FPImm.Val = Val;
1634     Op->StartLoc = S;
1635     Op->EndLoc = S;
1636     return Op;
1637   }
1638
1639   static ARM64Operand *CreateBarrier(unsigned Val, SMLoc S, MCContext &Ctx) {
1640     ARM64Operand *Op = new ARM64Operand(k_Barrier, Ctx);
1641     Op->Barrier.Val = Val;
1642     Op->StartLoc = S;
1643     Op->EndLoc = S;
1644     return Op;
1645   }
1646
1647   static ARM64Operand *CreateSysReg(StringRef Str, SMLoc S, MCContext &Ctx) {
1648     ARM64Operand *Op = new ARM64Operand(k_SysReg, Ctx);
1649     Op->SysReg.Data = Str.data();
1650     Op->SysReg.Length = Str.size();
1651     Op->StartLoc = S;
1652     Op->EndLoc = S;
1653     return Op;
1654   }
1655
1656   static ARM64Operand *CreateMem(unsigned BaseRegNum, const MCExpr *Off,
1657                                  SMLoc S, SMLoc E, SMLoc OffsetLoc,
1658                                  MCContext &Ctx) {
1659     ARM64Operand *Op = new ARM64Operand(k_Memory, Ctx);
1660     Op->Mem.BaseRegNum = BaseRegNum;
1661     Op->Mem.OffsetRegNum = 0;
1662     Op->Mem.OffsetImm = Off;
1663     Op->Mem.ExtType = ARM64_AM::UXTX;
1664     Op->Mem.ShiftVal = 0;
1665     Op->Mem.ExplicitShift = false;
1666     Op->Mem.Mode = ImmediateOffset;
1667     Op->OffsetLoc = OffsetLoc;
1668     Op->StartLoc = S;
1669     Op->EndLoc = E;
1670     return Op;
1671   }
1672
1673   static ARM64Operand *CreateRegOffsetMem(unsigned BaseReg, unsigned OffsetReg,
1674                                           ARM64_AM::ExtendType ExtType,
1675                                           unsigned ShiftVal, bool ExplicitShift,
1676                                           SMLoc S, SMLoc E, MCContext &Ctx) {
1677     ARM64Operand *Op = new ARM64Operand(k_Memory, Ctx);
1678     Op->Mem.BaseRegNum = BaseReg;
1679     Op->Mem.OffsetRegNum = OffsetReg;
1680     Op->Mem.OffsetImm = 0;
1681     Op->Mem.ExtType = ExtType;
1682     Op->Mem.ShiftVal = ShiftVal;
1683     Op->Mem.ExplicitShift = ExplicitShift;
1684     Op->Mem.Mode = RegisterOffset;
1685     Op->StartLoc = S;
1686     Op->EndLoc = E;
1687     return Op;
1688   }
1689
1690   static ARM64Operand *CreateSysCR(unsigned Val, SMLoc S, SMLoc E,
1691                                    MCContext &Ctx) {
1692     ARM64Operand *Op = new ARM64Operand(k_SysCR, Ctx);
1693     Op->SysCRImm.Val = Val;
1694     Op->StartLoc = S;
1695     Op->EndLoc = E;
1696     return Op;
1697   }
1698
1699   static ARM64Operand *CreatePrefetch(unsigned Val, SMLoc S, MCContext &Ctx) {
1700     ARM64Operand *Op = new ARM64Operand(k_Prefetch, Ctx);
1701     Op->Prefetch.Val = Val;
1702     Op->StartLoc = S;
1703     Op->EndLoc = S;
1704     return Op;
1705   }
1706
1707   static ARM64Operand *CreateShifter(ARM64_AM::ShiftType ShOp, unsigned Val,
1708                                      SMLoc S, SMLoc E, MCContext &Ctx) {
1709     ARM64Operand *Op = new ARM64Operand(k_Shifter, Ctx);
1710     Op->Shifter.Val = ARM64_AM::getShifterImm(ShOp, Val);
1711     Op->StartLoc = S;
1712     Op->EndLoc = E;
1713     return Op;
1714   }
1715
1716   static ARM64Operand *CreateExtend(ARM64_AM::ExtendType ExtOp, unsigned Val,
1717                                     SMLoc S, SMLoc E, MCContext &Ctx) {
1718     ARM64Operand *Op = new ARM64Operand(k_Extend, Ctx);
1719     Op->Extend.Val = ARM64_AM::getArithExtendImm(ExtOp, Val);
1720     Op->StartLoc = S;
1721     Op->EndLoc = E;
1722     return Op;
1723   }
1724 };
1725
1726 } // end anonymous namespace.
1727
1728 void ARM64Operand::print(raw_ostream &OS) const {
1729   switch (Kind) {
1730   case k_FPImm:
1731     OS << "<fpimm " << getFPImm() << "(" << ARM64_AM::getFPImmFloat(getFPImm())
1732        << ") >";
1733     break;
1734   case k_Barrier: {
1735     bool Valid;
1736     StringRef Name = ARM64DB::DBarrierMapper().toString(getBarrier(), Valid);
1737     if (Valid)
1738       OS << "<barrier " << Name << ">";
1739     else
1740       OS << "<barrier invalid #" << getBarrier() << ">";
1741     break;
1742   }
1743   case k_Immediate:
1744     getImm()->print(OS);
1745     break;
1746   case k_Memory:
1747     OS << "<memory>";
1748     break;
1749   case k_Register:
1750     OS << "<register " << getReg() << ">";
1751     break;
1752   case k_VectorList: {
1753     OS << "<vectorlist ";
1754     unsigned Reg = getVectorListStart();
1755     for (unsigned i = 0, e = getVectorListCount(); i != e; ++i)
1756       OS << Reg + i << " ";
1757     OS << ">";
1758     break;
1759   }
1760   case k_VectorIndex:
1761     OS << "<vectorindex " << getVectorIndex() << ">";
1762     break;
1763   case k_SysReg:
1764     OS << "<sysreg: " << getSysReg() << '>';
1765     break;
1766   case k_Token:
1767     OS << "'" << getToken() << "'";
1768     break;
1769   case k_SysCR:
1770     OS << "c" << getSysCR();
1771     break;
1772   case k_Prefetch: {
1773     bool Valid;
1774     StringRef Name = ARM64PRFM::PRFMMapper().toString(getPrefetch(), Valid);
1775     if (Valid)
1776       OS << "<prfop " << Name << ">";
1777     else
1778       OS << "<prfop invalid #" << getPrefetch() << ">";
1779     break;
1780   }
1781   case k_Shifter: {
1782     unsigned Val = getShifter();
1783     OS << "<" << ARM64_AM::getShiftName(ARM64_AM::getShiftType(Val)) << " #"
1784        << ARM64_AM::getShiftValue(Val) << ">";
1785     break;
1786   }
1787   case k_Extend: {
1788     unsigned Val = getExtend();
1789     OS << "<" << ARM64_AM::getExtendName(ARM64_AM::getArithExtendType(Val))
1790        << " #" << ARM64_AM::getArithShiftValue(Val) << ">";
1791     break;
1792   }
1793   }
1794 }
1795
1796 /// @name Auto-generated Match Functions
1797 /// {
1798
1799 static unsigned MatchRegisterName(StringRef Name);
1800
1801 /// }
1802
1803 static unsigned matchVectorRegName(StringRef Name) {
1804   return StringSwitch<unsigned>(Name)
1805       .Case("v0", ARM64::Q0)
1806       .Case("v1", ARM64::Q1)
1807       .Case("v2", ARM64::Q2)
1808       .Case("v3", ARM64::Q3)
1809       .Case("v4", ARM64::Q4)
1810       .Case("v5", ARM64::Q5)
1811       .Case("v6", ARM64::Q6)
1812       .Case("v7", ARM64::Q7)
1813       .Case("v8", ARM64::Q8)
1814       .Case("v9", ARM64::Q9)
1815       .Case("v10", ARM64::Q10)
1816       .Case("v11", ARM64::Q11)
1817       .Case("v12", ARM64::Q12)
1818       .Case("v13", ARM64::Q13)
1819       .Case("v14", ARM64::Q14)
1820       .Case("v15", ARM64::Q15)
1821       .Case("v16", ARM64::Q16)
1822       .Case("v17", ARM64::Q17)
1823       .Case("v18", ARM64::Q18)
1824       .Case("v19", ARM64::Q19)
1825       .Case("v20", ARM64::Q20)
1826       .Case("v21", ARM64::Q21)
1827       .Case("v22", ARM64::Q22)
1828       .Case("v23", ARM64::Q23)
1829       .Case("v24", ARM64::Q24)
1830       .Case("v25", ARM64::Q25)
1831       .Case("v26", ARM64::Q26)
1832       .Case("v27", ARM64::Q27)
1833       .Case("v28", ARM64::Q28)
1834       .Case("v29", ARM64::Q29)
1835       .Case("v30", ARM64::Q30)
1836       .Case("v31", ARM64::Q31)
1837       .Default(0);
1838 }
1839
1840 static bool isValidVectorKind(StringRef Name) {
1841   return StringSwitch<bool>(Name.lower())
1842       .Case(".8b", true)
1843       .Case(".16b", true)
1844       .Case(".4h", true)
1845       .Case(".8h", true)
1846       .Case(".2s", true)
1847       .Case(".4s", true)
1848       .Case(".1d", true)
1849       .Case(".2d", true)
1850       .Case(".1q", true)
1851       // Accept the width neutral ones, too, for verbose syntax. If those
1852       // aren't used in the right places, the token operand won't match so
1853       // all will work out.
1854       .Case(".b", true)
1855       .Case(".h", true)
1856       .Case(".s", true)
1857       .Case(".d", true)
1858       .Default(false);
1859 }
1860
1861 static void parseValidVectorKind(StringRef Name, unsigned &NumElements,
1862                                  char &ElementKind) {
1863   assert(isValidVectorKind(Name));
1864
1865   ElementKind = Name.lower()[Name.size() - 1];
1866   NumElements = 0;
1867
1868   if (Name.size() == 2)
1869     return;
1870
1871   // Parse the lane count
1872   Name = Name.drop_front();
1873   while (isdigit(Name.front())) {
1874     NumElements = 10 * NumElements + (Name.front() - '0');
1875     Name = Name.drop_front();
1876   }
1877 }
1878
1879 bool ARM64AsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
1880                                    SMLoc &EndLoc) {
1881   StartLoc = getLoc();
1882   RegNo = tryParseRegister();
1883   EndLoc = SMLoc::getFromPointer(getLoc().getPointer() - 1);
1884   return (RegNo == (unsigned)-1);
1885 }
1886
1887 /// tryParseRegister - Try to parse a register name. The token must be an
1888 /// Identifier when called, and if it is a register name the token is eaten and
1889 /// the register is added to the operand list.
1890 int ARM64AsmParser::tryParseRegister() {
1891   const AsmToken &Tok = Parser.getTok();
1892   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1893
1894   std::string lowerCase = Tok.getString().lower();
1895   unsigned RegNum = MatchRegisterName(lowerCase);
1896   // Also handle a few aliases of registers.
1897   if (RegNum == 0)
1898     RegNum = StringSwitch<unsigned>(lowerCase)
1899                  .Case("fp",  ARM64::FP)
1900                  .Case("lr",  ARM64::LR)
1901                  .Case("x31", ARM64::XZR)
1902                  .Case("w31", ARM64::WZR)
1903                  .Default(0);
1904
1905   if (RegNum == 0)
1906     return -1;
1907
1908   Parser.Lex(); // Eat identifier token.
1909   return RegNum;
1910 }
1911
1912 /// tryMatchVectorRegister - Try to parse a vector register name with optional
1913 /// kind specifier. If it is a register specifier, eat the token and return it.
1914 int ARM64AsmParser::tryMatchVectorRegister(StringRef &Kind, bool expected) {
1915   if (Parser.getTok().isNot(AsmToken::Identifier)) {
1916     TokError("vector register expected");
1917     return -1;
1918   }
1919
1920   StringRef Name = Parser.getTok().getString();
1921   // If there is a kind specifier, it's separated from the register name by
1922   // a '.'.
1923   size_t Start = 0, Next = Name.find('.');
1924   StringRef Head = Name.slice(Start, Next);
1925   unsigned RegNum = matchVectorRegName(Head);
1926   if (RegNum) {
1927     if (Next != StringRef::npos) {
1928       Kind = Name.slice(Next, StringRef::npos);
1929       if (!isValidVectorKind(Kind)) {
1930         TokError("invalid vector kind qualifier");
1931         return -1;
1932       }
1933     }
1934     Parser.Lex(); // Eat the register token.
1935     return RegNum;
1936   }
1937
1938   if (expected)
1939     TokError("vector register expected");
1940   return -1;
1941 }
1942
1943 static int MatchSysCRName(StringRef Name) {
1944   // Use the same layout as the tablegen'erated register name matcher. Ugly,
1945   // but efficient.
1946   switch (Name.size()) {
1947   default:
1948     break;
1949   case 2:
1950     if (Name[0] != 'c' && Name[0] != 'C')
1951       return -1;
1952     switch (Name[1]) {
1953     default:
1954       return -1;
1955     case '0':
1956       return 0;
1957     case '1':
1958       return 1;
1959     case '2':
1960       return 2;
1961     case '3':
1962       return 3;
1963     case '4':
1964       return 4;
1965     case '5':
1966       return 5;
1967     case '6':
1968       return 6;
1969     case '7':
1970       return 7;
1971     case '8':
1972       return 8;
1973     case '9':
1974       return 9;
1975     }
1976     break;
1977   case 3:
1978     if ((Name[0] != 'c' && Name[0] != 'C') || Name[1] != '1')
1979       return -1;
1980     switch (Name[2]) {
1981     default:
1982       return -1;
1983     case '0':
1984       return 10;
1985     case '1':
1986       return 11;
1987     case '2':
1988       return 12;
1989     case '3':
1990       return 13;
1991     case '4':
1992       return 14;
1993     case '5':
1994       return 15;
1995     }
1996     break;
1997   }
1998
1999   llvm_unreachable("Unhandled SysCR operand string!");
2000   return -1;
2001 }
2002
2003 /// tryParseSysCROperand - Try to parse a system instruction CR operand name.
2004 ARM64AsmParser::OperandMatchResultTy
2005 ARM64AsmParser::tryParseSysCROperand(OperandVector &Operands) {
2006   SMLoc S = getLoc();
2007   const AsmToken &Tok = Parser.getTok();
2008   if (Tok.isNot(AsmToken::Identifier))
2009     return MatchOperand_NoMatch;
2010
2011   int Num = MatchSysCRName(Tok.getString());
2012   if (Num == -1)
2013     return MatchOperand_NoMatch;
2014
2015   Parser.Lex(); // Eat identifier token.
2016   Operands.push_back(ARM64Operand::CreateSysCR(Num, S, getLoc(), getContext()));
2017   return MatchOperand_Success;
2018 }
2019
2020 /// tryParsePrefetch - Try to parse a prefetch operand.
2021 ARM64AsmParser::OperandMatchResultTy
2022 ARM64AsmParser::tryParsePrefetch(OperandVector &Operands) {
2023   SMLoc S = getLoc();
2024   const AsmToken &Tok = Parser.getTok();
2025   // Either an identifier for named values or a 5-bit immediate.
2026   bool Hash = Tok.is(AsmToken::Hash);
2027   if (Hash || Tok.is(AsmToken::Integer)) {
2028     if (Hash)
2029       Parser.Lex(); // Eat hash token.
2030     const MCExpr *ImmVal;
2031     if (getParser().parseExpression(ImmVal))
2032       return MatchOperand_ParseFail;
2033
2034     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2035     if (!MCE) {
2036       TokError("immediate value expected for prefetch operand");
2037       return MatchOperand_ParseFail;
2038     }
2039     unsigned prfop = MCE->getValue();
2040     if (prfop > 31) {
2041       TokError("prefetch operand out of range, [0,31] expected");
2042       return MatchOperand_ParseFail;
2043     }
2044
2045     Operands.push_back(ARM64Operand::CreatePrefetch(prfop, S, getContext()));
2046     return MatchOperand_Success;
2047   }
2048
2049   if (Tok.isNot(AsmToken::Identifier)) {
2050     TokError("pre-fetch hint expected");
2051     return MatchOperand_ParseFail;
2052   }
2053
2054   bool Valid;
2055   unsigned prfop = ARM64PRFM::PRFMMapper().fromString(Tok.getString(), Valid);
2056   if (!Valid) {
2057     TokError("pre-fetch hint expected");
2058     return MatchOperand_ParseFail;
2059   }
2060
2061   Parser.Lex(); // Eat identifier token.
2062   Operands.push_back(ARM64Operand::CreatePrefetch(prfop, S, getContext()));
2063   return MatchOperand_Success;
2064 }
2065
2066 /// tryParseAdrpLabel - Parse and validate a source label for the ADRP
2067 /// instruction.
2068 ARM64AsmParser::OperandMatchResultTy
2069 ARM64AsmParser::tryParseAdrpLabel(OperandVector &Operands) {
2070   SMLoc S = getLoc();
2071   const MCExpr *Expr;
2072
2073   if (Parser.getTok().is(AsmToken::Hash)) {
2074     Parser.Lex(); // Eat hash token.
2075   }
2076
2077   if (parseSymbolicImmVal(Expr))
2078     return MatchOperand_ParseFail;
2079
2080   ARM64MCExpr::VariantKind ELFRefKind;
2081   MCSymbolRefExpr::VariantKind DarwinRefKind;
2082   const MCConstantExpr *Addend;
2083   if (classifySymbolRef(Expr, ELFRefKind, DarwinRefKind, Addend)) {
2084     if (DarwinRefKind == MCSymbolRefExpr::VK_None &&
2085         ELFRefKind == ARM64MCExpr::VK_INVALID) {
2086       // No modifier was specified at all; this is the syntax for an ELF basic
2087       // ADRP relocation (unfortunately).
2088       Expr = ARM64MCExpr::Create(Expr, ARM64MCExpr::VK_ABS_PAGE, getContext());
2089     } else if ((DarwinRefKind == MCSymbolRefExpr::VK_GOTPAGE ||
2090                 DarwinRefKind == MCSymbolRefExpr::VK_TLVPPAGE) &&
2091                Addend != 0) {
2092       Error(S, "gotpage label reference not allowed an addend");
2093       return MatchOperand_ParseFail;
2094     } else if (DarwinRefKind != MCSymbolRefExpr::VK_PAGE &&
2095                DarwinRefKind != MCSymbolRefExpr::VK_GOTPAGE &&
2096                DarwinRefKind != MCSymbolRefExpr::VK_TLVPPAGE &&
2097                ELFRefKind != ARM64MCExpr::VK_GOT_PAGE &&
2098                ELFRefKind != ARM64MCExpr::VK_GOTTPREL_PAGE &&
2099                ELFRefKind != ARM64MCExpr::VK_TLSDESC_PAGE) {
2100       // The operand must be an @page or @gotpage qualified symbolref.
2101       Error(S, "page or gotpage label reference expected");
2102       return MatchOperand_ParseFail;
2103     }
2104   }
2105
2106   // We have either a label reference possibly with addend or an immediate. The
2107   // addend is a raw value here. The linker will adjust it to only reference the
2108   // page.
2109   SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2110   Operands.push_back(ARM64Operand::CreateImm(Expr, S, E, getContext()));
2111
2112   return MatchOperand_Success;
2113 }
2114
2115 /// tryParseAdrLabel - Parse and validate a source label for the ADR
2116 /// instruction.
2117 ARM64AsmParser::OperandMatchResultTy
2118 ARM64AsmParser::tryParseAdrLabel(OperandVector &Operands) {
2119   SMLoc S = getLoc();
2120   const MCExpr *Expr;
2121
2122   if (Parser.getTok().is(AsmToken::Hash)) {
2123     Parser.Lex(); // Eat hash token.
2124   }
2125
2126   if (getParser().parseExpression(Expr))
2127     return MatchOperand_ParseFail;
2128
2129   SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2130   Operands.push_back(ARM64Operand::CreateImm(Expr, S, E, getContext()));
2131
2132   return MatchOperand_Success;
2133 }
2134
2135 /// tryParseFPImm - A floating point immediate expression operand.
2136 ARM64AsmParser::OperandMatchResultTy
2137 ARM64AsmParser::tryParseFPImm(OperandVector &Operands) {
2138   SMLoc S = getLoc();
2139
2140   bool Hash = false;
2141   if (Parser.getTok().is(AsmToken::Hash)) {
2142     Parser.Lex(); // Eat '#'
2143     Hash = true;
2144   }
2145
2146   // Handle negation, as that still comes through as a separate token.
2147   bool isNegative = false;
2148   if (Parser.getTok().is(AsmToken::Minus)) {
2149     isNegative = true;
2150     Parser.Lex();
2151   }
2152   const AsmToken &Tok = Parser.getTok();
2153   if (Tok.is(AsmToken::Real)) {
2154     APFloat RealVal(APFloat::IEEEdouble, Tok.getString());
2155     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
2156     // If we had a '-' in front, toggle the sign bit.
2157     IntVal ^= (uint64_t)isNegative << 63;
2158     int Val = ARM64_AM::getFP64Imm(APInt(64, IntVal));
2159     Parser.Lex(); // Eat the token.
2160     // Check for out of range values. As an exception, we let Zero through,
2161     // as we handle that special case in post-processing before matching in
2162     // order to use the zero register for it.
2163     if (Val == -1 && !RealVal.isZero()) {
2164       TokError("floating point value out of range");
2165       return MatchOperand_ParseFail;
2166     }
2167     Operands.push_back(ARM64Operand::CreateFPImm(Val, S, getContext()));
2168     return MatchOperand_Success;
2169   }
2170   if (Tok.is(AsmToken::Integer)) {
2171     int64_t Val;
2172     if (!isNegative && Tok.getString().startswith("0x")) {
2173       Val = Tok.getIntVal();
2174       if (Val > 255 || Val < 0) {
2175         TokError("encoded floating point value out of range");
2176         return MatchOperand_ParseFail;
2177       }
2178     } else {
2179       APFloat RealVal(APFloat::IEEEdouble, Tok.getString());
2180       uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
2181       // If we had a '-' in front, toggle the sign bit.
2182       IntVal ^= (uint64_t)isNegative << 63;
2183       Val = ARM64_AM::getFP64Imm(APInt(64, IntVal));
2184     }
2185     Parser.Lex(); // Eat the token.
2186     Operands.push_back(ARM64Operand::CreateFPImm(Val, S, getContext()));
2187     return MatchOperand_Success;
2188   }
2189
2190   if (!Hash)
2191     return MatchOperand_NoMatch;
2192
2193   TokError("invalid floating point immediate");
2194   return MatchOperand_ParseFail;
2195 }
2196
2197 /// parseCondCodeString - Parse a Condition Code string.
2198 unsigned ARM64AsmParser::parseCondCodeString(StringRef Cond) {
2199   unsigned CC = StringSwitch<unsigned>(Cond.lower())
2200                     .Case("eq", ARM64CC::EQ)
2201                     .Case("ne", ARM64CC::NE)
2202                     .Case("cs", ARM64CC::CS)
2203                     .Case("hs", ARM64CC::CS)
2204                     .Case("cc", ARM64CC::CC)
2205                     .Case("lo", ARM64CC::CC)
2206                     .Case("mi", ARM64CC::MI)
2207                     .Case("pl", ARM64CC::PL)
2208                     .Case("vs", ARM64CC::VS)
2209                     .Case("vc", ARM64CC::VC)
2210                     .Case("hi", ARM64CC::HI)
2211                     .Case("ls", ARM64CC::LS)
2212                     .Case("ge", ARM64CC::GE)
2213                     .Case("lt", ARM64CC::LT)
2214                     .Case("gt", ARM64CC::GT)
2215                     .Case("le", ARM64CC::LE)
2216                     .Case("al", ARM64CC::AL)
2217                     .Case("nv", ARM64CC::NV)
2218                     .Default(ARM64CC::Invalid);
2219   return CC;
2220 }
2221
2222 /// parseCondCode - Parse a Condition Code operand.
2223 bool ARM64AsmParser::parseCondCode(OperandVector &Operands,
2224                                    bool invertCondCode) {
2225   SMLoc S = getLoc();
2226   const AsmToken &Tok = Parser.getTok();
2227   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2228
2229   StringRef Cond = Tok.getString();
2230   unsigned CC = parseCondCodeString(Cond);
2231   if (CC == ARM64CC::Invalid)
2232     return TokError("invalid condition code");
2233   Parser.Lex(); // Eat identifier token.
2234
2235   if (invertCondCode)
2236     CC = ARM64CC::getInvertedCondCode(ARM64CC::CondCode(CC));
2237
2238   const MCExpr *CCExpr = MCConstantExpr::Create(CC, getContext());
2239   Operands.push_back(
2240       ARM64Operand::CreateImm(CCExpr, S, getLoc(), getContext()));
2241   return false;
2242 }
2243
2244 /// ParseOptionalShift - Some operands take an optional shift argument. Parse
2245 /// them if present.
2246 bool ARM64AsmParser::parseOptionalShift(OperandVector &Operands) {
2247   const AsmToken &Tok = Parser.getTok();
2248   ARM64_AM::ShiftType ShOp = StringSwitch<ARM64_AM::ShiftType>(Tok.getString())
2249                                  .Case("lsl", ARM64_AM::LSL)
2250                                  .Case("lsr", ARM64_AM::LSR)
2251                                  .Case("asr", ARM64_AM::ASR)
2252                                  .Case("ror", ARM64_AM::ROR)
2253                                  .Case("msl", ARM64_AM::MSL)
2254                                  .Case("LSL", ARM64_AM::LSL)
2255                                  .Case("LSR", ARM64_AM::LSR)
2256                                  .Case("ASR", ARM64_AM::ASR)
2257                                  .Case("ROR", ARM64_AM::ROR)
2258                                  .Case("MSL", ARM64_AM::MSL)
2259                                  .Default(ARM64_AM::InvalidShift);
2260   if (ShOp == ARM64_AM::InvalidShift)
2261     return true;
2262
2263   SMLoc S = Tok.getLoc();
2264   Parser.Lex();
2265
2266   // We expect a number here.
2267   bool Hash = getLexer().is(AsmToken::Hash);
2268   if (!Hash && getLexer().isNot(AsmToken::Integer))
2269     return TokError("immediate value expected for shifter operand");
2270
2271   if (Hash)
2272     Parser.Lex(); // Eat the '#'.
2273
2274   SMLoc ExprLoc = getLoc();
2275   const MCExpr *ImmVal;
2276   if (getParser().parseExpression(ImmVal))
2277     return true;
2278
2279   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2280   if (!MCE)
2281     return TokError("immediate value expected for shifter operand");
2282
2283   if ((MCE->getValue() & 0x3f) != MCE->getValue())
2284     return Error(ExprLoc, "immediate value too large for shifter operand");
2285
2286   SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2287   Operands.push_back(
2288       ARM64Operand::CreateShifter(ShOp, MCE->getValue(), S, E, getContext()));
2289   return false;
2290 }
2291
2292 /// parseOptionalExtend - Some operands take an optional extend argument. Parse
2293 /// them if present.
2294 bool ARM64AsmParser::parseOptionalExtend(OperandVector &Operands) {
2295   const AsmToken &Tok = Parser.getTok();
2296   ARM64_AM::ExtendType ExtOp =
2297       StringSwitch<ARM64_AM::ExtendType>(Tok.getString())
2298           .Case("uxtb", ARM64_AM::UXTB)
2299           .Case("uxth", ARM64_AM::UXTH)
2300           .Case("uxtw", ARM64_AM::UXTW)
2301           .Case("uxtx", ARM64_AM::UXTX)
2302           .Case("lsl", ARM64_AM::UXTX) // Alias for UXTX
2303           .Case("sxtb", ARM64_AM::SXTB)
2304           .Case("sxth", ARM64_AM::SXTH)
2305           .Case("sxtw", ARM64_AM::SXTW)
2306           .Case("sxtx", ARM64_AM::SXTX)
2307           .Case("UXTB", ARM64_AM::UXTB)
2308           .Case("UXTH", ARM64_AM::UXTH)
2309           .Case("UXTW", ARM64_AM::UXTW)
2310           .Case("UXTX", ARM64_AM::UXTX)
2311           .Case("LSL", ARM64_AM::UXTX) // Alias for UXTX
2312           .Case("SXTB", ARM64_AM::SXTB)
2313           .Case("SXTH", ARM64_AM::SXTH)
2314           .Case("SXTW", ARM64_AM::SXTW)
2315           .Case("SXTX", ARM64_AM::SXTX)
2316           .Default(ARM64_AM::InvalidExtend);
2317   if (ExtOp == ARM64_AM::InvalidExtend)
2318     return true;
2319
2320   SMLoc S = Tok.getLoc();
2321   Parser.Lex();
2322
2323   if (getLexer().is(AsmToken::EndOfStatement) ||
2324       getLexer().is(AsmToken::Comma)) {
2325     SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2326     Operands.push_back(
2327         ARM64Operand::CreateExtend(ExtOp, 0, S, E, getContext()));
2328     return false;
2329   }
2330
2331   bool Hash = getLexer().is(AsmToken::Hash);
2332   if (!Hash && getLexer().isNot(AsmToken::Integer)) {
2333     SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2334     Operands.push_back(
2335         ARM64Operand::CreateExtend(ExtOp, 0, S, E, getContext()));
2336     return false;
2337   }
2338
2339   if (Hash)
2340     Parser.Lex(); // Eat the '#'.
2341
2342   const MCExpr *ImmVal;
2343   if (getParser().parseExpression(ImmVal))
2344     return true;
2345
2346   const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2347   if (!MCE)
2348     return TokError("immediate value expected for extend operand");
2349
2350   SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
2351   Operands.push_back(
2352       ARM64Operand::CreateExtend(ExtOp, MCE->getValue(), S, E, getContext()));
2353   return false;
2354 }
2355
2356 /// parseSysAlias - The IC, DC, AT, and TLBI instructions are simple aliases for
2357 /// the SYS instruction. Parse them specially so that we create a SYS MCInst.
2358 bool ARM64AsmParser::parseSysAlias(StringRef Name, SMLoc NameLoc,
2359                                    OperandVector &Operands) {
2360   if (Name.find('.') != StringRef::npos)
2361     return TokError("invalid operand");
2362
2363   Mnemonic = Name;
2364   Operands.push_back(
2365       ARM64Operand::CreateToken("sys", false, NameLoc, getContext()));
2366
2367   const AsmToken &Tok = Parser.getTok();
2368   StringRef Op = Tok.getString();
2369   SMLoc S = Tok.getLoc();
2370
2371   const MCExpr *Expr = 0;
2372
2373 #define SYS_ALIAS(op1, Cn, Cm, op2)                                            \
2374   do {                                                                         \
2375     Expr = MCConstantExpr::Create(op1, getContext());                          \
2376     Operands.push_back(                                                        \
2377         ARM64Operand::CreateImm(Expr, S, getLoc(), getContext()));             \
2378     Operands.push_back(                                                        \
2379         ARM64Operand::CreateSysCR(Cn, S, getLoc(), getContext()));             \
2380     Operands.push_back(                                                        \
2381         ARM64Operand::CreateSysCR(Cm, S, getLoc(), getContext()));             \
2382     Expr = MCConstantExpr::Create(op2, getContext());                          \
2383     Operands.push_back(                                                        \
2384         ARM64Operand::CreateImm(Expr, S, getLoc(), getContext()));             \
2385   } while (0)
2386
2387   if (Mnemonic == "ic") {
2388     if (!Op.compare_lower("ialluis")) {
2389       // SYS #0, C7, C1, #0
2390       SYS_ALIAS(0, 7, 1, 0);
2391     } else if (!Op.compare_lower("iallu")) {
2392       // SYS #0, C7, C5, #0
2393       SYS_ALIAS(0, 7, 5, 0);
2394     } else if (!Op.compare_lower("ivau")) {
2395       // SYS #3, C7, C5, #1
2396       SYS_ALIAS(3, 7, 5, 1);
2397     } else {
2398       return TokError("invalid operand for IC instruction");
2399     }
2400   } else if (Mnemonic == "dc") {
2401     if (!Op.compare_lower("zva")) {
2402       // SYS #3, C7, C4, #1
2403       SYS_ALIAS(3, 7, 4, 1);
2404     } else if (!Op.compare_lower("ivac")) {
2405       // SYS #3, C7, C6, #1
2406       SYS_ALIAS(0, 7, 6, 1);
2407     } else if (!Op.compare_lower("isw")) {
2408       // SYS #0, C7, C6, #2
2409       SYS_ALIAS(0, 7, 6, 2);
2410     } else if (!Op.compare_lower("cvac")) {
2411       // SYS #3, C7, C10, #1
2412       SYS_ALIAS(3, 7, 10, 1);
2413     } else if (!Op.compare_lower("csw")) {
2414       // SYS #0, C7, C10, #2
2415       SYS_ALIAS(0, 7, 10, 2);
2416     } else if (!Op.compare_lower("cvau")) {
2417       // SYS #3, C7, C11, #1
2418       SYS_ALIAS(3, 7, 11, 1);
2419     } else if (!Op.compare_lower("civac")) {
2420       // SYS #3, C7, C14, #1
2421       SYS_ALIAS(3, 7, 14, 1);
2422     } else if (!Op.compare_lower("cisw")) {
2423       // SYS #0, C7, C14, #2
2424       SYS_ALIAS(0, 7, 14, 2);
2425     } else {
2426       return TokError("invalid operand for DC instruction");
2427     }
2428   } else if (Mnemonic == "at") {
2429     if (!Op.compare_lower("s1e1r")) {
2430       // SYS #0, C7, C8, #0
2431       SYS_ALIAS(0, 7, 8, 0);
2432     } else if (!Op.compare_lower("s1e2r")) {
2433       // SYS #4, C7, C8, #0
2434       SYS_ALIAS(4, 7, 8, 0);
2435     } else if (!Op.compare_lower("s1e3r")) {
2436       // SYS #6, C7, C8, #0
2437       SYS_ALIAS(6, 7, 8, 0);
2438     } else if (!Op.compare_lower("s1e1w")) {
2439       // SYS #0, C7, C8, #1
2440       SYS_ALIAS(0, 7, 8, 1);
2441     } else if (!Op.compare_lower("s1e2w")) {
2442       // SYS #4, C7, C8, #1
2443       SYS_ALIAS(4, 7, 8, 1);
2444     } else if (!Op.compare_lower("s1e3w")) {
2445       // SYS #6, C7, C8, #1
2446       SYS_ALIAS(6, 7, 8, 1);
2447     } else if (!Op.compare_lower("s1e0r")) {
2448       // SYS #0, C7, C8, #3
2449       SYS_ALIAS(0, 7, 8, 2);
2450     } else if (!Op.compare_lower("s1e0w")) {
2451       // SYS #0, C7, C8, #3
2452       SYS_ALIAS(0, 7, 8, 3);
2453     } else if (!Op.compare_lower("s12e1r")) {
2454       // SYS #4, C7, C8, #4
2455       SYS_ALIAS(4, 7, 8, 4);
2456     } else if (!Op.compare_lower("s12e1w")) {
2457       // SYS #4, C7, C8, #5
2458       SYS_ALIAS(4, 7, 8, 5);
2459     } else if (!Op.compare_lower("s12e0r")) {
2460       // SYS #4, C7, C8, #6
2461       SYS_ALIAS(4, 7, 8, 6);
2462     } else if (!Op.compare_lower("s12e0w")) {
2463       // SYS #4, C7, C8, #7
2464       SYS_ALIAS(4, 7, 8, 7);
2465     } else {
2466       return TokError("invalid operand for AT instruction");
2467     }
2468   } else if (Mnemonic == "tlbi") {
2469     if (!Op.compare_lower("vmalle1is")) {
2470       // SYS #0, C8, C3, #0
2471       SYS_ALIAS(0, 8, 3, 0);
2472     } else if (!Op.compare_lower("alle2is")) {
2473       // SYS #4, C8, C3, #0
2474       SYS_ALIAS(4, 8, 3, 0);
2475     } else if (!Op.compare_lower("alle3is")) {
2476       // SYS #6, C8, C3, #0
2477       SYS_ALIAS(6, 8, 3, 0);
2478     } else if (!Op.compare_lower("vae1is")) {
2479       // SYS #0, C8, C3, #1
2480       SYS_ALIAS(0, 8, 3, 1);
2481     } else if (!Op.compare_lower("vae2is")) {
2482       // SYS #4, C8, C3, #1
2483       SYS_ALIAS(4, 8, 3, 1);
2484     } else if (!Op.compare_lower("vae3is")) {
2485       // SYS #6, C8, C3, #1
2486       SYS_ALIAS(6, 8, 3, 1);
2487     } else if (!Op.compare_lower("aside1is")) {
2488       // SYS #0, C8, C3, #2
2489       SYS_ALIAS(0, 8, 3, 2);
2490     } else if (!Op.compare_lower("vaae1is")) {
2491       // SYS #0, C8, C3, #3
2492       SYS_ALIAS(0, 8, 3, 3);
2493     } else if (!Op.compare_lower("alle1is")) {
2494       // SYS #4, C8, C3, #4
2495       SYS_ALIAS(4, 8, 3, 4);
2496     } else if (!Op.compare_lower("vale1is")) {
2497       // SYS #0, C8, C3, #5
2498       SYS_ALIAS(0, 8, 3, 5);
2499     } else if (!Op.compare_lower("vaale1is")) {
2500       // SYS #0, C8, C3, #7
2501       SYS_ALIAS(0, 8, 3, 7);
2502     } else if (!Op.compare_lower("vmalle1")) {
2503       // SYS #0, C8, C7, #0
2504       SYS_ALIAS(0, 8, 7, 0);
2505     } else if (!Op.compare_lower("alle2")) {
2506       // SYS #4, C8, C7, #0
2507       SYS_ALIAS(4, 8, 7, 0);
2508     } else if (!Op.compare_lower("vale2is")) {
2509       // SYS #4, C8, C3, #5
2510       SYS_ALIAS(4, 8, 3, 5);
2511     } else if (!Op.compare_lower("vale3is")) {
2512       // SYS #6, C8, C3, #5
2513       SYS_ALIAS(6, 8, 3, 5);
2514     } else if (!Op.compare_lower("alle3")) {
2515       // SYS #6, C8, C7, #0
2516       SYS_ALIAS(6, 8, 7, 0);
2517     } else if (!Op.compare_lower("vae1")) {
2518       // SYS #0, C8, C7, #1
2519       SYS_ALIAS(0, 8, 7, 1);
2520     } else if (!Op.compare_lower("vae2")) {
2521       // SYS #4, C8, C7, #1
2522       SYS_ALIAS(4, 8, 7, 1);
2523     } else if (!Op.compare_lower("vae3")) {
2524       // SYS #6, C8, C7, #1
2525       SYS_ALIAS(6, 8, 7, 1);
2526     } else if (!Op.compare_lower("aside1")) {
2527       // SYS #0, C8, C7, #2
2528       SYS_ALIAS(0, 8, 7, 2);
2529     } else if (!Op.compare_lower("vaae1")) {
2530       // SYS #0, C8, C7, #3
2531       SYS_ALIAS(0, 8, 7, 3);
2532     } else if (!Op.compare_lower("alle1")) {
2533       // SYS #4, C8, C7, #4
2534       SYS_ALIAS(4, 8, 7, 4);
2535     } else if (!Op.compare_lower("vale1")) {
2536       // SYS #0, C8, C7, #5
2537       SYS_ALIAS(0, 8, 7, 5);
2538     } else if (!Op.compare_lower("vale2")) {
2539       // SYS #4, C8, C7, #5
2540       SYS_ALIAS(4, 8, 7, 5);
2541     } else if (!Op.compare_lower("vale3")) {
2542       // SYS #6, C8, C7, #5
2543       SYS_ALIAS(6, 8, 7, 5);
2544     } else if (!Op.compare_lower("vaale1")) {
2545       // SYS #0, C8, C7, #7
2546       SYS_ALIAS(0, 8, 7, 7);
2547     } else if (!Op.compare_lower("ipas2e1")) {
2548       // SYS #4, C8, C4, #1
2549       SYS_ALIAS(4, 8, 4, 1);
2550     } else if (!Op.compare_lower("ipas2le1")) {
2551       // SYS #4, C8, C4, #5
2552       SYS_ALIAS(4, 8, 4, 5);
2553     } else if (!Op.compare_lower("ipas2e1is")) {
2554       // SYS #4, C8, C4, #1
2555       SYS_ALIAS(4, 8, 0, 1);
2556     } else if (!Op.compare_lower("ipas2le1is")) {
2557       // SYS #4, C8, C4, #5
2558       SYS_ALIAS(4, 8, 0, 5);
2559     } else if (!Op.compare_lower("vmalls12e1")) {
2560       // SYS #4, C8, C7, #6
2561       SYS_ALIAS(4, 8, 7, 6);
2562     } else if (!Op.compare_lower("vmalls12e1is")) {
2563       // SYS #4, C8, C3, #6
2564       SYS_ALIAS(4, 8, 3, 6);
2565     } else {
2566       return TokError("invalid operand for TLBI instruction");
2567     }
2568   }
2569
2570 #undef SYS_ALIAS
2571
2572   Parser.Lex(); // Eat operand.
2573
2574   bool ExpectRegister = (Op.lower().find("all") == StringRef::npos);
2575   bool HasRegister = false;
2576
2577   // Check for the optional register operand.
2578   if (getLexer().is(AsmToken::Comma)) {
2579     Parser.Lex(); // Eat comma.
2580
2581     if (Tok.isNot(AsmToken::Identifier) || parseRegister(Operands))
2582       return TokError("expected register operand");
2583
2584     HasRegister = true;
2585   }
2586
2587   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2588     Parser.eatToEndOfStatement();
2589     return TokError("unexpected token in argument list");
2590   }
2591
2592   if (ExpectRegister && !HasRegister) {
2593     return TokError("specified " + Mnemonic + " op requires a register");
2594   }
2595   else if (!ExpectRegister && HasRegister) {
2596     return TokError("specified " + Mnemonic + " op does not use a register");
2597   }
2598
2599   Parser.Lex(); // Consume the EndOfStatement
2600   return false;
2601 }
2602
2603 ARM64AsmParser::OperandMatchResultTy
2604 ARM64AsmParser::tryParseBarrierOperand(OperandVector &Operands) {
2605   const AsmToken &Tok = Parser.getTok();
2606
2607   // Can be either a #imm style literal or an option name
2608   bool Hash = Tok.is(AsmToken::Hash);
2609   if (Hash || Tok.is(AsmToken::Integer)) {
2610     // Immediate operand.
2611     if (Hash)
2612       Parser.Lex(); // Eat the '#'
2613     const MCExpr *ImmVal;
2614     SMLoc ExprLoc = getLoc();
2615     if (getParser().parseExpression(ImmVal))
2616       return MatchOperand_ParseFail;
2617     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2618     if (!MCE) {
2619       Error(ExprLoc, "immediate value expected for barrier operand");
2620       return MatchOperand_ParseFail;
2621     }
2622     if (MCE->getValue() < 0 || MCE->getValue() > 15) {
2623       Error(ExprLoc, "barrier operand out of range");
2624       return MatchOperand_ParseFail;
2625     }
2626     Operands.push_back(
2627         ARM64Operand::CreateBarrier(MCE->getValue(), ExprLoc, getContext()));
2628     return MatchOperand_Success;
2629   }
2630
2631   if (Tok.isNot(AsmToken::Identifier)) {
2632     TokError("invalid operand for instruction");
2633     return MatchOperand_ParseFail;
2634   }
2635
2636   bool Valid;
2637   unsigned Opt = ARM64DB::DBarrierMapper().fromString(Tok.getString(), Valid);
2638   if (!Valid) {
2639     TokError("invalid barrier option name");
2640     return MatchOperand_ParseFail;
2641   }
2642
2643   // The only valid named option for ISB is 'sy'
2644   if (Mnemonic == "isb" && Opt != ARM64DB::SY) {
2645     TokError("'sy' or #imm operand expected");
2646     return MatchOperand_ParseFail;
2647   }
2648
2649   Operands.push_back(ARM64Operand::CreateBarrier(Opt, getLoc(), getContext()));
2650   Parser.Lex(); // Consume the option
2651
2652   return MatchOperand_Success;
2653 }
2654
2655 ARM64AsmParser::OperandMatchResultTy
2656 ARM64AsmParser::tryParseSysReg(OperandVector &Operands) {
2657   const AsmToken &Tok = Parser.getTok();
2658
2659   if (Tok.isNot(AsmToken::Identifier))
2660     return MatchOperand_NoMatch;
2661
2662   Operands.push_back(ARM64Operand::CreateSysReg(Tok.getString(), getLoc(),
2663                      getContext()));
2664   Parser.Lex(); // Eat identifier
2665
2666   return MatchOperand_Success;
2667 }
2668
2669 /// tryParseVectorRegister - Parse a vector register operand.
2670 bool ARM64AsmParser::tryParseVectorRegister(OperandVector &Operands) {
2671   if (Parser.getTok().isNot(AsmToken::Identifier))
2672     return true;
2673
2674   SMLoc S = getLoc();
2675   // Check for a vector register specifier first.
2676   StringRef Kind;
2677   int64_t Reg = tryMatchVectorRegister(Kind, false);
2678   if (Reg == -1)
2679     return true;
2680   Operands.push_back(
2681       ARM64Operand::CreateReg(Reg, true, S, getLoc(), getContext()));
2682   // If there was an explicit qualifier, that goes on as a literal text
2683   // operand.
2684   if (!Kind.empty())
2685     Operands.push_back(ARM64Operand::CreateToken(Kind, false, S, getContext()));
2686
2687   // If there is an index specifier following the register, parse that too.
2688   if (Parser.getTok().is(AsmToken::LBrac)) {
2689     SMLoc SIdx = getLoc();
2690     Parser.Lex(); // Eat left bracket token.
2691
2692     const MCExpr *ImmVal;
2693     if (getParser().parseExpression(ImmVal))
2694       return false;
2695     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2696     if (!MCE) {
2697       TokError("immediate value expected for vector index");
2698       return false;
2699     }
2700
2701     SMLoc E = getLoc();
2702     if (Parser.getTok().isNot(AsmToken::RBrac)) {
2703       Error(E, "']' expected");
2704       return false;
2705     }
2706
2707     Parser.Lex(); // Eat right bracket token.
2708
2709     Operands.push_back(ARM64Operand::CreateVectorIndex(MCE->getValue(), SIdx, E,
2710                                                        getContext()));
2711   }
2712
2713   return false;
2714 }
2715
2716 /// parseRegister - Parse a non-vector register operand.
2717 bool ARM64AsmParser::parseRegister(OperandVector &Operands) {
2718   SMLoc S = getLoc();
2719   // Try for a vector register.
2720   if (!tryParseVectorRegister(Operands))
2721     return false;
2722
2723   // Try for a scalar register.
2724   int64_t Reg = tryParseRegister();
2725   if (Reg == -1)
2726     return true;
2727   Operands.push_back(
2728       ARM64Operand::CreateReg(Reg, false, S, getLoc(), getContext()));
2729
2730   // A small number of instructions (FMOVXDhighr, for example) have "[1]"
2731   // as a string token in the instruction itself.
2732   if (getLexer().getKind() == AsmToken::LBrac) {
2733     SMLoc LBracS = getLoc();
2734     Parser.Lex();
2735     const AsmToken &Tok = Parser.getTok();
2736     if (Tok.is(AsmToken::Integer)) {
2737       SMLoc IntS = getLoc();
2738       int64_t Val = Tok.getIntVal();
2739       if (Val == 1) {
2740         Parser.Lex();
2741         if (getLexer().getKind() == AsmToken::RBrac) {
2742           SMLoc RBracS = getLoc();
2743           Parser.Lex();
2744           Operands.push_back(
2745               ARM64Operand::CreateToken("[", false, LBracS, getContext()));
2746           Operands.push_back(
2747               ARM64Operand::CreateToken("1", false, IntS, getContext()));
2748           Operands.push_back(
2749               ARM64Operand::CreateToken("]", false, RBracS, getContext()));
2750           return false;
2751         }
2752       }
2753     }
2754   }
2755
2756   return false;
2757 }
2758
2759 /// tryParseNoIndexMemory - Custom parser method for memory operands that
2760 ///                         do not allow base regisrer writeback modes,
2761 ///                         or those that handle writeback separately from
2762 ///                         the memory operand (like the AdvSIMD ldX/stX
2763 ///                         instructions.
2764 ARM64AsmParser::OperandMatchResultTy
2765 ARM64AsmParser::tryParseNoIndexMemory(OperandVector &Operands) {
2766   if (Parser.getTok().isNot(AsmToken::LBrac))
2767     return MatchOperand_NoMatch;
2768   SMLoc S = getLoc();
2769   Parser.Lex(); // Eat left bracket token.
2770
2771   const AsmToken &BaseRegTok = Parser.getTok();
2772   if (BaseRegTok.isNot(AsmToken::Identifier)) {
2773     Error(BaseRegTok.getLoc(), "register expected");
2774     return MatchOperand_ParseFail;
2775   }
2776
2777   int64_t Reg = tryParseRegister();
2778   if (Reg == -1) {
2779     Error(BaseRegTok.getLoc(), "register expected");
2780     return MatchOperand_ParseFail;
2781   }
2782
2783   SMLoc E = getLoc();
2784   if (Parser.getTok().isNot(AsmToken::RBrac)) {
2785     Error(E, "']' expected");
2786     return MatchOperand_ParseFail;
2787   }
2788
2789   Parser.Lex(); // Eat right bracket token.
2790
2791   Operands.push_back(ARM64Operand::CreateMem(Reg, 0, S, E, E, getContext()));
2792   return MatchOperand_Success;
2793 }
2794
2795 /// parseMemory - Parse a memory operand for a basic load/store instruction.
2796 bool ARM64AsmParser::parseMemory(OperandVector &Operands) {
2797   assert(Parser.getTok().is(AsmToken::LBrac) && "Token is not a Left Bracket");
2798   SMLoc S = getLoc();
2799   Parser.Lex(); // Eat left bracket token.
2800
2801   const AsmToken &BaseRegTok = Parser.getTok();
2802   if (BaseRegTok.isNot(AsmToken::Identifier))
2803     return Error(BaseRegTok.getLoc(), "register expected");
2804
2805   int64_t Reg = tryParseRegister();
2806   if (Reg == -1)
2807     return Error(BaseRegTok.getLoc(), "register expected");
2808
2809   // If there is an offset expression, parse it.
2810   const MCExpr *OffsetExpr = 0;
2811   SMLoc OffsetLoc;
2812   if (Parser.getTok().is(AsmToken::Comma)) {
2813     Parser.Lex(); // Eat the comma.
2814     OffsetLoc = getLoc();
2815
2816     // Register offset
2817     const AsmToken &OffsetRegTok = Parser.getTok();
2818     int Reg2 = OffsetRegTok.is(AsmToken::Identifier) ? tryParseRegister() : -1;
2819     if (Reg2 != -1) {
2820       // Default shift is LSL, with an omitted shift.  We use the third bit of
2821       // the extend value to indicate presence/omission of the immediate offset.
2822       ARM64_AM::ExtendType ExtOp = ARM64_AM::UXTX;
2823       int64_t ShiftVal = 0;
2824       bool ExplicitShift = false;
2825
2826       if (Parser.getTok().is(AsmToken::Comma)) {
2827         // Embedded extend operand.
2828         Parser.Lex(); // Eat the comma
2829
2830         SMLoc ExtLoc = getLoc();
2831         const AsmToken &Tok = Parser.getTok();
2832         ExtOp = StringSwitch<ARM64_AM::ExtendType>(Tok.getString())
2833                     .Case("uxtw", ARM64_AM::UXTW)
2834                     .Case("lsl", ARM64_AM::UXTX) // Alias for UXTX
2835                     .Case("sxtw", ARM64_AM::SXTW)
2836                     .Case("sxtx", ARM64_AM::SXTX)
2837                     .Case("UXTW", ARM64_AM::UXTW)
2838                     .Case("LSL", ARM64_AM::UXTX) // Alias for UXTX
2839                     .Case("SXTW", ARM64_AM::SXTW)
2840                     .Case("SXTX", ARM64_AM::SXTX)
2841                     .Default(ARM64_AM::InvalidExtend);
2842         if (ExtOp == ARM64_AM::InvalidExtend)
2843           return Error(ExtLoc, "expected valid extend operation");
2844
2845         Parser.Lex(); // Eat the extend op.
2846
2847         // A 32-bit offset register is only valid for [SU]/XTW extend
2848         // operators.
2849         if (ARM64MCRegisterClasses[ARM64::GPR32allRegClassID].contains(Reg2)) {
2850          if (ExtOp != ARM64_AM::UXTW &&
2851             ExtOp != ARM64_AM::SXTW)
2852           return Error(ExtLoc, "32-bit general purpose offset register "
2853                                "requires sxtw or uxtw extend");
2854         } else if (!ARM64MCRegisterClasses[ARM64::GPR64allRegClassID].contains(
2855                        Reg2))
2856           return Error(OffsetLoc,
2857                        "64-bit general purpose offset register expected");
2858
2859         bool Hash = getLexer().is(AsmToken::Hash);
2860         if (getLexer().is(AsmToken::RBrac)) {
2861           // No immediate operand.
2862           if (ExtOp == ARM64_AM::UXTX)
2863             return Error(ExtLoc, "LSL extend requires immediate operand");
2864         } else if (Hash || getLexer().is(AsmToken::Integer)) {
2865           // Immediate operand.
2866           if (Hash)
2867             Parser.Lex(); // Eat the '#'
2868           const MCExpr *ImmVal;
2869           SMLoc ExprLoc = getLoc();
2870           if (getParser().parseExpression(ImmVal))
2871             return true;
2872           const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
2873           if (!MCE)
2874             return TokError("immediate value expected for extend operand");
2875
2876           ExplicitShift = true;
2877           ShiftVal = MCE->getValue();
2878           if (ShiftVal < 0 || ShiftVal > 4)
2879             return Error(ExprLoc, "immediate operand out of range");
2880         } else
2881           return Error(getLoc(), "expected immediate operand");
2882       }
2883
2884       if (Parser.getTok().isNot(AsmToken::RBrac))
2885         return Error(getLoc(), "']' expected");
2886
2887       Parser.Lex(); // Eat right bracket token.
2888
2889       SMLoc E = getLoc();
2890       Operands.push_back(ARM64Operand::CreateRegOffsetMem(
2891           Reg, Reg2, ExtOp, ShiftVal, ExplicitShift, S, E, getContext()));
2892       return false;
2893
2894       // Immediate expressions.
2895     } else if (Parser.getTok().is(AsmToken::Hash) ||
2896                Parser.getTok().is(AsmToken::Integer)) {
2897       if (Parser.getTok().is(AsmToken::Hash))
2898         Parser.Lex(); // Eat hash token.
2899
2900       if (parseSymbolicImmVal(OffsetExpr))
2901         return true;
2902     } else {
2903       // FIXME: We really should make sure that we're dealing with a LDR/STR
2904       // instruction that can legally have a symbolic expression here.
2905       // Symbol reference.
2906       if (Parser.getTok().isNot(AsmToken::Identifier) &&
2907           Parser.getTok().isNot(AsmToken::String))
2908         return Error(getLoc(), "identifier or immediate expression expected");
2909       if (getParser().parseExpression(OffsetExpr))
2910         return true;
2911       // If this is a plain ref, Make sure a legal variant kind was specified.
2912       // Otherwise, it's a more complicated expression and we have to just
2913       // assume it's OK and let the relocation stuff puke if it's not.
2914       ARM64MCExpr::VariantKind ELFRefKind;
2915       MCSymbolRefExpr::VariantKind DarwinRefKind;
2916       const MCConstantExpr *Addend;
2917       if (classifySymbolRef(OffsetExpr, ELFRefKind, DarwinRefKind, Addend) &&
2918           Addend == 0) {
2919         assert(ELFRefKind == ARM64MCExpr::VK_INVALID &&
2920                "ELF symbol modifiers not supported here yet");
2921
2922         switch (DarwinRefKind) {
2923         default:
2924           return Error(getLoc(), "expected @pageoff or @gotpageoff modifier");
2925         case MCSymbolRefExpr::VK_GOTPAGEOFF:
2926         case MCSymbolRefExpr::VK_PAGEOFF:
2927         case MCSymbolRefExpr::VK_TLVPPAGEOFF:
2928           // These are what we're expecting.
2929           break;
2930         }
2931       }
2932     }
2933   }
2934
2935   SMLoc E = getLoc();
2936   if (Parser.getTok().isNot(AsmToken::RBrac))
2937     return Error(E, "']' expected");
2938
2939   Parser.Lex(); // Eat right bracket token.
2940
2941   // Create the memory operand.
2942   Operands.push_back(
2943       ARM64Operand::CreateMem(Reg, OffsetExpr, S, E, OffsetLoc, getContext()));
2944
2945   // Check for a '!', indicating pre-indexed addressing with writeback.
2946   if (Parser.getTok().is(AsmToken::Exclaim)) {
2947     // There needs to have been an immediate or wback doesn't make sense.
2948     if (!OffsetExpr)
2949       return Error(E, "missing offset for pre-indexed addressing");
2950     // Pre-indexed with writeback must have a constant expression for the
2951     // offset. FIXME: Theoretically, we'd like to allow fixups so long
2952     // as they don't require a relocation.
2953     if (!isa<MCConstantExpr>(OffsetExpr))
2954       return Error(OffsetLoc, "constant immediate expression expected");
2955
2956     // Create the Token operand for the '!'.
2957     Operands.push_back(ARM64Operand::CreateToken(
2958         "!", false, Parser.getTok().getLoc(), getContext()));
2959     Parser.Lex(); // Eat the '!' token.
2960   }
2961
2962   return false;
2963 }
2964
2965 bool ARM64AsmParser::parseSymbolicImmVal(const MCExpr *&ImmVal) {
2966   bool HasELFModifier = false;
2967   ARM64MCExpr::VariantKind RefKind;
2968
2969   if (Parser.getTok().is(AsmToken::Colon)) {
2970     Parser.Lex(); // Eat ':"
2971     HasELFModifier = true;
2972
2973     if (Parser.getTok().isNot(AsmToken::Identifier)) {
2974       Error(Parser.getTok().getLoc(),
2975             "expect relocation specifier in operand after ':'");
2976       return true;
2977     }
2978
2979     std::string LowerCase = Parser.getTok().getIdentifier().lower();
2980     RefKind = StringSwitch<ARM64MCExpr::VariantKind>(LowerCase)
2981                   .Case("lo12", ARM64MCExpr::VK_LO12)
2982                   .Case("abs_g3", ARM64MCExpr::VK_ABS_G3)
2983                   .Case("abs_g2", ARM64MCExpr::VK_ABS_G2)
2984                   .Case("abs_g2_nc", ARM64MCExpr::VK_ABS_G2_NC)
2985                   .Case("abs_g1", ARM64MCExpr::VK_ABS_G1)
2986                   .Case("abs_g1_nc", ARM64MCExpr::VK_ABS_G1_NC)
2987                   .Case("abs_g0", ARM64MCExpr::VK_ABS_G0)
2988                   .Case("abs_g0_nc", ARM64MCExpr::VK_ABS_G0_NC)
2989                   .Case("dtprel_g2", ARM64MCExpr::VK_DTPREL_G2)
2990                   .Case("dtprel_g1", ARM64MCExpr::VK_DTPREL_G1)
2991                   .Case("dtprel_g1_nc", ARM64MCExpr::VK_DTPREL_G1_NC)
2992                   .Case("dtprel_g0", ARM64MCExpr::VK_DTPREL_G0)
2993                   .Case("dtprel_g0_nc", ARM64MCExpr::VK_DTPREL_G0_NC)
2994                   .Case("dtprel_lo12", ARM64MCExpr::VK_DTPREL_LO12)
2995                   .Case("dtprel_lo12_nc", ARM64MCExpr::VK_DTPREL_LO12_NC)
2996                   .Case("tprel_g2", ARM64MCExpr::VK_TPREL_G2)
2997                   .Case("tprel_g1", ARM64MCExpr::VK_TPREL_G1)
2998                   .Case("tprel_g1_nc", ARM64MCExpr::VK_TPREL_G1_NC)
2999                   .Case("tprel_g0", ARM64MCExpr::VK_TPREL_G0)
3000                   .Case("tprel_g0_nc", ARM64MCExpr::VK_TPREL_G0_NC)
3001                   .Case("tprel_lo12", ARM64MCExpr::VK_TPREL_LO12)
3002                   .Case("tprel_lo12_nc", ARM64MCExpr::VK_TPREL_LO12_NC)
3003                   .Case("tlsdesc_lo12", ARM64MCExpr::VK_TLSDESC_LO12)
3004                   .Case("got", ARM64MCExpr::VK_GOT_PAGE)
3005                   .Case("got_lo12", ARM64MCExpr::VK_GOT_LO12)
3006                   .Case("gottprel", ARM64MCExpr::VK_GOTTPREL_PAGE)
3007                   .Case("gottprel_lo12", ARM64MCExpr::VK_GOTTPREL_LO12_NC)
3008                   .Case("gottprel_g1", ARM64MCExpr::VK_GOTTPREL_G1)
3009                   .Case("gottprel_g0_nc", ARM64MCExpr::VK_GOTTPREL_G0_NC)
3010                   .Case("tlsdesc", ARM64MCExpr::VK_TLSDESC_PAGE)
3011                   .Default(ARM64MCExpr::VK_INVALID);
3012
3013     if (RefKind == ARM64MCExpr::VK_INVALID) {
3014       Error(Parser.getTok().getLoc(),
3015             "expect relocation specifier in operand after ':'");
3016       return true;
3017     }
3018
3019     Parser.Lex(); // Eat identifier
3020
3021     if (Parser.getTok().isNot(AsmToken::Colon)) {
3022       Error(Parser.getTok().getLoc(), "expect ':' after relocation specifier");
3023       return true;
3024     }
3025     Parser.Lex(); // Eat ':'
3026   }
3027
3028   if (getParser().parseExpression(ImmVal))
3029     return true;
3030
3031   if (HasELFModifier)
3032     ImmVal = ARM64MCExpr::Create(ImmVal, RefKind, getContext());
3033
3034   return false;
3035 }
3036
3037 /// parseVectorList - Parse a vector list operand for AdvSIMD instructions.
3038 bool ARM64AsmParser::parseVectorList(OperandVector &Operands) {
3039   assert(Parser.getTok().is(AsmToken::LCurly) && "Token is not a Left Bracket");
3040   SMLoc S = getLoc();
3041   Parser.Lex(); // Eat left bracket token.
3042   StringRef Kind;
3043   int64_t FirstReg = tryMatchVectorRegister(Kind, true);
3044   if (FirstReg == -1)
3045     return true;
3046   int64_t PrevReg = FirstReg;
3047   unsigned Count = 1;
3048
3049   if (Parser.getTok().is(AsmToken::Minus)) {
3050     Parser.Lex(); // Eat the minus.
3051
3052     SMLoc Loc = getLoc();
3053     StringRef NextKind;
3054     int64_t Reg = tryMatchVectorRegister(NextKind, true);
3055     if (Reg == -1)
3056       return true;
3057     // Any Kind suffices must match on all regs in the list.
3058     if (Kind != NextKind)
3059       return Error(Loc, "mismatched register size suffix");
3060
3061     unsigned Space = (PrevReg < Reg) ? (Reg - PrevReg) : (Reg + 32 - PrevReg);
3062
3063     if (Space == 0 || Space > 3) {
3064       return Error(Loc, "invalid number of vectors");
3065     }
3066
3067     Count += Space;
3068   }
3069   else {
3070     while (Parser.getTok().is(AsmToken::Comma)) {
3071       Parser.Lex(); // Eat the comma token.
3072
3073       SMLoc Loc = getLoc();
3074       StringRef NextKind;
3075       int64_t Reg = tryMatchVectorRegister(NextKind, true);
3076       if (Reg == -1)
3077         return true;
3078       // Any Kind suffices must match on all regs in the list.
3079       if (Kind != NextKind)
3080         return Error(Loc, "mismatched register size suffix");
3081
3082       // Registers must be incremental (with wraparound at 31)
3083       if (getContext().getRegisterInfo()->getEncodingValue(Reg) !=
3084           (getContext().getRegisterInfo()->getEncodingValue(PrevReg) + 1) % 32)
3085        return Error(Loc, "registers must be sequential");
3086
3087       PrevReg = Reg;
3088       ++Count;
3089     }
3090   }
3091
3092   if (Parser.getTok().is(AsmToken::EndOfStatement))
3093     Error(getLoc(), "'}' expected");
3094   Parser.Lex(); // Eat the '}' token.
3095
3096   unsigned NumElements = 0;
3097   char ElementKind = 0;
3098   if (!Kind.empty())
3099     parseValidVectorKind(Kind, NumElements, ElementKind);
3100
3101   Operands.push_back(ARM64Operand::CreateVectorList(
3102       FirstReg, Count, NumElements, ElementKind, S, getLoc(), getContext()));
3103
3104   // If there is an index specifier following the list, parse that too.
3105   if (Parser.getTok().is(AsmToken::LBrac)) {
3106     SMLoc SIdx = getLoc();
3107     Parser.Lex(); // Eat left bracket token.
3108
3109     const MCExpr *ImmVal;
3110     if (getParser().parseExpression(ImmVal))
3111       return false;
3112     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3113     if (!MCE) {
3114       TokError("immediate value expected for vector index");
3115       return false;
3116     }
3117
3118     SMLoc E = getLoc();
3119     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3120       Error(E, "']' expected");
3121       return false;
3122     }
3123
3124     Parser.Lex(); // Eat right bracket token.
3125
3126     Operands.push_back(ARM64Operand::CreateVectorIndex(MCE->getValue(), SIdx, E,
3127                                                        getContext()));
3128   }
3129   return false;
3130 }
3131
3132 /// parseOperand - Parse a arm instruction operand.  For now this parses the
3133 /// operand regardless of the mnemonic.
3134 bool ARM64AsmParser::parseOperand(OperandVector &Operands, bool isCondCode,
3135                                   bool invertCondCode) {
3136   // Check if the current operand has a custom associated parser, if so, try to
3137   // custom parse the operand, or fallback to the general approach.
3138   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
3139   if (ResTy == MatchOperand_Success)
3140     return false;
3141   // If there wasn't a custom match, try the generic matcher below. Otherwise,
3142   // there was a match, but an error occurred, in which case, just return that
3143   // the operand parsing failed.
3144   if (ResTy == MatchOperand_ParseFail)
3145     return true;
3146
3147   // Nothing custom, so do general case parsing.
3148   SMLoc S, E;
3149   switch (getLexer().getKind()) {
3150   default: {
3151     SMLoc S = getLoc();
3152     const MCExpr *Expr;
3153     if (parseSymbolicImmVal(Expr))
3154       return Error(S, "invalid operand");
3155
3156     SMLoc E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
3157     Operands.push_back(ARM64Operand::CreateImm(Expr, S, E, getContext()));
3158     return false;
3159   }
3160   case AsmToken::LBrac:
3161     return parseMemory(Operands);
3162   case AsmToken::LCurly:
3163     return parseVectorList(Operands);
3164   case AsmToken::Identifier: {
3165     // If we're expecting a Condition Code operand, then just parse that.
3166     if (isCondCode)
3167       return parseCondCode(Operands, invertCondCode);
3168
3169     // If it's a register name, parse it.
3170     if (!parseRegister(Operands))
3171       return false;
3172
3173     // This could be an optional "shift" operand.
3174     if (!parseOptionalShift(Operands))
3175       return false;
3176
3177     // Or maybe it could be an optional "extend" operand.
3178     if (!parseOptionalExtend(Operands))
3179       return false;
3180
3181     // This was not a register so parse other operands that start with an
3182     // identifier (like labels) as expressions and create them as immediates.
3183     const MCExpr *IdVal;
3184     S = getLoc();
3185     if (getParser().parseExpression(IdVal))
3186       return true;
3187
3188     E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
3189     Operands.push_back(ARM64Operand::CreateImm(IdVal, S, E, getContext()));
3190     return false;
3191   }
3192   case AsmToken::Integer:
3193   case AsmToken::Real:
3194   case AsmToken::Hash: {
3195     // #42 -> immediate.
3196     S = getLoc();
3197     if (getLexer().is(AsmToken::Hash))
3198       Parser.Lex();
3199
3200     // The only Real that should come through here is a literal #0.0 for
3201     // the fcmp[e] r, #0.0 instructions. They expect raw token operands,
3202     // so convert the value.
3203     const AsmToken &Tok = Parser.getTok();
3204     if (Tok.is(AsmToken::Real)) {
3205       APFloat RealVal(APFloat::IEEEdouble, Tok.getString());
3206       uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
3207       if (IntVal != 0 || (Mnemonic != "fcmp" && Mnemonic != "fcmpe"))
3208         return TokError("unexpected floating point literal");
3209       Parser.Lex(); // Eat the token.
3210
3211       Operands.push_back(
3212           ARM64Operand::CreateToken("#0", false, S, getContext()));
3213       Operands.push_back(
3214           ARM64Operand::CreateToken(".0", false, S, getContext()));
3215       return false;
3216     }
3217
3218     const MCExpr *ImmVal;
3219     if (parseSymbolicImmVal(ImmVal))
3220       return true;
3221
3222     E = SMLoc::getFromPointer(getLoc().getPointer() - 1);
3223     Operands.push_back(ARM64Operand::CreateImm(ImmVal, S, E, getContext()));
3224     return false;
3225   }
3226   }
3227 }
3228
3229 /// ParseInstruction - Parse an ARM64 instruction mnemonic followed by its
3230 /// operands.
3231 bool ARM64AsmParser::ParseInstruction(ParseInstructionInfo &Info,
3232                                       StringRef Name, SMLoc NameLoc,
3233                                       OperandVector &Operands) {
3234   // Create the leading tokens for the mnemonic, split by '.' characters.
3235   size_t Start = 0, Next = Name.find('.');
3236   StringRef Head = Name.slice(Start, Next);
3237
3238   // IC, DC, AT, and TLBI instructions are aliases for the SYS instruction.
3239   if (Head == "ic" || Head == "dc" || Head == "at" || Head == "tlbi")
3240     return parseSysAlias(Head, NameLoc, Operands);
3241
3242   Operands.push_back(
3243       ARM64Operand::CreateToken(Head, false, NameLoc, getContext()));
3244   Mnemonic = Head;
3245
3246   // Handle condition codes for a branch mnemonic
3247   if (Head == "b" && Next != StringRef::npos) {
3248     Start = Next;
3249     Next = Name.find('.', Start + 1);
3250     Head = Name.slice(Start + 1, Next);
3251
3252     SMLoc SuffixLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
3253                                             (Head.data() - Name.data()));
3254     unsigned CC = parseCondCodeString(Head);
3255     if (CC == ARM64CC::Invalid)
3256       return Error(SuffixLoc, "invalid condition code");
3257     const MCExpr *CCExpr = MCConstantExpr::Create(CC, getContext());
3258     Operands.push_back(
3259         ARM64Operand::CreateImm(CCExpr, NameLoc, NameLoc, getContext()));
3260   }
3261
3262   // Add the remaining tokens in the mnemonic.
3263   while (Next != StringRef::npos) {
3264     Start = Next;
3265     Next = Name.find('.', Start + 1);
3266     Head = Name.slice(Start, Next);
3267     SMLoc SuffixLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
3268                                             (Head.data() - Name.data()) + 1);
3269     Operands.push_back(
3270         ARM64Operand::CreateToken(Head, true, SuffixLoc, getContext()));
3271   }
3272
3273   // Conditional compare instructions have a Condition Code operand, which needs
3274   // to be parsed and an immediate operand created.
3275   bool condCodeFourthOperand =
3276       (Head == "ccmp" || Head == "ccmn" || Head == "fccmp" ||
3277        Head == "fccmpe" || Head == "fcsel" || Head == "csel" ||
3278        Head == "csinc" || Head == "csinv" || Head == "csneg");
3279
3280   // These instructions are aliases to some of the conditional select
3281   // instructions. However, the condition code is inverted in the aliased
3282   // instruction.
3283   //
3284   // FIXME: Is this the correct way to handle these? Or should the parser
3285   //        generate the aliased instructions directly?
3286   bool condCodeSecondOperand = (Head == "cset" || Head == "csetm");
3287   bool condCodeThirdOperand =
3288       (Head == "cinc" || Head == "cinv" || Head == "cneg");
3289
3290   // Read the remaining operands.
3291   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3292     // Read the first operand.
3293     if (parseOperand(Operands, false, false)) {
3294       Parser.eatToEndOfStatement();
3295       return true;
3296     }
3297
3298     unsigned N = 2;
3299     while (getLexer().is(AsmToken::Comma)) {
3300       Parser.Lex(); // Eat the comma.
3301
3302       // Parse and remember the operand.
3303       if (parseOperand(Operands, (N == 4 && condCodeFourthOperand) ||
3304                                      (N == 3 && condCodeThirdOperand) ||
3305                                      (N == 2 && condCodeSecondOperand),
3306                        condCodeSecondOperand || condCodeThirdOperand)) {
3307         Parser.eatToEndOfStatement();
3308         return true;
3309       }
3310
3311       ++N;
3312     }
3313   }
3314
3315   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3316     SMLoc Loc = Parser.getTok().getLoc();
3317     Parser.eatToEndOfStatement();
3318     return Error(Loc, "unexpected token in argument list");
3319   }
3320
3321   Parser.Lex(); // Consume the EndOfStatement
3322   return false;
3323 }
3324
3325 // FIXME: This entire function is a giant hack to provide us with decent
3326 // operand range validation/diagnostics until TableGen/MC can be extended
3327 // to support autogeneration of this kind of validation.
3328 bool ARM64AsmParser::validateInstruction(MCInst &Inst,
3329                                          SmallVectorImpl<SMLoc> &Loc) {
3330   const MCRegisterInfo *RI = getContext().getRegisterInfo();
3331   // Check for indexed addressing modes w/ the base register being the
3332   // same as a destination/source register or pair load where
3333   // the Rt == Rt2. All of those are undefined behaviour.
3334   switch (Inst.getOpcode()) {
3335   case ARM64::LDPSWpre:
3336   case ARM64::LDPWpost:
3337   case ARM64::LDPWpre:
3338   case ARM64::LDPXpost:
3339   case ARM64::LDPXpre: {
3340     unsigned Rt = Inst.getOperand(0).getReg();
3341     unsigned Rt2 = Inst.getOperand(1).getReg();
3342     unsigned Rn = Inst.getOperand(2).getReg();
3343     if (RI->isSubRegisterEq(Rn, Rt))
3344       return Error(Loc[0], "unpredictable LDP instruction, writeback base "
3345                            "is also a destination");
3346     if (RI->isSubRegisterEq(Rn, Rt2))
3347       return Error(Loc[1], "unpredictable LDP instruction, writeback base "
3348                            "is also a destination");
3349     // FALLTHROUGH
3350   }
3351   case ARM64::LDPDpost:
3352   case ARM64::LDPDpre:
3353   case ARM64::LDPQpost:
3354   case ARM64::LDPQpre:
3355   case ARM64::LDPSpost:
3356   case ARM64::LDPSpre:
3357   case ARM64::LDPSWpost:
3358   case ARM64::LDPDi:
3359   case ARM64::LDPQi:
3360   case ARM64::LDPSi:
3361   case ARM64::LDPSWi:
3362   case ARM64::LDPWi:
3363   case ARM64::LDPXi: {
3364     unsigned Rt = Inst.getOperand(0).getReg();
3365     unsigned Rt2 = Inst.getOperand(1).getReg();
3366     if (Rt == Rt2)
3367       return Error(Loc[1], "unpredictable LDP instruction, Rt2==Rt");
3368     break;
3369   }
3370   case ARM64::STPDpost:
3371   case ARM64::STPDpre:
3372   case ARM64::STPQpost:
3373   case ARM64::STPQpre:
3374   case ARM64::STPSpost:
3375   case ARM64::STPSpre:
3376   case ARM64::STPWpost:
3377   case ARM64::STPWpre:
3378   case ARM64::STPXpost:
3379   case ARM64::STPXpre: {
3380     unsigned Rt = Inst.getOperand(0).getReg();
3381     unsigned Rt2 = Inst.getOperand(1).getReg();
3382     unsigned Rn = Inst.getOperand(2).getReg();
3383     if (RI->isSubRegisterEq(Rn, Rt))
3384       return Error(Loc[0], "unpredictable STP instruction, writeback base "
3385                            "is also a source");
3386     if (RI->isSubRegisterEq(Rn, Rt2))
3387       return Error(Loc[1], "unpredictable STP instruction, writeback base "
3388                            "is also a source");
3389     break;
3390   }
3391   case ARM64::LDRBBpre:
3392   case ARM64::LDRBpre:
3393   case ARM64::LDRHHpre:
3394   case ARM64::LDRHpre:
3395   case ARM64::LDRSBWpre:
3396   case ARM64::LDRSBXpre:
3397   case ARM64::LDRSHWpre:
3398   case ARM64::LDRSHXpre:
3399   case ARM64::LDRSWpre:
3400   case ARM64::LDRWpre:
3401   case ARM64::LDRXpre:
3402   case ARM64::LDRBBpost:
3403   case ARM64::LDRBpost:
3404   case ARM64::LDRHHpost:
3405   case ARM64::LDRHpost:
3406   case ARM64::LDRSBWpost:
3407   case ARM64::LDRSBXpost:
3408   case ARM64::LDRSHWpost:
3409   case ARM64::LDRSHXpost:
3410   case ARM64::LDRSWpost:
3411   case ARM64::LDRWpost:
3412   case ARM64::LDRXpost: {
3413     unsigned Rt = Inst.getOperand(0).getReg();
3414     unsigned Rn = Inst.getOperand(1).getReg();
3415     if (RI->isSubRegisterEq(Rn, Rt))
3416       return Error(Loc[0], "unpredictable LDR instruction, writeback base "
3417                            "is also a source");
3418     break;
3419   }
3420   case ARM64::STRBBpost:
3421   case ARM64::STRBpost:
3422   case ARM64::STRHHpost:
3423   case ARM64::STRHpost:
3424   case ARM64::STRWpost:
3425   case ARM64::STRXpost:
3426   case ARM64::STRBBpre:
3427   case ARM64::STRBpre:
3428   case ARM64::STRHHpre:
3429   case ARM64::STRHpre:
3430   case ARM64::STRWpre:
3431   case ARM64::STRXpre: {
3432     unsigned Rt = Inst.getOperand(0).getReg();
3433     unsigned Rn = Inst.getOperand(1).getReg();
3434     if (RI->isSubRegisterEq(Rn, Rt))
3435       return Error(Loc[0], "unpredictable STR instruction, writeback base "
3436                            "is also a source");
3437     break;
3438   }
3439   }
3440
3441   // Now check immediate ranges. Separate from the above as there is overlap
3442   // in the instructions being checked and this keeps the nested conditionals
3443   // to a minimum.
3444   switch (Inst.getOpcode()) {
3445   case ARM64::ANDWrs:
3446   case ARM64::ANDSWrs:
3447   case ARM64::EORWrs:
3448   case ARM64::ORRWrs: {
3449     if (!Inst.getOperand(3).isImm())
3450       return Error(Loc[3], "immediate value expected");
3451     int64_t shifter = Inst.getOperand(3).getImm();
3452     ARM64_AM::ShiftType ST = ARM64_AM::getShiftType(shifter);
3453     if (ST == ARM64_AM::LSL && shifter > 31)
3454       return Error(Loc[3], "shift value out of range");
3455     return false;
3456   }
3457   case ARM64::ADDSWri:
3458   case ARM64::ADDSXri:
3459   case ARM64::ADDWri:
3460   case ARM64::ADDXri:
3461   case ARM64::SUBSWri:
3462   case ARM64::SUBSXri:
3463   case ARM64::SUBWri:
3464   case ARM64::SUBXri: {
3465     if (!Inst.getOperand(3).isImm())
3466       return Error(Loc[3], "immediate value expected");
3467     int64_t shifter = Inst.getOperand(3).getImm();
3468     if (shifter != 0 && shifter != 12)
3469       return Error(Loc[3], "shift value out of range");
3470     // The imm12 operand can be an expression. Validate that it's legit.
3471     // FIXME: We really, really want to allow arbitrary expressions here
3472     // and resolve the value and validate the result at fixup time, but
3473     // that's hard as we have long since lost any source information we
3474     // need to generate good diagnostics by that point.
3475     if (Inst.getOpcode() == ARM64::ADDXri && Inst.getOperand(2).isExpr()) {
3476       const MCExpr *Expr = Inst.getOperand(2).getExpr();
3477       ARM64MCExpr::VariantKind ELFRefKind;
3478       MCSymbolRefExpr::VariantKind DarwinRefKind;
3479       const MCConstantExpr *Addend;
3480       if (!classifySymbolRef(Expr, ELFRefKind, DarwinRefKind, Addend)) {
3481         return Error(Loc[2], "invalid immediate expression");
3482       }
3483
3484       if (DarwinRefKind == MCSymbolRefExpr::VK_PAGEOFF ||
3485           DarwinRefKind == MCSymbolRefExpr::VK_TLVPPAGEOFF ||
3486           ELFRefKind == ARM64MCExpr::VK_LO12 ||
3487           ELFRefKind == ARM64MCExpr::VK_DTPREL_LO12 ||
3488           ELFRefKind == ARM64MCExpr::VK_DTPREL_LO12_NC ||
3489           ELFRefKind == ARM64MCExpr::VK_TPREL_LO12 ||
3490           ELFRefKind == ARM64MCExpr::VK_TPREL_LO12_NC ||
3491           ELFRefKind == ARM64MCExpr::VK_TLSDESC_LO12) {
3492         // Note that we don't range-check the addend. It's adjusted
3493         // modulo page size when converted, so there is no "out of range"
3494         // condition when using @pageoff. Any validity checking for the value
3495         // was done in the is*() predicate function.
3496         return false;
3497       } else if (DarwinRefKind == MCSymbolRefExpr::VK_GOTPAGEOFF) {
3498         // @gotpageoff can only be used directly, not with an addend.
3499         return Addend != 0;
3500       }
3501
3502       // Otherwise, we're not sure, so don't allow it for now.
3503       return Error(Loc[2], "invalid immediate expression");
3504     }
3505
3506     // If it's anything but an immediate, it's not legit.
3507     if (!Inst.getOperand(2).isImm())
3508       return Error(Loc[2], "invalid immediate expression");
3509     int64_t imm = Inst.getOperand(2).getImm();
3510     if (imm > 4095 || imm < 0)
3511       return Error(Loc[2], "immediate value out of range");
3512     return false;
3513   }
3514   case ARM64::LDRBpre:
3515   case ARM64::LDRHpre:
3516   case ARM64::LDRSBWpre:
3517   case ARM64::LDRSBXpre:
3518   case ARM64::LDRSHWpre:
3519   case ARM64::LDRSHXpre:
3520   case ARM64::LDRWpre:
3521   case ARM64::LDRXpre:
3522   case ARM64::LDRSpre:
3523   case ARM64::LDRDpre:
3524   case ARM64::LDRQpre:
3525   case ARM64::STRBpre:
3526   case ARM64::STRHpre:
3527   case ARM64::STRWpre:
3528   case ARM64::STRXpre:
3529   case ARM64::STRSpre:
3530   case ARM64::STRDpre:
3531   case ARM64::STRQpre:
3532   case ARM64::LDRBpost:
3533   case ARM64::LDRHpost:
3534   case ARM64::LDRSBWpost:
3535   case ARM64::LDRSBXpost:
3536   case ARM64::LDRSHWpost:
3537   case ARM64::LDRSHXpost:
3538   case ARM64::LDRWpost:
3539   case ARM64::LDRXpost:
3540   case ARM64::LDRSpost:
3541   case ARM64::LDRDpost:
3542   case ARM64::LDRQpost:
3543   case ARM64::STRBpost:
3544   case ARM64::STRHpost:
3545   case ARM64::STRWpost:
3546   case ARM64::STRXpost:
3547   case ARM64::STRSpost:
3548   case ARM64::STRDpost:
3549   case ARM64::STRQpost:
3550   case ARM64::LDTRXi:
3551   case ARM64::LDTRWi:
3552   case ARM64::LDTRHi:
3553   case ARM64::LDTRBi:
3554   case ARM64::LDTRSHWi:
3555   case ARM64::LDTRSHXi:
3556   case ARM64::LDTRSBWi:
3557   case ARM64::LDTRSBXi:
3558   case ARM64::LDTRSWi:
3559   case ARM64::STTRWi:
3560   case ARM64::STTRXi:
3561   case ARM64::STTRHi:
3562   case ARM64::STTRBi:
3563   case ARM64::LDURWi:
3564   case ARM64::LDURXi:
3565   case ARM64::LDURSi:
3566   case ARM64::LDURDi:
3567   case ARM64::LDURQi:
3568   case ARM64::LDURHi:
3569   case ARM64::LDURBi:
3570   case ARM64::LDURSHWi:
3571   case ARM64::LDURSHXi:
3572   case ARM64::LDURSBWi:
3573   case ARM64::LDURSBXi:
3574   case ARM64::LDURSWi:
3575   case ARM64::PRFUMi:
3576   case ARM64::STURWi:
3577   case ARM64::STURXi:
3578   case ARM64::STURSi:
3579   case ARM64::STURDi:
3580   case ARM64::STURQi:
3581   case ARM64::STURHi:
3582   case ARM64::STURBi: {
3583     // FIXME: Should accept expressions and error in fixup evaluation
3584     // if out of range.
3585     if (!Inst.getOperand(2).isImm())
3586       return Error(Loc[1], "immediate value expected");
3587     int64_t offset = Inst.getOperand(2).getImm();
3588     if (offset > 255 || offset < -256)
3589       return Error(Loc[1], "offset value out of range");
3590     return false;
3591   }
3592   case ARM64::LDRSro:
3593   case ARM64::LDRWro:
3594   case ARM64::LDRSWro:
3595   case ARM64::STRWro:
3596   case ARM64::STRSro: {
3597     // FIXME: Should accept expressions and error in fixup evaluation
3598     // if out of range.
3599     if (!Inst.getOperand(3).isImm())
3600       return Error(Loc[1], "immediate value expected");
3601     int64_t shift = Inst.getOperand(3).getImm();
3602     ARM64_AM::ExtendType type = ARM64_AM::getMemExtendType(shift);
3603     if (type != ARM64_AM::UXTW && type != ARM64_AM::UXTX &&
3604         type != ARM64_AM::SXTW && type != ARM64_AM::SXTX)
3605       return Error(Loc[1], "shift type invalid");
3606     return false;
3607   }
3608   case ARM64::LDRDro:
3609   case ARM64::LDRQro:
3610   case ARM64::LDRXro:
3611   case ARM64::PRFMro:
3612   case ARM64::STRXro:
3613   case ARM64::STRDro:
3614   case ARM64::STRQro: {
3615     // FIXME: Should accept expressions and error in fixup evaluation
3616     // if out of range.
3617     if (!Inst.getOperand(3).isImm())
3618       return Error(Loc[1], "immediate value expected");
3619     int64_t shift = Inst.getOperand(3).getImm();
3620     ARM64_AM::ExtendType type = ARM64_AM::getMemExtendType(shift);
3621     if (type != ARM64_AM::UXTW && type != ARM64_AM::UXTX &&
3622         type != ARM64_AM::SXTW && type != ARM64_AM::SXTX)
3623       return Error(Loc[1], "shift type invalid");
3624     return false;
3625   }
3626   case ARM64::LDRHro:
3627   case ARM64::LDRHHro:
3628   case ARM64::LDRSHWro:
3629   case ARM64::LDRSHXro:
3630   case ARM64::STRHro:
3631   case ARM64::STRHHro: {
3632     // FIXME: Should accept expressions and error in fixup evaluation
3633     // if out of range.
3634     if (!Inst.getOperand(3).isImm())
3635       return Error(Loc[1], "immediate value expected");
3636     int64_t shift = Inst.getOperand(3).getImm();
3637     ARM64_AM::ExtendType type = ARM64_AM::getMemExtendType(shift);
3638     if (type != ARM64_AM::UXTW && type != ARM64_AM::UXTX &&
3639         type != ARM64_AM::SXTW && type != ARM64_AM::SXTX)
3640       return Error(Loc[1], "shift type invalid");
3641     return false;
3642   }
3643   case ARM64::LDRBro:
3644   case ARM64::LDRBBro:
3645   case ARM64::LDRSBWro:
3646   case ARM64::LDRSBXro:
3647   case ARM64::STRBro:
3648   case ARM64::STRBBro: {
3649     // FIXME: Should accept expressions and error in fixup evaluation
3650     // if out of range.
3651     if (!Inst.getOperand(3).isImm())
3652       return Error(Loc[1], "immediate value expected");
3653     int64_t shift = Inst.getOperand(3).getImm();
3654     ARM64_AM::ExtendType type = ARM64_AM::getMemExtendType(shift);
3655     if (type != ARM64_AM::UXTW && type != ARM64_AM::UXTX &&
3656         type != ARM64_AM::SXTW && type != ARM64_AM::SXTX)
3657       return Error(Loc[1], "shift type invalid");
3658     return false;
3659   }
3660   case ARM64::LDPWi:
3661   case ARM64::LDPXi:
3662   case ARM64::LDPSi:
3663   case ARM64::LDPDi:
3664   case ARM64::LDPQi:
3665   case ARM64::LDPSWi:
3666   case ARM64::STPWi:
3667   case ARM64::STPXi:
3668   case ARM64::STPSi:
3669   case ARM64::STPDi:
3670   case ARM64::STPQi:
3671   case ARM64::LDPWpre:
3672   case ARM64::LDPXpre:
3673   case ARM64::LDPSpre:
3674   case ARM64::LDPDpre:
3675   case ARM64::LDPQpre:
3676   case ARM64::LDPSWpre:
3677   case ARM64::STPWpre:
3678   case ARM64::STPXpre:
3679   case ARM64::STPSpre:
3680   case ARM64::STPDpre:
3681   case ARM64::STPQpre:
3682   case ARM64::LDPWpost:
3683   case ARM64::LDPXpost:
3684   case ARM64::LDPSpost:
3685   case ARM64::LDPDpost:
3686   case ARM64::LDPQpost:
3687   case ARM64::LDPSWpost:
3688   case ARM64::STPWpost:
3689   case ARM64::STPXpost:
3690   case ARM64::STPSpost:
3691   case ARM64::STPDpost:
3692   case ARM64::STPQpost:
3693   case ARM64::LDNPWi:
3694   case ARM64::LDNPXi:
3695   case ARM64::LDNPSi:
3696   case ARM64::LDNPDi:
3697   case ARM64::LDNPQi:
3698   case ARM64::STNPWi:
3699   case ARM64::STNPXi:
3700   case ARM64::STNPSi:
3701   case ARM64::STNPDi:
3702   case ARM64::STNPQi: {
3703     // FIXME: Should accept expressions and error in fixup evaluation
3704     // if out of range.
3705     if (!Inst.getOperand(3).isImm())
3706       return Error(Loc[2], "immediate value expected");
3707     int64_t offset = Inst.getOperand(3).getImm();
3708     if (offset > 63 || offset < -64)
3709       return Error(Loc[2], "offset value out of range");
3710     return false;
3711   }
3712   default:
3713     return false;
3714   }
3715 }
3716
3717 static void rewriteMOVI(ARM64AsmParser::OperandVector &Operands,
3718                         StringRef mnemonic, uint64_t imm, unsigned shift,
3719                         MCContext &Context) {
3720   ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[0]);
3721   ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
3722   Operands[0] =
3723       ARM64Operand::CreateToken(mnemonic, false, Op->getStartLoc(), Context);
3724
3725   const MCExpr *NewImm = MCConstantExpr::Create(imm >> shift, Context);
3726   Operands[2] = ARM64Operand::CreateImm(NewImm, Op2->getStartLoc(),
3727                                         Op2->getEndLoc(), Context);
3728
3729   Operands.push_back(ARM64Operand::CreateShifter(
3730       ARM64_AM::LSL, shift, Op2->getStartLoc(), Op2->getEndLoc(), Context));
3731   delete Op2;
3732   delete Op;
3733 }
3734
3735 static void rewriteMOVRSP(ARM64AsmParser::OperandVector &Operands,
3736                         MCContext &Context) {
3737   ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[0]);
3738   ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
3739   Operands[0] =
3740     ARM64Operand::CreateToken("add", false, Op->getStartLoc(), Context);
3741
3742   const MCExpr *Imm = MCConstantExpr::Create(0, Context);
3743   Operands.push_back(ARM64Operand::CreateImm(Imm, Op2->getStartLoc(),
3744                                              Op2->getEndLoc(), Context));
3745   Operands.push_back(ARM64Operand::CreateShifter(
3746       ARM64_AM::LSL, 0, Op2->getStartLoc(), Op2->getEndLoc(), Context));
3747
3748   delete Op;
3749 }
3750
3751 static void rewriteMOVR(ARM64AsmParser::OperandVector &Operands,
3752                         MCContext &Context) {
3753   ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[0]);
3754   ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
3755   Operands[0] =
3756     ARM64Operand::CreateToken("orr", false, Op->getStartLoc(), Context);
3757
3758   // Operands[2] becomes Operands[3].
3759   Operands.push_back(Operands[2]);
3760   // And Operands[2] becomes ZR.
3761   unsigned ZeroReg = ARM64::XZR;
3762   if (ARM64MCRegisterClasses[ARM64::GPR32allRegClassID].contains(
3763           Operands[2]->getReg()))
3764     ZeroReg = ARM64::WZR;
3765
3766   Operands[2] =
3767     ARM64Operand::CreateReg(ZeroReg, false, Op2->getStartLoc(),
3768                             Op2->getEndLoc(), Context);
3769
3770   delete Op;
3771 }
3772
3773 bool ARM64AsmParser::showMatchError(SMLoc Loc, unsigned ErrCode) {
3774   switch (ErrCode) {
3775   case Match_MissingFeature:
3776     return Error(Loc,
3777                  "instruction requires a CPU feature not currently enabled");
3778   case Match_InvalidOperand:
3779     return Error(Loc, "invalid operand for instruction");
3780   case Match_InvalidSuffix:
3781     return Error(Loc, "invalid type suffix for instruction");
3782   case Match_InvalidMemoryIndexedSImm9:
3783     return Error(Loc, "index must be an integer in range [-256,255].");
3784   case Match_InvalidMemoryIndexed32SImm7:
3785     return Error(Loc, "index must be a multiple of 4 in range [-256,252].");
3786   case Match_InvalidMemoryIndexed64SImm7:
3787     return Error(Loc, "index must be a multiple of 8 in range [-512,504].");
3788   case Match_InvalidMemoryIndexed128SImm7:
3789     return Error(Loc, "index must be a multiple of 16 in range [-1024,1008].");
3790   case Match_InvalidMemoryIndexed8:
3791     return Error(Loc, "index must be an integer in range [0,4095].");
3792   case Match_InvalidMemoryIndexed16:
3793     return Error(Loc, "index must be a multiple of 2 in range [0,8190].");
3794   case Match_InvalidMemoryIndexed32:
3795     return Error(Loc, "index must be a multiple of 4 in range [0,16380].");
3796   case Match_InvalidMemoryIndexed64:
3797     return Error(Loc, "index must be a multiple of 8 in range [0,32760].");
3798   case Match_InvalidMemoryIndexed128:
3799     return Error(Loc, "index must be a multiple of 16 in range [0,65520].");
3800   case Match_InvalidImm1_8:
3801     return Error(Loc, "immediate must be an integer in range [1,8].");
3802   case Match_InvalidImm1_16:
3803     return Error(Loc, "immediate must be an integer in range [1,16].");
3804   case Match_InvalidImm1_32:
3805     return Error(Loc, "immediate must be an integer in range [1,32].");
3806   case Match_InvalidImm1_64:
3807     return Error(Loc, "immediate must be an integer in range [1,64].");
3808   case Match_InvalidLabel:
3809     return Error(Loc, "expected label or encodable integer pc offset");
3810   case Match_MnemonicFail:
3811     return Error(Loc, "unrecognized instruction mnemonic");
3812   default:
3813     assert(0 && "unexpected error code!");
3814     return Error(Loc, "invalid instruction format");
3815   }
3816 }
3817
3818 bool ARM64AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
3819                                              OperandVector &Operands,
3820                                              MCStreamer &Out,
3821                                              unsigned &ErrorInfo,
3822                                              bool MatchingInlineAsm) {
3823   assert(!Operands.empty() && "Unexpect empty operand list!");
3824   ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[0]);
3825   assert(Op->isToken() && "Leading operand should always be a mnemonic!");
3826
3827   StringRef Tok = Op->getToken();
3828   // Translate CMN/CMP pseudos to ADDS/SUBS with zero register destination.
3829   // This needs to be done before the special handling of ADD/SUB immediates.
3830   if (Tok == "cmp" || Tok == "cmn") {
3831     // Replace the opcode with either ADDS or SUBS.
3832     const char *Repl = StringSwitch<const char *>(Tok)
3833                            .Case("cmp", "subs")
3834                            .Case("cmn", "adds")
3835                            .Default(0);
3836     assert(Repl && "Unknown compare instruction");
3837     delete Operands[0];
3838     Operands[0] = ARM64Operand::CreateToken(Repl, false, IDLoc, getContext());
3839
3840     // Insert WZR or XZR as destination operand.
3841     ARM64Operand *RegOp = static_cast<ARM64Operand *>(Operands[1]);
3842     unsigned ZeroReg;
3843     if (RegOp->isReg() &&
3844         ARM64MCRegisterClasses[ARM64::GPR32allRegClassID].contains(
3845             RegOp->getReg()))
3846       ZeroReg = ARM64::WZR;
3847     else
3848       ZeroReg = ARM64::XZR;
3849     Operands.insert(
3850         Operands.begin() + 1,
3851         ARM64Operand::CreateReg(ZeroReg, false, IDLoc, IDLoc, getContext()));
3852     // Update since we modified it above.
3853     ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[0]);
3854     Tok = Op->getToken();
3855   }
3856
3857   unsigned NumOperands = Operands.size();
3858
3859   if (Tok == "mov" && NumOperands == 3) {
3860     // The MOV mnemomic is aliased to movn/movz, depending on the value of
3861     // the immediate being instantiated.
3862     // FIXME: Catching this here is a total hack, and we should use tblgen
3863     // support to implement this instead as soon as it is available.
3864
3865     ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
3866     ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
3867     if (Op2->isImm()) {
3868       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op2->getImm())) {
3869         uint64_t Val = CE->getValue();
3870         uint64_t NVal = ~Val;
3871
3872         // If this is a 32-bit register and the value has none of the upper
3873         // set, clear the complemented upper 32-bits so the logic below works
3874         // for 32-bit registers too.
3875         ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
3876         if (Op1->isReg() &&
3877             ARM64MCRegisterClasses[ARM64::GPR32allRegClassID].contains(
3878                 Op1->getReg()) &&
3879             (Val & 0xFFFFFFFFULL) == Val)
3880           NVal &= 0x00000000FFFFFFFFULL;
3881
3882         // MOVK Rd, imm << 0
3883         if ((Val & 0xFFFF) == Val)
3884           rewriteMOVI(Operands, "movz", Val, 0, getContext());
3885
3886         // MOVK Rd, imm << 16
3887         else if ((Val & 0xFFFF0000ULL) == Val)
3888           rewriteMOVI(Operands, "movz", Val, 16, getContext());
3889
3890         // MOVK Rd, imm << 32
3891         else if ((Val & 0xFFFF00000000ULL) == Val)
3892           rewriteMOVI(Operands, "movz", Val, 32, getContext());
3893
3894         // MOVK Rd, imm << 48
3895         else if ((Val & 0xFFFF000000000000ULL) == Val)
3896           rewriteMOVI(Operands, "movz", Val, 48, getContext());
3897
3898         // MOVN Rd, (~imm << 0)
3899         else if ((NVal & 0xFFFFULL) == NVal)
3900           rewriteMOVI(Operands, "movn", NVal, 0, getContext());
3901
3902         // MOVN Rd, ~(imm << 16)
3903         else if ((NVal & 0xFFFF0000ULL) == NVal)
3904           rewriteMOVI(Operands, "movn", NVal, 16, getContext());
3905
3906         // MOVN Rd, ~(imm << 32)
3907         else if ((NVal & 0xFFFF00000000ULL) == NVal)
3908           rewriteMOVI(Operands, "movn", NVal, 32, getContext());
3909
3910         // MOVN Rd, ~(imm << 48)
3911         else if ((NVal & 0xFFFF000000000000ULL) == NVal)
3912           rewriteMOVI(Operands, "movn", NVal, 48, getContext());
3913       }
3914     } else if (Op1->isReg() && Op2->isReg()) {
3915       // reg->reg move.
3916       unsigned Reg1 = Op1->getReg();
3917       unsigned Reg2 = Op2->getReg();
3918       if ((Reg1 == ARM64::SP &&
3919            ARM64MCRegisterClasses[ARM64::GPR64allRegClassID].contains(Reg2)) ||
3920           (Reg2 == ARM64::SP &&
3921            ARM64MCRegisterClasses[ARM64::GPR64allRegClassID].contains(Reg1)) ||
3922           (Reg1 == ARM64::WSP &&
3923            ARM64MCRegisterClasses[ARM64::GPR32allRegClassID].contains(Reg2)) ||
3924           (Reg2 == ARM64::WSP &&
3925            ARM64MCRegisterClasses[ARM64::GPR32allRegClassID].contains(Reg1)))
3926         rewriteMOVRSP(Operands, getContext());
3927       else
3928         rewriteMOVR(Operands, getContext());
3929     }
3930   } else if (NumOperands == 4) {
3931     if (Tok == "add" || Tok == "adds" || Tok == "sub" || Tok == "subs") {
3932       // Handle the uimm24 immediate form, where the shift is not specified.
3933       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
3934       if (Op3->isImm()) {
3935         if (const MCConstantExpr *CE =
3936                 dyn_cast<MCConstantExpr>(Op3->getImm())) {
3937           uint64_t Val = CE->getValue();
3938           if (Val >= (1 << 24)) {
3939             Error(IDLoc, "immediate value is too large");
3940             return true;
3941           }
3942           if (Val < (1 << 12)) {
3943             Operands.push_back(ARM64Operand::CreateShifter(
3944                 ARM64_AM::LSL, 0, IDLoc, IDLoc, getContext()));
3945           } else if ((Val & 0xfff) == 0) {
3946             delete Operands[3];
3947             CE = MCConstantExpr::Create(Val >> 12, getContext());
3948             Operands[3] =
3949                 ARM64Operand::CreateImm(CE, IDLoc, IDLoc, getContext());
3950             Operands.push_back(ARM64Operand::CreateShifter(
3951                 ARM64_AM::LSL, 12, IDLoc, IDLoc, getContext()));
3952           } else {
3953             Error(IDLoc, "immediate value is too large");
3954             return true;
3955           }
3956         } else {
3957           Operands.push_back(ARM64Operand::CreateShifter(
3958               ARM64_AM::LSL, 0, IDLoc, IDLoc, getContext()));
3959         }
3960       }
3961
3962       // FIXME: Horible hack to handle the LSL -> UBFM alias.
3963     } else if (NumOperands == 4 && Tok == "lsl") {
3964       ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
3965       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
3966       if (Op2->isReg() && Op3->isImm()) {
3967         const MCConstantExpr *Op3CE = dyn_cast<MCConstantExpr>(Op3->getImm());
3968         if (Op3CE) {
3969           uint64_t Op3Val = Op3CE->getValue();
3970           uint64_t NewOp3Val = 0;
3971           uint64_t NewOp4Val = 0;
3972           if (ARM64MCRegisterClasses[ARM64::GPR32allRegClassID].contains(
3973                   Op2->getReg())) {
3974             NewOp3Val = (32 - Op3Val) & 0x1f;
3975             NewOp4Val = 31 - Op3Val;
3976           } else {
3977             NewOp3Val = (64 - Op3Val) & 0x3f;
3978             NewOp4Val = 63 - Op3Val;
3979           }
3980
3981           const MCExpr *NewOp3 =
3982               MCConstantExpr::Create(NewOp3Val, getContext());
3983           const MCExpr *NewOp4 =
3984               MCConstantExpr::Create(NewOp4Val, getContext());
3985
3986           Operands[0] = ARM64Operand::CreateToken(
3987               "ubfm", false, Op->getStartLoc(), getContext());
3988           Operands[3] = ARM64Operand::CreateImm(NewOp3, Op3->getStartLoc(),
3989                                                 Op3->getEndLoc(), getContext());
3990           Operands.push_back(ARM64Operand::CreateImm(
3991               NewOp4, Op3->getStartLoc(), Op3->getEndLoc(), getContext()));
3992           delete Op3;
3993           delete Op;
3994         }
3995       }
3996
3997       // FIXME: Horrible hack to handle the optional LSL shift for vector
3998       //        instructions.
3999     } else if (NumOperands == 4 && (Tok == "bic" || Tok == "orr")) {
4000       ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
4001       ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
4002       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
4003       if ((Op1->isToken() && Op2->isVectorReg() && Op3->isImm()) ||
4004           (Op1->isVectorReg() && Op2->isToken() && Op3->isImm()))
4005         Operands.push_back(ARM64Operand::CreateShifter(ARM64_AM::LSL, 0, IDLoc,
4006                                                        IDLoc, getContext()));
4007     } else if (NumOperands == 4 && (Tok == "movi" || Tok == "mvni")) {
4008       ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
4009       ARM64Operand *Op2 = static_cast<ARM64Operand *>(Operands[2]);
4010       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
4011       if ((Op1->isToken() && Op2->isVectorReg() && Op3->isImm()) ||
4012           (Op1->isVectorReg() && Op2->isToken() && Op3->isImm())) {
4013         StringRef Suffix = Op1->isToken() ? Op1->getToken() : Op2->getToken();
4014         // Canonicalize on lower-case for ease of comparison.
4015         std::string CanonicalSuffix = Suffix.lower();
4016         if (Tok != "movi" ||
4017             (CanonicalSuffix != ".1d" && CanonicalSuffix != ".2d" &&
4018              CanonicalSuffix != ".8b" && CanonicalSuffix != ".16b"))
4019           Operands.push_back(ARM64Operand::CreateShifter(
4020               ARM64_AM::LSL, 0, IDLoc, IDLoc, getContext()));
4021       }
4022     }
4023   } else if (NumOperands == 5) {
4024     // FIXME: Horrible hack to handle the BFI -> BFM, SBFIZ->SBFM, and
4025     // UBFIZ -> UBFM aliases.
4026     if (Tok == "bfi" || Tok == "sbfiz" || Tok == "ubfiz") {
4027       ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
4028       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
4029       ARM64Operand *Op4 = static_cast<ARM64Operand *>(Operands[4]);
4030
4031       if (Op1->isReg() && Op3->isImm() && Op4->isImm()) {
4032         const MCConstantExpr *Op3CE = dyn_cast<MCConstantExpr>(Op3->getImm());
4033         const MCConstantExpr *Op4CE = dyn_cast<MCConstantExpr>(Op4->getImm());
4034
4035         if (Op3CE && Op4CE) {
4036           uint64_t Op3Val = Op3CE->getValue();
4037           uint64_t Op4Val = Op4CE->getValue();
4038
4039           uint64_t NewOp3Val = 0;
4040           if (ARM64MCRegisterClasses[ARM64::GPR32allRegClassID].contains(
4041                   Op1->getReg()))
4042             NewOp3Val = (32 - Op3Val) & 0x1f;
4043           else
4044             NewOp3Val = (64 - Op3Val) & 0x3f;
4045
4046           uint64_t NewOp4Val = Op4Val - 1;
4047
4048           const MCExpr *NewOp3 =
4049               MCConstantExpr::Create(NewOp3Val, getContext());
4050           const MCExpr *NewOp4 =
4051               MCConstantExpr::Create(NewOp4Val, getContext());
4052           Operands[3] = ARM64Operand::CreateImm(NewOp3, Op3->getStartLoc(),
4053                                                 Op3->getEndLoc(), getContext());
4054           Operands[4] = ARM64Operand::CreateImm(NewOp4, Op4->getStartLoc(),
4055                                                 Op4->getEndLoc(), getContext());
4056           if (Tok == "bfi")
4057             Operands[0] = ARM64Operand::CreateToken(
4058                 "bfm", false, Op->getStartLoc(), getContext());
4059           else if (Tok == "sbfiz")
4060             Operands[0] = ARM64Operand::CreateToken(
4061                 "sbfm", false, Op->getStartLoc(), getContext());
4062           else if (Tok == "ubfiz")
4063             Operands[0] = ARM64Operand::CreateToken(
4064                 "ubfm", false, Op->getStartLoc(), getContext());
4065           else
4066             llvm_unreachable("No valid mnemonic for alias?");
4067
4068           delete Op;
4069           delete Op3;
4070           delete Op4;
4071         }
4072       }
4073
4074       // FIXME: Horrible hack to handle the BFXIL->BFM, SBFX->SBFM, and
4075       // UBFX -> UBFM aliases.
4076     } else if (NumOperands == 5 &&
4077                (Tok == "bfxil" || Tok == "sbfx" || Tok == "ubfx")) {
4078       ARM64Operand *Op1 = static_cast<ARM64Operand *>(Operands[1]);
4079       ARM64Operand *Op3 = static_cast<ARM64Operand *>(Operands[3]);
4080       ARM64Operand *Op4 = static_cast<ARM64Operand *>(Operands[4]);
4081
4082       if (Op1->isReg() && Op3->isImm() && Op4->isImm()) {
4083         const MCConstantExpr *Op3CE = dyn_cast<MCConstantExpr>(Op3->getImm());
4084         const MCConstantExpr *Op4CE = dyn_cast<MCConstantExpr>(Op4->getImm());
4085
4086         if (Op3CE && Op4CE) {
4087           uint64_t Op3Val = Op3CE->getValue();
4088           uint64_t Op4Val = Op4CE->getValue();
4089           uint64_t NewOp4Val = Op3Val + Op4Val - 1;
4090
4091           if (NewOp4Val >= Op3Val) {
4092             const MCExpr *NewOp4 =
4093                 MCConstantExpr::Create(NewOp4Val, getContext());
4094             Operands[4] = ARM64Operand::CreateImm(
4095                 NewOp4, Op4->getStartLoc(), Op4->getEndLoc(), getContext());
4096             if (Tok == "bfxil")
4097               Operands[0] = ARM64Operand::CreateToken(
4098                   "bfm", false, Op->getStartLoc(), getContext());
4099             else if (Tok == "sbfx")
4100               Operands[0] = ARM64Operand::CreateToken(
4101                   "sbfm", false, Op->getStartLoc(), getContext());
4102             else if (Tok == "ubfx")
4103               Operands[0] = ARM64Operand::CreateToken(
4104                   "ubfm", false, Op->getStartLoc(), getContext());
4105             else
4106               llvm_unreachable("No valid mnemonic for alias?");
4107
4108             delete Op;
4109             delete Op4;
4110           }
4111         }
4112       }
4113     }
4114   }
4115   // FIXME: Horrible hack for tbz and tbnz with Wn register operand.
4116   //        InstAlias can't quite handle this since the reg classes aren't
4117   //        subclasses.
4118   if (NumOperands == 4 && (Tok == "tbz" || Tok == "tbnz")) {
4119     ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[2]);
4120     if (Op->isImm()) {
4121       if (const MCConstantExpr *OpCE = dyn_cast<MCConstantExpr>(Op->getImm())) {
4122         if (OpCE->getValue() < 32) {
4123           // The source register can be Wn here, but the matcher expects a
4124           // GPR64. Twiddle it here if necessary.
4125           ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[1]);
4126           if (Op->isReg()) {
4127             unsigned Reg = getXRegFromWReg(Op->getReg());
4128             Operands[1] = ARM64Operand::CreateReg(
4129                 Reg, false, Op->getStartLoc(), Op->getEndLoc(), getContext());
4130             delete Op;
4131           }
4132         }
4133       }
4134     }
4135   }
4136   // FIXME: Horrible hack for sxtw and uxtw with Wn src and Xd dst operands.
4137   //        InstAlias can't quite handle this since the reg classes aren't
4138   //        subclasses.
4139   if (NumOperands == 3 && (Tok == "sxtw" || Tok == "uxtw")) {
4140     // The source register can be Wn here, but the matcher expects a
4141     // GPR64. Twiddle it here if necessary.
4142     ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[2]);
4143     if (Op->isReg()) {
4144       unsigned Reg = getXRegFromWReg(Op->getReg());
4145       Operands[2] = ARM64Operand::CreateReg(Reg, false, Op->getStartLoc(),
4146                                             Op->getEndLoc(), getContext());
4147       delete Op;
4148     }
4149   }
4150   // FIXME: Likewise for [su]xt[bh] with a Xd dst operand
4151   else if (NumOperands == 3 &&
4152            (Tok == "sxtb" || Tok == "uxtb" || Tok == "sxth" || Tok == "uxth")) {
4153     ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[1]);
4154     if (Op->isReg() &&
4155         ARM64MCRegisterClasses[ARM64::GPR64allRegClassID].contains(
4156             Op->getReg())) {
4157       // The source register can be Wn here, but the matcher expects a
4158       // GPR64. Twiddle it here if necessary.
4159       ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[2]);
4160       if (Op->isReg()) {
4161         unsigned Reg = getXRegFromWReg(Op->getReg());
4162         Operands[2] = ARM64Operand::CreateReg(Reg, false, Op->getStartLoc(),
4163                                               Op->getEndLoc(), getContext());
4164         delete Op;
4165       }
4166     }
4167   }
4168
4169   // Yet another horrible hack to handle FMOV Rd, #0.0 using [WX]ZR.
4170   if (NumOperands == 3 && Tok == "fmov") {
4171     ARM64Operand *RegOp = static_cast<ARM64Operand *>(Operands[1]);
4172     ARM64Operand *ImmOp = static_cast<ARM64Operand *>(Operands[2]);
4173     if (RegOp->isReg() && ImmOp->isFPImm() &&
4174         ImmOp->getFPImm() == (unsigned)-1) {
4175       unsigned zreg = ARM64MCRegisterClasses[ARM64::FPR32RegClassID].contains(
4176                           RegOp->getReg())
4177                           ? ARM64::WZR
4178                           : ARM64::XZR;
4179       Operands[2] = ARM64Operand::CreateReg(zreg, false, Op->getStartLoc(),
4180                                             Op->getEndLoc(), getContext());
4181       delete ImmOp;
4182     }
4183   }
4184
4185   // FIXME: Horrible hack to handle the literal .d[1] vector index on
4186   // FMOV instructions. The index isn't an actual instruction operand
4187   // but rather syntactic sugar. It really should be part of the mnemonic,
4188   // not the operand, but whatever.
4189   if ((NumOperands == 5) && Tok == "fmov") {
4190     // If the last operand is a vectorindex of '1', then replace it with
4191     // a '[' '1' ']' token sequence, which is what the matcher
4192     // (annoyingly) expects for a literal vector index operand.
4193     ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[NumOperands - 1]);
4194     if (Op->isVectorIndexD() && Op->getVectorIndex() == 1) {
4195       SMLoc Loc = Op->getStartLoc();
4196       Operands.pop_back();
4197       delete Op;
4198       Operands.push_back(
4199           ARM64Operand::CreateToken("[", false, Loc, getContext()));
4200       Operands.push_back(
4201           ARM64Operand::CreateToken("1", false, Loc, getContext()));
4202       Operands.push_back(
4203           ARM64Operand::CreateToken("]", false, Loc, getContext()));
4204     } else if (Op->isReg()) {
4205       // Similarly, check the destination operand for the GPR->High-lane
4206       // variant.
4207       unsigned OpNo = NumOperands - 2;
4208       ARM64Operand *Op = static_cast<ARM64Operand *>(Operands[OpNo]);
4209       if (Op->isVectorIndexD() && Op->getVectorIndex() == 1) {
4210         SMLoc Loc = Op->getStartLoc();
4211         Operands[OpNo] =
4212             ARM64Operand::CreateToken("[", false, Loc, getContext());
4213         Operands.insert(
4214             Operands.begin() + OpNo + 1,
4215             ARM64Operand::CreateToken("1", false, Loc, getContext()));
4216         Operands.insert(
4217             Operands.begin() + OpNo + 2,
4218             ARM64Operand::CreateToken("]", false, Loc, getContext()));
4219         delete Op;
4220       }
4221     }
4222   }
4223
4224   MCInst Inst;
4225   // First try to match against the secondary set of tables containing the
4226   // short-form NEON instructions (e.g. "fadd.2s v0, v1, v2").
4227   unsigned MatchResult =
4228       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm, 1);
4229
4230   // If that fails, try against the alternate table containing long-form NEON:
4231   // "fadd v0.2s, v1.2s, v2.2s"
4232   if (MatchResult != Match_Success)
4233     MatchResult =
4234         MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm, 0);
4235
4236   switch (MatchResult) {
4237   case Match_Success: {
4238     // Perform range checking and other semantic validations
4239     SmallVector<SMLoc, 8> OperandLocs;
4240     NumOperands = Operands.size();
4241     for (unsigned i = 1; i < NumOperands; ++i)
4242       OperandLocs.push_back(Operands[i]->getStartLoc());
4243     if (validateInstruction(Inst, OperandLocs))
4244       return true;
4245
4246     Inst.setLoc(IDLoc);
4247     Out.EmitInstruction(Inst, STI);
4248     return false;
4249   }
4250   case Match_MissingFeature:
4251   case Match_MnemonicFail:
4252     return showMatchError(IDLoc, MatchResult);
4253   case Match_InvalidOperand: {
4254     SMLoc ErrorLoc = IDLoc;
4255     if (ErrorInfo != ~0U) {
4256       if (ErrorInfo >= Operands.size())
4257         return Error(IDLoc, "too few operands for instruction");
4258
4259       ErrorLoc = ((ARM64Operand *)Operands[ErrorInfo])->getStartLoc();
4260       if (ErrorLoc == SMLoc())
4261         ErrorLoc = IDLoc;
4262     }
4263     // If the match failed on a suffix token operand, tweak the diagnostic
4264     // accordingly.
4265     if (((ARM64Operand *)Operands[ErrorInfo])->isToken() &&
4266         ((ARM64Operand *)Operands[ErrorInfo])->isTokenSuffix())
4267       MatchResult = Match_InvalidSuffix;
4268
4269     return showMatchError(ErrorLoc, MatchResult);
4270   }
4271   case Match_InvalidMemoryIndexedSImm9: {
4272     // If there is not a '!' after the memory operand that failed, we really
4273     // want the diagnostic for the non-pre-indexed instruction variant instead.
4274     // Be careful to check for the post-indexed variant as well, which also
4275     // uses this match diagnostic. Also exclude the explicitly unscaled
4276     // mnemonics, as they want the unscaled diagnostic as well.
4277     if (Operands.size() == ErrorInfo + 1 &&
4278         !((ARM64Operand *)Operands[ErrorInfo])->isImm() &&
4279         !Tok.startswith("stur") && !Tok.startswith("ldur")) {
4280       // whether we want an Indexed64 or Indexed32 diagnostic depends on
4281       // the register class of the previous operand. Default to 64 in case
4282       // we see something unexpected.
4283       MatchResult = Match_InvalidMemoryIndexed64;
4284       if (ErrorInfo) {
4285         ARM64Operand *PrevOp = (ARM64Operand *)Operands[ErrorInfo - 1];
4286         if (PrevOp->isReg() &&
4287             ARM64MCRegisterClasses[ARM64::GPR32RegClassID].contains(
4288                 PrevOp->getReg()))
4289           MatchResult = Match_InvalidMemoryIndexed32;
4290       }
4291     }
4292     SMLoc ErrorLoc = ((ARM64Operand *)Operands[ErrorInfo])->getStartLoc();
4293     if (ErrorLoc == SMLoc())
4294       ErrorLoc = IDLoc;
4295     return showMatchError(ErrorLoc, MatchResult);
4296   }
4297   case Match_InvalidMemoryIndexed32:
4298   case Match_InvalidMemoryIndexed64:
4299   case Match_InvalidMemoryIndexed128:
4300     // If there is a '!' after the memory operand that failed, we really
4301     // want the diagnostic for the pre-indexed instruction variant instead.
4302     if (Operands.size() > ErrorInfo + 1 &&
4303         ((ARM64Operand *)Operands[ErrorInfo + 1])->isTokenEqual("!"))
4304       MatchResult = Match_InvalidMemoryIndexedSImm9;
4305   // FALL THROUGH
4306   case Match_InvalidMemoryIndexed8:
4307   case Match_InvalidMemoryIndexed16:
4308   case Match_InvalidMemoryIndexed32SImm7:
4309   case Match_InvalidMemoryIndexed64SImm7:
4310   case Match_InvalidMemoryIndexed128SImm7:
4311   case Match_InvalidImm1_8:
4312   case Match_InvalidImm1_16:
4313   case Match_InvalidImm1_32:
4314   case Match_InvalidImm1_64:
4315   case Match_InvalidLabel: {
4316     // Any time we get here, there's nothing fancy to do. Just get the
4317     // operand SMLoc and display the diagnostic.
4318     SMLoc ErrorLoc = ((ARM64Operand *)Operands[ErrorInfo])->getStartLoc();
4319     // If it's a memory operand, the error is with the offset immediate,
4320     // so get that location instead.
4321     if (((ARM64Operand *)Operands[ErrorInfo])->isMem())
4322       ErrorLoc = ((ARM64Operand *)Operands[ErrorInfo])->getOffsetLoc();
4323     if (ErrorLoc == SMLoc())
4324       ErrorLoc = IDLoc;
4325     return showMatchError(ErrorLoc, MatchResult);
4326   }
4327   }
4328
4329   llvm_unreachable("Implement any new match types added!");
4330   return true;
4331 }
4332
4333 /// ParseDirective parses the arm specific directives
4334 bool ARM64AsmParser::ParseDirective(AsmToken DirectiveID) {
4335   StringRef IDVal = DirectiveID.getIdentifier();
4336   SMLoc Loc = DirectiveID.getLoc();
4337   if (IDVal == ".hword")
4338     return parseDirectiveWord(2, Loc);
4339   if (IDVal == ".word")
4340     return parseDirectiveWord(4, Loc);
4341   if (IDVal == ".xword")
4342     return parseDirectiveWord(8, Loc);
4343   if (IDVal == ".tlsdesccall")
4344     return parseDirectiveTLSDescCall(Loc);
4345
4346   return parseDirectiveLOH(IDVal, Loc);
4347 }
4348
4349 /// parseDirectiveWord
4350 ///  ::= .word [ expression (, expression)* ]
4351 bool ARM64AsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
4352   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4353     for (;;) {
4354       const MCExpr *Value;
4355       if (getParser().parseExpression(Value))
4356         return true;
4357
4358       getParser().getStreamer().EmitValue(Value, Size);
4359
4360       if (getLexer().is(AsmToken::EndOfStatement))
4361         break;
4362
4363       // FIXME: Improve diagnostic.
4364       if (getLexer().isNot(AsmToken::Comma))
4365         return Error(L, "unexpected token in directive");
4366       Parser.Lex();
4367     }
4368   }
4369
4370   Parser.Lex();
4371   return false;
4372 }
4373
4374 // parseDirectiveTLSDescCall:
4375 //   ::= .tlsdesccall symbol
4376 bool ARM64AsmParser::parseDirectiveTLSDescCall(SMLoc L) {
4377   StringRef Name;
4378   if (getParser().parseIdentifier(Name))
4379     return Error(L, "expected symbol after directive");
4380
4381   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
4382   const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, getContext());
4383   Expr = ARM64MCExpr::Create(Expr, ARM64MCExpr::VK_TLSDESC, getContext());
4384
4385   MCInst Inst;
4386   Inst.setOpcode(ARM64::TLSDESCCALL);
4387   Inst.addOperand(MCOperand::CreateExpr(Expr));
4388
4389   getParser().getStreamer().EmitInstruction(Inst, STI);
4390   return false;
4391 }
4392
4393 /// ::= .loh <lohName | lohId> label1, ..., labelN
4394 /// The number of arguments depends on the loh identifier.
4395 bool ARM64AsmParser::parseDirectiveLOH(StringRef IDVal, SMLoc Loc) {
4396   if (IDVal != MCLOHDirectiveName())
4397     return true;
4398   MCLOHType Kind;
4399   if (getParser().getTok().isNot(AsmToken::Identifier)) {
4400     if (getParser().getTok().isNot(AsmToken::Integer))
4401       return TokError("expected an identifier or a number in directive");
4402     // We successfully get a numeric value for the identifier.
4403     // Check if it is valid.
4404     int64_t Id = getParser().getTok().getIntVal();
4405     Kind = (MCLOHType)Id;
4406     // Check that Id does not overflow MCLOHType.
4407     if (!isValidMCLOHType(Kind) || Id != Kind)
4408       return TokError("invalid numeric identifier in directive");
4409   } else {
4410     StringRef Name = getTok().getIdentifier();
4411     // We successfully parse an identifier.
4412     // Check if it is a recognized one.
4413     int Id = MCLOHNameToId(Name);
4414
4415     if (Id == -1)
4416       return TokError("invalid identifier in directive");
4417     Kind = (MCLOHType)Id;
4418   }
4419   // Consume the identifier.
4420   Lex();
4421   // Get the number of arguments of this LOH.
4422   int NbArgs = MCLOHIdToNbArgs(Kind);
4423
4424   assert(NbArgs != -1 && "Invalid number of arguments");
4425
4426   SmallVector<MCSymbol *, 3> Args;
4427   for (int Idx = 0; Idx < NbArgs; ++Idx) {
4428     StringRef Name;
4429     if (getParser().parseIdentifier(Name))
4430       return TokError("expected identifier in directive");
4431     Args.push_back(getContext().GetOrCreateSymbol(Name));
4432
4433     if (Idx + 1 == NbArgs)
4434       break;
4435     if (getLexer().isNot(AsmToken::Comma))
4436       return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4437     Lex();
4438   }
4439   if (getLexer().isNot(AsmToken::EndOfStatement))
4440     return TokError("unexpected token in '" + Twine(IDVal) + "' directive");
4441
4442   getStreamer().EmitLOHDirective((MCLOHType)Kind, Args);
4443   return false;
4444 }
4445
4446 bool
4447 ARM64AsmParser::classifySymbolRef(const MCExpr *Expr,
4448                                   ARM64MCExpr::VariantKind &ELFRefKind,
4449                                   MCSymbolRefExpr::VariantKind &DarwinRefKind,
4450                                   const MCConstantExpr *&Addend) {
4451   ELFRefKind = ARM64MCExpr::VK_INVALID;
4452   DarwinRefKind = MCSymbolRefExpr::VK_None;
4453
4454   if (const ARM64MCExpr *AE = dyn_cast<ARM64MCExpr>(Expr)) {
4455     ELFRefKind = AE->getKind();
4456     Expr = AE->getSubExpr();
4457   }
4458
4459   const MCSymbolRefExpr *SE = dyn_cast<MCSymbolRefExpr>(Expr);
4460   if (SE) {
4461     // It's a simple symbol reference with no addend.
4462     DarwinRefKind = SE->getKind();
4463     Addend = 0;
4464     return true;
4465   }
4466
4467   const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr);
4468   if (!BE)
4469     return false;
4470
4471   SE = dyn_cast<MCSymbolRefExpr>(BE->getLHS());
4472   if (!SE)
4473     return false;
4474   DarwinRefKind = SE->getKind();
4475
4476   if (BE->getOpcode() != MCBinaryExpr::Add)
4477     return false;
4478
4479   // See if the addend is is a constant, otherwise there's more going
4480   // on here than we can deal with.
4481   Addend = dyn_cast<MCConstantExpr>(BE->getRHS());
4482   if (!Addend)
4483     return false;
4484
4485   // It's some symbol reference + a constant addend, but really
4486   // shouldn't use both Darwin and ELF syntax.
4487   return ELFRefKind == ARM64MCExpr::VK_INVALID ||
4488          DarwinRefKind == MCSymbolRefExpr::VK_None;
4489 }
4490
4491 /// Force static initialization.
4492 extern "C" void LLVMInitializeARM64AsmParser() {
4493   RegisterMCAsmParser<ARM64AsmParser> X(TheARM64Target);
4494 }
4495
4496 #define GET_REGISTER_MATCHER
4497 #define GET_MATCHER_IMPLEMENTATION
4498 #include "ARM64GenAsmMatcher.inc"
4499
4500 // Define this matcher function after the auto-generated include so we
4501 // have the match class enum definitions.
4502 unsigned ARM64AsmParser::validateTargetOperandClass(MCParsedAsmOperand *AsmOp,
4503                                                     unsigned Kind) {
4504   ARM64Operand *Op = static_cast<ARM64Operand *>(AsmOp);
4505   // If the kind is a token for a literal immediate, check if our asm
4506   // operand matches. This is for InstAliases which have a fixed-value
4507   // immediate in the syntax.
4508   int64_t ExpectedVal;
4509   switch (Kind) {
4510   default:
4511     return Match_InvalidOperand;
4512   case MCK__35_0:
4513     ExpectedVal = 0;
4514     break;
4515   case MCK__35_1:
4516     ExpectedVal = 1;
4517     break;
4518   case MCK__35_12:
4519     ExpectedVal = 12;
4520     break;
4521   case MCK__35_16:
4522     ExpectedVal = 16;
4523     break;
4524   case MCK__35_2:
4525     ExpectedVal = 2;
4526     break;
4527   case MCK__35_24:
4528     ExpectedVal = 24;
4529     break;
4530   case MCK__35_3:
4531     ExpectedVal = 3;
4532     break;
4533   case MCK__35_32:
4534     ExpectedVal = 32;
4535     break;
4536   case MCK__35_4:
4537     ExpectedVal = 4;
4538     break;
4539   case MCK__35_48:
4540     ExpectedVal = 48;
4541     break;
4542   case MCK__35_6:
4543     ExpectedVal = 6;
4544     break;
4545   case MCK__35_64:
4546     ExpectedVal = 64;
4547     break;
4548   case MCK__35_8:
4549     ExpectedVal = 8;
4550     break;
4551   }
4552   if (!Op->isImm())
4553     return Match_InvalidOperand;
4554   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
4555   if (!CE)
4556     return Match_InvalidOperand;
4557   if (CE->getValue() == ExpectedVal)
4558     return Match_Success;
4559   return Match_InvalidOperand;
4560 }