OSDN Git Service

Revert CMake: Make most target symbols hidden by default
[android-x86/external-llvm.git] / lib / Target / ARM / AsmParser / ARMAsmParser.cpp
1 //===- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "ARMFeatures.h"
10 #include "Utils/ARMBaseInfo.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMBaseInfo.h"
13 #include "MCTargetDesc/ARMInstPrinter.h"
14 #include "MCTargetDesc/ARMMCExpr.h"
15 #include "MCTargetDesc/ARMMCTargetDesc.h"
16 #include "TargetInfo/ARMTargetInfo.h"
17 #include "llvm/ADT/APFloat.h"
18 #include "llvm/ADT/APInt.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCInstrDesc.h"
32 #include "llvm/MC/MCInstrInfo.h"
33 #include "llvm/MC/MCObjectFileInfo.h"
34 #include "llvm/MC/MCParser/MCAsmLexer.h"
35 #include "llvm/MC/MCParser/MCAsmParser.h"
36 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
37 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
38 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
39 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/MC/MCSection.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSubtargetInfo.h"
44 #include "llvm/MC/MCSymbol.h"
45 #include "llvm/MC/SubtargetFeature.h"
46 #include "llvm/Support/ARMBuildAttributes.h"
47 #include "llvm/Support/ARMEHABI.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/SMLoc.h"
54 #include "llvm/Support/TargetParser.h"
55 #include "llvm/Support/TargetRegistry.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <algorithm>
58 #include <cassert>
59 #include <cstddef>
60 #include <cstdint>
61 #include <iterator>
62 #include <limits>
63 #include <memory>
64 #include <string>
65 #include <utility>
66 #include <vector>
67
68 #define DEBUG_TYPE "asm-parser"
69
70 using namespace llvm;
71
72 namespace {
73
74 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
75
76 static cl::opt<ImplicitItModeTy> ImplicitItMode(
77     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
78     cl::desc("Allow conditional instructions outdside of an IT block"),
79     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
80                           "Accept in both ISAs, emit implicit ITs in Thumb"),
81                clEnumValN(ImplicitItModeTy::Never, "never",
82                           "Warn in ARM, reject in Thumb"),
83                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
84                           "Accept in ARM, reject in Thumb"),
85                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
86                           "Warn in ARM, emit implicit ITs in Thumb")));
87
88 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
89                                         cl::init(false));
90
91 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
92
93 class UnwindContext {
94   using Locs = SmallVector<SMLoc, 4>;
95
96   MCAsmParser &Parser;
97   Locs FnStartLocs;
98   Locs CantUnwindLocs;
99   Locs PersonalityLocs;
100   Locs PersonalityIndexLocs;
101   Locs HandlerDataLocs;
102   int FPReg;
103
104 public:
105   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
106
107   bool hasFnStart() const { return !FnStartLocs.empty(); }
108   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
109   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
110
111   bool hasPersonality() const {
112     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
113   }
114
115   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
116   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
117   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
118   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
119   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
120
121   void saveFPReg(int Reg) { FPReg = Reg; }
122   int getFPReg() const { return FPReg; }
123
124   void emitFnStartLocNotes() const {
125     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
126          FI != FE; ++FI)
127       Parser.Note(*FI, ".fnstart was specified here");
128   }
129
130   void emitCantUnwindLocNotes() const {
131     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
132                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
133       Parser.Note(*UI, ".cantunwind was specified here");
134   }
135
136   void emitHandlerDataLocNotes() const {
137     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
138                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
139       Parser.Note(*HI, ".handlerdata was specified here");
140   }
141
142   void emitPersonalityLocNotes() const {
143     for (Locs::const_iterator PI = PersonalityLocs.begin(),
144                               PE = PersonalityLocs.end(),
145                               PII = PersonalityIndexLocs.begin(),
146                               PIE = PersonalityIndexLocs.end();
147          PI != PE || PII != PIE;) {
148       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
149         Parser.Note(*PI++, ".personality was specified here");
150       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
151         Parser.Note(*PII++, ".personalityindex was specified here");
152       else
153         llvm_unreachable(".personality and .personalityindex cannot be "
154                          "at the same location");
155     }
156   }
157
158   void reset() {
159     FnStartLocs = Locs();
160     CantUnwindLocs = Locs();
161     PersonalityLocs = Locs();
162     HandlerDataLocs = Locs();
163     PersonalityIndexLocs = Locs();
164     FPReg = ARM::SP;
165   }
166 };
167
168
169 class ARMAsmParser : public MCTargetAsmParser {
170   const MCRegisterInfo *MRI;
171   UnwindContext UC;
172
173   ARMTargetStreamer &getTargetStreamer() {
174     assert(getParser().getStreamer().getTargetStreamer() &&
175            "do not have a target streamer");
176     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
177     return static_cast<ARMTargetStreamer &>(TS);
178   }
179
180   // Map of register aliases registers via the .req directive.
181   StringMap<unsigned> RegisterReqs;
182
183   bool NextSymbolIsThumb;
184
185   bool useImplicitITThumb() const {
186     return ImplicitItMode == ImplicitItModeTy::Always ||
187            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
188   }
189
190   bool useImplicitITARM() const {
191     return ImplicitItMode == ImplicitItModeTy::Always ||
192            ImplicitItMode == ImplicitItModeTy::ARMOnly;
193   }
194
195   struct {
196     ARMCC::CondCodes Cond;    // Condition for IT block.
197     unsigned Mask:4;          // Condition mask for instructions.
198                               // Starting at first 1 (from lsb).
199                               //   '1'  condition as indicated in IT.
200                               //   '0'  inverse of condition (else).
201                               // Count of instructions in IT block is
202                               // 4 - trailingzeroes(mask)
203                               // Note that this does not have the same encoding
204                               // as in the IT instruction, which also depends
205                               // on the low bit of the condition code.
206
207     unsigned CurPosition;     // Current position in parsing of IT
208                               // block. In range [0,4], with 0 being the IT
209                               // instruction itself. Initialized according to
210                               // count of instructions in block.  ~0U if no
211                               // active IT block.
212
213     bool IsExplicit;          // true  - The IT instruction was present in the
214                               //         input, we should not modify it.
215                               // false - The IT instruction was added
216                               //         implicitly, we can extend it if that
217                               //         would be legal.
218   } ITState;
219
220   SmallVector<MCInst, 4> PendingConditionalInsts;
221
222   void flushPendingInstructions(MCStreamer &Out) override {
223     if (!inImplicitITBlock()) {
224       assert(PendingConditionalInsts.size() == 0);
225       return;
226     }
227
228     // Emit the IT instruction
229     unsigned Mask = getITMaskEncoding();
230     MCInst ITInst;
231     ITInst.setOpcode(ARM::t2IT);
232     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
233     ITInst.addOperand(MCOperand::createImm(Mask));
234     Out.EmitInstruction(ITInst, getSTI());
235
236     // Emit the conditonal instructions
237     assert(PendingConditionalInsts.size() <= 4);
238     for (const MCInst &Inst : PendingConditionalInsts) {
239       Out.EmitInstruction(Inst, getSTI());
240     }
241     PendingConditionalInsts.clear();
242
243     // Clear the IT state
244     ITState.Mask = 0;
245     ITState.CurPosition = ~0U;
246   }
247
248   bool inITBlock() { return ITState.CurPosition != ~0U; }
249   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
250   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
251
252   bool lastInITBlock() {
253     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
254   }
255
256   void forwardITPosition() {
257     if (!inITBlock()) return;
258     // Move to the next instruction in the IT block, if there is one. If not,
259     // mark the block as done, except for implicit IT blocks, which we leave
260     // open until we find an instruction that can't be added to it.
261     unsigned TZ = countTrailingZeros(ITState.Mask);
262     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
263       ITState.CurPosition = ~0U; // Done with the IT block after this.
264   }
265
266   // Rewind the state of the current IT block, removing the last slot from it.
267   void rewindImplicitITPosition() {
268     assert(inImplicitITBlock());
269     assert(ITState.CurPosition > 1);
270     ITState.CurPosition--;
271     unsigned TZ = countTrailingZeros(ITState.Mask);
272     unsigned NewMask = 0;
273     NewMask |= ITState.Mask & (0xC << TZ);
274     NewMask |= 0x2 << TZ;
275     ITState.Mask = NewMask;
276   }
277
278   // Rewind the state of the current IT block, removing the last slot from it.
279   // If we were at the first slot, this closes the IT block.
280   void discardImplicitITBlock() {
281     assert(inImplicitITBlock());
282     assert(ITState.CurPosition == 1);
283     ITState.CurPosition = ~0U;
284   }
285
286   // Return the low-subreg of a given Q register.
287   unsigned getDRegFromQReg(unsigned QReg) const {
288     return MRI->getSubReg(QReg, ARM::dsub_0);
289   }
290
291   // Get the encoding of the IT mask, as it will appear in an IT instruction.
292   unsigned getITMaskEncoding() {
293     assert(inITBlock());
294     unsigned Mask = ITState.Mask;
295     unsigned TZ = countTrailingZeros(Mask);
296     if ((ITState.Cond & 1) == 0) {
297       assert(Mask && TZ <= 3 && "illegal IT mask value!");
298       Mask ^= (0xE << TZ) & 0xF;
299     }
300     return Mask;
301   }
302
303   // Get the condition code corresponding to the current IT block slot.
304   ARMCC::CondCodes currentITCond() {
305     unsigned MaskBit;
306     if (ITState.CurPosition == 1)
307       MaskBit = 1;
308     else
309       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
310
311     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
312   }
313
314   // Invert the condition of the current IT block slot without changing any
315   // other slots in the same block.
316   void invertCurrentITCondition() {
317     if (ITState.CurPosition == 1) {
318       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
319     } else {
320       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
321     }
322   }
323
324   // Returns true if the current IT block is full (all 4 slots used).
325   bool isITBlockFull() {
326     return inITBlock() && (ITState.Mask & 1);
327   }
328
329   // Extend the current implicit IT block to have one more slot with the given
330   // condition code.
331   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
332     assert(inImplicitITBlock());
333     assert(!isITBlockFull());
334     assert(Cond == ITState.Cond ||
335            Cond == ARMCC::getOppositeCondition(ITState.Cond));
336     unsigned TZ = countTrailingZeros(ITState.Mask);
337     unsigned NewMask = 0;
338     // Keep any existing condition bits.
339     NewMask |= ITState.Mask & (0xE << TZ);
340     // Insert the new condition bit.
341     NewMask |= (Cond == ITState.Cond) << TZ;
342     // Move the trailing 1 down one bit.
343     NewMask |= 1 << (TZ - 1);
344     ITState.Mask = NewMask;
345   }
346
347   // Create a new implicit IT block with a dummy condition code.
348   void startImplicitITBlock() {
349     assert(!inITBlock());
350     ITState.Cond = ARMCC::AL;
351     ITState.Mask = 8;
352     ITState.CurPosition = 1;
353     ITState.IsExplicit = false;
354   }
355
356   // Create a new explicit IT block with the given condition and mask. The mask
357   // should be in the parsed format, with a 1 implying 't', regardless of the
358   // low bit of the condition.
359   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
360     assert(!inITBlock());
361     ITState.Cond = Cond;
362     ITState.Mask = Mask;
363     ITState.CurPosition = 0;
364     ITState.IsExplicit = true;
365   }
366
367   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
368     return getParser().Note(L, Msg, Range);
369   }
370
371   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
372     return getParser().Warning(L, Msg, Range);
373   }
374
375   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
376     return getParser().Error(L, Msg, Range);
377   }
378
379   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
380                            unsigned ListNo, bool IsARPop = false);
381   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
382                            unsigned ListNo);
383
384   int tryParseRegister();
385   bool tryParseRegisterWithWriteBack(OperandVector &);
386   int tryParseShiftRegister(OperandVector &);
387   bool parseRegisterList(OperandVector &);
388   bool parseMemory(OperandVector &);
389   bool parseOperand(OperandVector &, StringRef Mnemonic);
390   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
391   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
392                               unsigned &ShiftAmount);
393   bool parseLiteralValues(unsigned Size, SMLoc L);
394   bool parseDirectiveThumb(SMLoc L);
395   bool parseDirectiveARM(SMLoc L);
396   bool parseDirectiveThumbFunc(SMLoc L);
397   bool parseDirectiveCode(SMLoc L);
398   bool parseDirectiveSyntax(SMLoc L);
399   bool parseDirectiveReq(StringRef Name, SMLoc L);
400   bool parseDirectiveUnreq(SMLoc L);
401   bool parseDirectiveArch(SMLoc L);
402   bool parseDirectiveEabiAttr(SMLoc L);
403   bool parseDirectiveCPU(SMLoc L);
404   bool parseDirectiveFPU(SMLoc L);
405   bool parseDirectiveFnStart(SMLoc L);
406   bool parseDirectiveFnEnd(SMLoc L);
407   bool parseDirectiveCantUnwind(SMLoc L);
408   bool parseDirectivePersonality(SMLoc L);
409   bool parseDirectiveHandlerData(SMLoc L);
410   bool parseDirectiveSetFP(SMLoc L);
411   bool parseDirectivePad(SMLoc L);
412   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
413   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
414   bool parseDirectiveLtorg(SMLoc L);
415   bool parseDirectiveEven(SMLoc L);
416   bool parseDirectivePersonalityIndex(SMLoc L);
417   bool parseDirectiveUnwindRaw(SMLoc L);
418   bool parseDirectiveTLSDescSeq(SMLoc L);
419   bool parseDirectiveMovSP(SMLoc L);
420   bool parseDirectiveObjectArch(SMLoc L);
421   bool parseDirectiveArchExtension(SMLoc L);
422   bool parseDirectiveAlign(SMLoc L);
423   bool parseDirectiveThumbSet(SMLoc L);
424
425   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
426                           bool &CarrySetting, unsigned &ProcessorIMod,
427                           StringRef &ITMask);
428   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
429                              bool &CanAcceptCarrySet,
430                              bool &CanAcceptPredicationCode);
431
432   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
433                                      OperandVector &Operands);
434   bool isThumb() const {
435     // FIXME: Can tablegen auto-generate this?
436     return getSTI().getFeatureBits()[ARM::ModeThumb];
437   }
438
439   bool isThumbOne() const {
440     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
441   }
442
443   bool isThumbTwo() const {
444     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
445   }
446
447   bool hasThumb() const {
448     return getSTI().getFeatureBits()[ARM::HasV4TOps];
449   }
450
451   bool hasThumb2() const {
452     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
453   }
454
455   bool hasV6Ops() const {
456     return getSTI().getFeatureBits()[ARM::HasV6Ops];
457   }
458
459   bool hasV6T2Ops() const {
460     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
461   }
462
463   bool hasV6MOps() const {
464     return getSTI().getFeatureBits()[ARM::HasV6MOps];
465   }
466
467   bool hasV7Ops() const {
468     return getSTI().getFeatureBits()[ARM::HasV7Ops];
469   }
470
471   bool hasV8Ops() const {
472     return getSTI().getFeatureBits()[ARM::HasV8Ops];
473   }
474
475   bool hasV8MBaseline() const {
476     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
477   }
478
479   bool hasV8MMainline() const {
480     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
481   }
482
483   bool has8MSecExt() const {
484     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
485   }
486
487   bool hasARM() const {
488     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
489   }
490
491   bool hasDSP() const {
492     return getSTI().getFeatureBits()[ARM::FeatureDSP];
493   }
494
495   bool hasD32() const {
496     return getSTI().getFeatureBits()[ARM::FeatureD32];
497   }
498
499   bool hasV8_1aOps() const {
500     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
501   }
502
503   bool hasRAS() const {
504     return getSTI().getFeatureBits()[ARM::FeatureRAS];
505   }
506
507   void SwitchMode() {
508     MCSubtargetInfo &STI = copySTI();
509     auto FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
510     setAvailableFeatures(FB);
511   }
512
513   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
514
515   bool isMClass() const {
516     return getSTI().getFeatureBits()[ARM::FeatureMClass];
517   }
518
519   /// @name Auto-generated Match Functions
520   /// {
521
522 #define GET_ASSEMBLER_HEADER
523 #include "ARMGenAsmMatcher.inc"
524
525   /// }
526
527   OperandMatchResultTy parseITCondCode(OperandVector &);
528   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
529   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
530   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
531   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
532   OperandMatchResultTy parseTraceSyncBarrierOptOperand(OperandVector &);
533   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
534   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
535   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
536   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
537   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
538                                    int High);
539   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
540     return parsePKHImm(O, "lsl", 0, 31);
541   }
542   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
543     return parsePKHImm(O, "asr", 1, 32);
544   }
545   OperandMatchResultTy parseSetEndImm(OperandVector &);
546   OperandMatchResultTy parseShifterImm(OperandVector &);
547   OperandMatchResultTy parseRotImm(OperandVector &);
548   OperandMatchResultTy parseModImm(OperandVector &);
549   OperandMatchResultTy parseBitfield(OperandVector &);
550   OperandMatchResultTy parsePostIdxReg(OperandVector &);
551   OperandMatchResultTy parseAM3Offset(OperandVector &);
552   OperandMatchResultTy parseFPImm(OperandVector &);
553   OperandMatchResultTy parseVectorList(OperandVector &);
554   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
555                                        SMLoc &EndLoc);
556
557   // Asm Match Converter Methods
558   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
559   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
560
561   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
562   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
563   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
564   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
565   bool isITBlockTerminator(MCInst &Inst) const;
566   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
567   bool validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
568                         bool Load, bool ARMMode, bool Writeback);
569
570 public:
571   enum ARMMatchResultTy {
572     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
573     Match_RequiresNotITBlock,
574     Match_RequiresV6,
575     Match_RequiresThumb2,
576     Match_RequiresV8,
577     Match_RequiresFlagSetting,
578 #define GET_OPERAND_DIAGNOSTIC_TYPES
579 #include "ARMGenAsmMatcher.inc"
580
581   };
582
583   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
584                const MCInstrInfo &MII, const MCTargetOptions &Options)
585     : MCTargetAsmParser(Options, STI, MII), UC(Parser) {
586     MCAsmParserExtension::Initialize(Parser);
587
588     // Cache the MCRegisterInfo.
589     MRI = getContext().getRegisterInfo();
590
591     // Initialize the set of available features.
592     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
593
594     // Add build attributes based on the selected target.
595     if (AddBuildAttributes)
596       getTargetStreamer().emitTargetAttributes(STI);
597
598     // Not in an ITBlock to start with.
599     ITState.CurPosition = ~0U;
600
601     NextSymbolIsThumb = false;
602   }
603
604   // Implementation of the MCTargetAsmParser interface:
605   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
606   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
607                         SMLoc NameLoc, OperandVector &Operands) override;
608   bool ParseDirective(AsmToken DirectiveID) override;
609
610   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
611                                       unsigned Kind) override;
612   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
613
614   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
615                                OperandVector &Operands, MCStreamer &Out,
616                                uint64_t &ErrorInfo,
617                                bool MatchingInlineAsm) override;
618   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
619                             SmallVectorImpl<NearMissInfo> &NearMisses,
620                             bool MatchingInlineAsm, bool &EmitInITBlock,
621                             MCStreamer &Out);
622
623   struct NearMissMessage {
624     SMLoc Loc;
625     SmallString<128> Message;
626   };
627
628   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
629
630   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
631                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
632                         SMLoc IDLoc, OperandVector &Operands);
633   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
634                         OperandVector &Operands);
635
636   void doBeforeLabelEmit(MCSymbol *Symbol) override;
637
638   void onLabelParsed(MCSymbol *Symbol) override;
639 };
640
641 /// ARMOperand - Instances of this class represent a parsed ARM machine
642 /// operand.
643 class ARMOperand : public MCParsedAsmOperand {
644   enum KindTy {
645     k_CondCode,
646     k_CCOut,
647     k_ITCondMask,
648     k_CoprocNum,
649     k_CoprocReg,
650     k_CoprocOption,
651     k_Immediate,
652     k_MemBarrierOpt,
653     k_InstSyncBarrierOpt,
654     k_TraceSyncBarrierOpt,
655     k_Memory,
656     k_PostIndexRegister,
657     k_MSRMask,
658     k_BankedReg,
659     k_ProcIFlags,
660     k_VectorIndex,
661     k_Register,
662     k_RegisterList,
663     k_DPRRegisterList,
664     k_SPRRegisterList,
665     k_VectorList,
666     k_VectorListAllLanes,
667     k_VectorListIndexed,
668     k_ShiftedRegister,
669     k_ShiftedImmediate,
670     k_ShifterImmediate,
671     k_RotateImmediate,
672     k_ModifiedImmediate,
673     k_ConstantPoolImmediate,
674     k_BitfieldDescriptor,
675     k_Token,
676   } Kind;
677
678   SMLoc StartLoc, EndLoc, AlignmentLoc;
679   SmallVector<unsigned, 8> Registers;
680
681   struct CCOp {
682     ARMCC::CondCodes Val;
683   };
684
685   struct CopOp {
686     unsigned Val;
687   };
688
689   struct CoprocOptionOp {
690     unsigned Val;
691   };
692
693   struct ITMaskOp {
694     unsigned Mask:4;
695   };
696
697   struct MBOptOp {
698     ARM_MB::MemBOpt Val;
699   };
700
701   struct ISBOptOp {
702     ARM_ISB::InstSyncBOpt Val;
703   };
704
705   struct TSBOptOp {
706     ARM_TSB::TraceSyncBOpt Val;
707   };
708
709   struct IFlagsOp {
710     ARM_PROC::IFlags Val;
711   };
712
713   struct MMaskOp {
714     unsigned Val;
715   };
716
717   struct BankedRegOp {
718     unsigned Val;
719   };
720
721   struct TokOp {
722     const char *Data;
723     unsigned Length;
724   };
725
726   struct RegOp {
727     unsigned RegNum;
728   };
729
730   // A vector register list is a sequential list of 1 to 4 registers.
731   struct VectorListOp {
732     unsigned RegNum;
733     unsigned Count;
734     unsigned LaneIndex;
735     bool isDoubleSpaced;
736   };
737
738   struct VectorIndexOp {
739     unsigned Val;
740   };
741
742   struct ImmOp {
743     const MCExpr *Val;
744   };
745
746   /// Combined record for all forms of ARM address expressions.
747   struct MemoryOp {
748     unsigned BaseRegNum;
749     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
750     // was specified.
751     const MCConstantExpr *OffsetImm;  // Offset immediate value
752     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
753     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
754     unsigned ShiftImm;        // shift for OffsetReg.
755     unsigned Alignment;       // 0 = no alignment specified
756     // n = alignment in bytes (2, 4, 8, 16, or 32)
757     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
758   };
759
760   struct PostIdxRegOp {
761     unsigned RegNum;
762     bool isAdd;
763     ARM_AM::ShiftOpc ShiftTy;
764     unsigned ShiftImm;
765   };
766
767   struct ShifterImmOp {
768     bool isASR;
769     unsigned Imm;
770   };
771
772   struct RegShiftedRegOp {
773     ARM_AM::ShiftOpc ShiftTy;
774     unsigned SrcReg;
775     unsigned ShiftReg;
776     unsigned ShiftImm;
777   };
778
779   struct RegShiftedImmOp {
780     ARM_AM::ShiftOpc ShiftTy;
781     unsigned SrcReg;
782     unsigned ShiftImm;
783   };
784
785   struct RotImmOp {
786     unsigned Imm;
787   };
788
789   struct ModImmOp {
790     unsigned Bits;
791     unsigned Rot;
792   };
793
794   struct BitfieldOp {
795     unsigned LSB;
796     unsigned Width;
797   };
798
799   union {
800     struct CCOp CC;
801     struct CopOp Cop;
802     struct CoprocOptionOp CoprocOption;
803     struct MBOptOp MBOpt;
804     struct ISBOptOp ISBOpt;
805     struct TSBOptOp TSBOpt;
806     struct ITMaskOp ITMask;
807     struct IFlagsOp IFlags;
808     struct MMaskOp MMask;
809     struct BankedRegOp BankedReg;
810     struct TokOp Tok;
811     struct RegOp Reg;
812     struct VectorListOp VectorList;
813     struct VectorIndexOp VectorIndex;
814     struct ImmOp Imm;
815     struct MemoryOp Memory;
816     struct PostIdxRegOp PostIdxReg;
817     struct ShifterImmOp ShifterImm;
818     struct RegShiftedRegOp RegShiftedReg;
819     struct RegShiftedImmOp RegShiftedImm;
820     struct RotImmOp RotImm;
821     struct ModImmOp ModImm;
822     struct BitfieldOp Bitfield;
823   };
824
825 public:
826   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
827
828   /// getStartLoc - Get the location of the first token of this operand.
829   SMLoc getStartLoc() const override { return StartLoc; }
830
831   /// getEndLoc - Get the location of the last token of this operand.
832   SMLoc getEndLoc() const override { return EndLoc; }
833
834   /// getLocRange - Get the range between the first and last token of this
835   /// operand.
836   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
837
838   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
839   SMLoc getAlignmentLoc() const {
840     assert(Kind == k_Memory && "Invalid access!");
841     return AlignmentLoc;
842   }
843
844   ARMCC::CondCodes getCondCode() const {
845     assert(Kind == k_CondCode && "Invalid access!");
846     return CC.Val;
847   }
848
849   unsigned getCoproc() const {
850     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
851     return Cop.Val;
852   }
853
854   StringRef getToken() const {
855     assert(Kind == k_Token && "Invalid access!");
856     return StringRef(Tok.Data, Tok.Length);
857   }
858
859   unsigned getReg() const override {
860     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
861     return Reg.RegNum;
862   }
863
864   const SmallVectorImpl<unsigned> &getRegList() const {
865     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
866             Kind == k_SPRRegisterList) && "Invalid access!");
867     return Registers;
868   }
869
870   const MCExpr *getImm() const {
871     assert(isImm() && "Invalid access!");
872     return Imm.Val;
873   }
874
875   const MCExpr *getConstantPoolImm() const {
876     assert(isConstantPoolImm() && "Invalid access!");
877     return Imm.Val;
878   }
879
880   unsigned getVectorIndex() const {
881     assert(Kind == k_VectorIndex && "Invalid access!");
882     return VectorIndex.Val;
883   }
884
885   ARM_MB::MemBOpt getMemBarrierOpt() const {
886     assert(Kind == k_MemBarrierOpt && "Invalid access!");
887     return MBOpt.Val;
888   }
889
890   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
891     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
892     return ISBOpt.Val;
893   }
894
895   ARM_TSB::TraceSyncBOpt getTraceSyncBarrierOpt() const {
896     assert(Kind == k_TraceSyncBarrierOpt && "Invalid access!");
897     return TSBOpt.Val;
898   }
899
900   ARM_PROC::IFlags getProcIFlags() const {
901     assert(Kind == k_ProcIFlags && "Invalid access!");
902     return IFlags.Val;
903   }
904
905   unsigned getMSRMask() const {
906     assert(Kind == k_MSRMask && "Invalid access!");
907     return MMask.Val;
908   }
909
910   unsigned getBankedReg() const {
911     assert(Kind == k_BankedReg && "Invalid access!");
912     return BankedReg.Val;
913   }
914
915   bool isCoprocNum() const { return Kind == k_CoprocNum; }
916   bool isCoprocReg() const { return Kind == k_CoprocReg; }
917   bool isCoprocOption() const { return Kind == k_CoprocOption; }
918   bool isCondCode() const { return Kind == k_CondCode; }
919   bool isCCOut() const { return Kind == k_CCOut; }
920   bool isITMask() const { return Kind == k_ITCondMask; }
921   bool isITCondCode() const { return Kind == k_CondCode; }
922   bool isImm() const override {
923     return Kind == k_Immediate;
924   }
925
926   bool isARMBranchTarget() const {
927     if (!isImm()) return false;
928
929     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
930       return CE->getValue() % 4 == 0;
931     return true;
932   }
933
934
935   bool isThumbBranchTarget() const {
936     if (!isImm()) return false;
937
938     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
939       return CE->getValue() % 2 == 0;
940     return true;
941   }
942
943   // checks whether this operand is an unsigned offset which fits is a field
944   // of specified width and scaled by a specific number of bits
945   template<unsigned width, unsigned scale>
946   bool isUnsignedOffset() const {
947     if (!isImm()) return false;
948     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
949     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
950       int64_t Val = CE->getValue();
951       int64_t Align = 1LL << scale;
952       int64_t Max = Align * ((1LL << width) - 1);
953       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
954     }
955     return false;
956   }
957
958   // checks whether this operand is an signed offset which fits is a field
959   // of specified width and scaled by a specific number of bits
960   template<unsigned width, unsigned scale>
961   bool isSignedOffset() const {
962     if (!isImm()) return false;
963     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
964     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
965       int64_t Val = CE->getValue();
966       int64_t Align = 1LL << scale;
967       int64_t Max = Align * ((1LL << (width-1)) - 1);
968       int64_t Min = -Align * (1LL << (width-1));
969       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
970     }
971     return false;
972   }
973
974   // checks whether this operand is a memory operand computed as an offset
975   // applied to PC. the offset may have 8 bits of magnitude and is represented
976   // with two bits of shift. textually it may be either [pc, #imm], #imm or
977   // relocable expression...
978   bool isThumbMemPC() const {
979     int64_t Val = 0;
980     if (isImm()) {
981       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
982       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
983       if (!CE) return false;
984       Val = CE->getValue();
985     }
986     else if (isMem()) {
987       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
988       if(Memory.BaseRegNum != ARM::PC) return false;
989       Val = Memory.OffsetImm->getValue();
990     }
991     else return false;
992     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
993   }
994
995   bool isFPImm() const {
996     if (!isImm()) return false;
997     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
998     if (!CE) return false;
999     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1000     return Val != -1;
1001   }
1002
1003   template<int64_t N, int64_t M>
1004   bool isImmediate() const {
1005     if (!isImm()) return false;
1006     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1007     if (!CE) return false;
1008     int64_t Value = CE->getValue();
1009     return Value >= N && Value <= M;
1010   }
1011
1012   template<int64_t N, int64_t M>
1013   bool isImmediateS4() const {
1014     if (!isImm()) return false;
1015     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1016     if (!CE) return false;
1017     int64_t Value = CE->getValue();
1018     return ((Value & 3) == 0) && Value >= N && Value <= M;
1019   }
1020
1021   bool isFBits16() const {
1022     return isImmediate<0, 17>();
1023   }
1024   bool isFBits32() const {
1025     return isImmediate<1, 33>();
1026   }
1027   bool isImm8s4() const {
1028     return isImmediateS4<-1020, 1020>();
1029   }
1030   bool isImm0_1020s4() const {
1031     return isImmediateS4<0, 1020>();
1032   }
1033   bool isImm0_508s4() const {
1034     return isImmediateS4<0, 508>();
1035   }
1036   bool isImm0_508s4Neg() const {
1037     if (!isImm()) return false;
1038     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1039     if (!CE) return false;
1040     int64_t Value = -CE->getValue();
1041     // explicitly exclude zero. we want that to use the normal 0_508 version.
1042     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1043   }
1044
1045   bool isImm0_4095Neg() const {
1046     if (!isImm()) return false;
1047     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1048     if (!CE) return false;
1049     // isImm0_4095Neg is used with 32-bit immediates only.
1050     // 32-bit immediates are zero extended to 64-bit when parsed,
1051     // thus simple -CE->getValue() results in a big negative number,
1052     // not a small positive number as intended
1053     if ((CE->getValue() >> 32) > 0) return false;
1054     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1055     return Value > 0 && Value < 4096;
1056   }
1057
1058   bool isImm0_7() const {
1059     return isImmediate<0, 7>();
1060   }
1061
1062   bool isImm1_16() const {
1063     return isImmediate<1, 16>();
1064   }
1065
1066   bool isImm1_32() const {
1067     return isImmediate<1, 32>();
1068   }
1069
1070   bool isImm8_255() const {
1071     return isImmediate<8, 255>();
1072   }
1073
1074   bool isImm256_65535Expr() const {
1075     if (!isImm()) return false;
1076     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1077     // If it's not a constant expression, it'll generate a fixup and be
1078     // handled later.
1079     if (!CE) return true;
1080     int64_t Value = CE->getValue();
1081     return Value >= 256 && Value < 65536;
1082   }
1083
1084   bool isImm0_65535Expr() const {
1085     if (!isImm()) return false;
1086     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1087     // If it's not a constant expression, it'll generate a fixup and be
1088     // handled later.
1089     if (!CE) return true;
1090     int64_t Value = CE->getValue();
1091     return Value >= 0 && Value < 65536;
1092   }
1093
1094   bool isImm24bit() const {
1095     return isImmediate<0, 0xffffff + 1>();
1096   }
1097
1098   bool isImmThumbSR() const {
1099     return isImmediate<1, 33>();
1100   }
1101
1102   bool isPKHLSLImm() const {
1103     return isImmediate<0, 32>();
1104   }
1105
1106   bool isPKHASRImm() const {
1107     return isImmediate<0, 33>();
1108   }
1109
1110   bool isAdrLabel() const {
1111     // If we have an immediate that's not a constant, treat it as a label
1112     // reference needing a fixup.
1113     if (isImm() && !isa<MCConstantExpr>(getImm()))
1114       return true;
1115
1116     // If it is a constant, it must fit into a modified immediate encoding.
1117     if (!isImm()) return false;
1118     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1119     if (!CE) return false;
1120     int64_t Value = CE->getValue();
1121     return (ARM_AM::getSOImmVal(Value) != -1 ||
1122             ARM_AM::getSOImmVal(-Value) != -1);
1123   }
1124
1125   bool isT2SOImm() const {
1126     // If we have an immediate that's not a constant, treat it as an expression
1127     // needing a fixup.
1128     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1129       // We want to avoid matching :upper16: and :lower16: as we want these
1130       // expressions to match in isImm0_65535Expr()
1131       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1132       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1133                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1134     }
1135     if (!isImm()) return false;
1136     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1137     if (!CE) return false;
1138     int64_t Value = CE->getValue();
1139     return ARM_AM::getT2SOImmVal(Value) != -1;
1140   }
1141
1142   bool isT2SOImmNot() const {
1143     if (!isImm()) return false;
1144     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1145     if (!CE) return false;
1146     int64_t Value = CE->getValue();
1147     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1148       ARM_AM::getT2SOImmVal(~Value) != -1;
1149   }
1150
1151   bool isT2SOImmNeg() const {
1152     if (!isImm()) return false;
1153     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1154     if (!CE) return false;
1155     int64_t Value = CE->getValue();
1156     // Only use this when not representable as a plain so_imm.
1157     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1158       ARM_AM::getT2SOImmVal(-Value) != -1;
1159   }
1160
1161   bool isSetEndImm() const {
1162     if (!isImm()) return false;
1163     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1164     if (!CE) return false;
1165     int64_t Value = CE->getValue();
1166     return Value == 1 || Value == 0;
1167   }
1168
1169   bool isReg() const override { return Kind == k_Register; }
1170   bool isRegList() const { return Kind == k_RegisterList; }
1171   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1172   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1173   bool isToken() const override { return Kind == k_Token; }
1174   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1175   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1176   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
1177   bool isMem() const override {
1178     if (Kind != k_Memory)
1179       return false;
1180     if (Memory.BaseRegNum &&
1181         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1182       return false;
1183     if (Memory.OffsetRegNum &&
1184         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1185       return false;
1186     return true;
1187   }
1188   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1189   bool isRegShiftedReg() const {
1190     return Kind == k_ShiftedRegister &&
1191            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1192                RegShiftedReg.SrcReg) &&
1193            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1194                RegShiftedReg.ShiftReg);
1195   }
1196   bool isRegShiftedImm() const {
1197     return Kind == k_ShiftedImmediate &&
1198            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1199                RegShiftedImm.SrcReg);
1200   }
1201   bool isRotImm() const { return Kind == k_RotateImmediate; }
1202   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1203
1204   bool isModImmNot() const {
1205     if (!isImm()) return false;
1206     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1207     if (!CE) return false;
1208     int64_t Value = CE->getValue();
1209     return ARM_AM::getSOImmVal(~Value) != -1;
1210   }
1211
1212   bool isModImmNeg() const {
1213     if (!isImm()) return false;
1214     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1215     if (!CE) return false;
1216     int64_t Value = CE->getValue();
1217     return ARM_AM::getSOImmVal(Value) == -1 &&
1218       ARM_AM::getSOImmVal(-Value) != -1;
1219   }
1220
1221   bool isThumbModImmNeg1_7() const {
1222     if (!isImm()) return false;
1223     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1224     if (!CE) return false;
1225     int32_t Value = -(int32_t)CE->getValue();
1226     return 0 < Value && Value < 8;
1227   }
1228
1229   bool isThumbModImmNeg8_255() const {
1230     if (!isImm()) return false;
1231     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1232     if (!CE) return false;
1233     int32_t Value = -(int32_t)CE->getValue();
1234     return 7 < Value && Value < 256;
1235   }
1236
1237   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1238   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1239   bool isPostIdxRegShifted() const {
1240     return Kind == k_PostIndexRegister &&
1241            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1242   }
1243   bool isPostIdxReg() const {
1244     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1245   }
1246   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1247     if (!isMem())
1248       return false;
1249     // No offset of any kind.
1250     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1251      (alignOK || Memory.Alignment == Alignment);
1252   }
1253   bool isMemPCRelImm12() const {
1254     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1255       return false;
1256     // Base register must be PC.
1257     if (Memory.BaseRegNum != ARM::PC)
1258       return false;
1259     // Immediate offset in range [-4095, 4095].
1260     if (!Memory.OffsetImm) return true;
1261     int64_t Val = Memory.OffsetImm->getValue();
1262     return (Val > -4096 && Val < 4096) ||
1263            (Val == std::numeric_limits<int32_t>::min());
1264   }
1265
1266   bool isAlignedMemory() const {
1267     return isMemNoOffset(true);
1268   }
1269
1270   bool isAlignedMemoryNone() const {
1271     return isMemNoOffset(false, 0);
1272   }
1273
1274   bool isDupAlignedMemoryNone() const {
1275     return isMemNoOffset(false, 0);
1276   }
1277
1278   bool isAlignedMemory16() const {
1279     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1280       return true;
1281     return isMemNoOffset(false, 0);
1282   }
1283
1284   bool isDupAlignedMemory16() const {
1285     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1286       return true;
1287     return isMemNoOffset(false, 0);
1288   }
1289
1290   bool isAlignedMemory32() const {
1291     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1292       return true;
1293     return isMemNoOffset(false, 0);
1294   }
1295
1296   bool isDupAlignedMemory32() const {
1297     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1298       return true;
1299     return isMemNoOffset(false, 0);
1300   }
1301
1302   bool isAlignedMemory64() const {
1303     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1304       return true;
1305     return isMemNoOffset(false, 0);
1306   }
1307
1308   bool isDupAlignedMemory64() const {
1309     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1310       return true;
1311     return isMemNoOffset(false, 0);
1312   }
1313
1314   bool isAlignedMemory64or128() const {
1315     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1316       return true;
1317     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1318       return true;
1319     return isMemNoOffset(false, 0);
1320   }
1321
1322   bool isDupAlignedMemory64or128() const {
1323     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1324       return true;
1325     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1326       return true;
1327     return isMemNoOffset(false, 0);
1328   }
1329
1330   bool isAlignedMemory64or128or256() const {
1331     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1332       return true;
1333     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1334       return true;
1335     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1336       return true;
1337     return isMemNoOffset(false, 0);
1338   }
1339
1340   bool isAddrMode2() const {
1341     if (!isMem() || Memory.Alignment != 0) return false;
1342     // Check for register offset.
1343     if (Memory.OffsetRegNum) return true;
1344     // Immediate offset in range [-4095, 4095].
1345     if (!Memory.OffsetImm) return true;
1346     int64_t Val = Memory.OffsetImm->getValue();
1347     return Val > -4096 && Val < 4096;
1348   }
1349
1350   bool isAM2OffsetImm() const {
1351     if (!isImm()) return false;
1352     // Immediate offset in range [-4095, 4095].
1353     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1354     if (!CE) return false;
1355     int64_t Val = CE->getValue();
1356     return (Val == std::numeric_limits<int32_t>::min()) ||
1357            (Val > -4096 && Val < 4096);
1358   }
1359
1360   bool isAddrMode3() const {
1361     // If we have an immediate that's not a constant, treat it as a label
1362     // reference needing a fixup. If it is a constant, it's something else
1363     // and we reject it.
1364     if (isImm() && !isa<MCConstantExpr>(getImm()))
1365       return true;
1366     if (!isMem() || Memory.Alignment != 0) return false;
1367     // No shifts are legal for AM3.
1368     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1369     // Check for register offset.
1370     if (Memory.OffsetRegNum) return true;
1371     // Immediate offset in range [-255, 255].
1372     if (!Memory.OffsetImm) return true;
1373     int64_t Val = Memory.OffsetImm->getValue();
1374     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1375     // have to check for this too.
1376     return (Val > -256 && Val < 256) ||
1377            Val == std::numeric_limits<int32_t>::min();
1378   }
1379
1380   bool isAM3Offset() const {
1381     if (isPostIdxReg())
1382       return true;
1383     if (!isImm())
1384       return false;
1385     // Immediate offset in range [-255, 255].
1386     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1387     if (!CE) return false;
1388     int64_t Val = CE->getValue();
1389     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1390     return (Val > -256 && Val < 256) ||
1391            Val == std::numeric_limits<int32_t>::min();
1392   }
1393
1394   bool isAddrMode5() const {
1395     // If we have an immediate that's not a constant, treat it as a label
1396     // reference needing a fixup. If it is a constant, it's something else
1397     // and we reject it.
1398     if (isImm() && !isa<MCConstantExpr>(getImm()))
1399       return true;
1400     if (!isMem() || Memory.Alignment != 0) return false;
1401     // Check for register offset.
1402     if (Memory.OffsetRegNum) return false;
1403     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1404     if (!Memory.OffsetImm) return true;
1405     int64_t Val = Memory.OffsetImm->getValue();
1406     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1407       Val == std::numeric_limits<int32_t>::min();
1408   }
1409
1410   bool isAddrMode5FP16() const {
1411     // If we have an immediate that's not a constant, treat it as a label
1412     // reference needing a fixup. If it is a constant, it's something else
1413     // and we reject it.
1414     if (isImm() && !isa<MCConstantExpr>(getImm()))
1415       return true;
1416     if (!isMem() || Memory.Alignment != 0) return false;
1417     // Check for register offset.
1418     if (Memory.OffsetRegNum) return false;
1419     // Immediate offset in range [-510, 510] and a multiple of 2.
1420     if (!Memory.OffsetImm) return true;
1421     int64_t Val = Memory.OffsetImm->getValue();
1422     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1423            Val == std::numeric_limits<int32_t>::min();
1424   }
1425
1426   bool isMemTBB() const {
1427     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1428         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1429       return false;
1430     return true;
1431   }
1432
1433   bool isMemTBH() const {
1434     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1435         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1436         Memory.Alignment != 0 )
1437       return false;
1438     return true;
1439   }
1440
1441   bool isMemRegOffset() const {
1442     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1443       return false;
1444     return true;
1445   }
1446
1447   bool isT2MemRegOffset() const {
1448     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1449         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1450       return false;
1451     // Only lsl #{0, 1, 2, 3} allowed.
1452     if (Memory.ShiftType == ARM_AM::no_shift)
1453       return true;
1454     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1455       return false;
1456     return true;
1457   }
1458
1459   bool isMemThumbRR() const {
1460     // Thumb reg+reg addressing is simple. Just two registers, a base and
1461     // an offset. No shifts, negations or any other complicating factors.
1462     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1463         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1464       return false;
1465     return isARMLowRegister(Memory.BaseRegNum) &&
1466       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1467   }
1468
1469   bool isMemThumbRIs4() const {
1470     if (!isMem() || Memory.OffsetRegNum != 0 ||
1471         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1472       return false;
1473     // Immediate offset, multiple of 4 in range [0, 124].
1474     if (!Memory.OffsetImm) return true;
1475     int64_t Val = Memory.OffsetImm->getValue();
1476     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1477   }
1478
1479   bool isMemThumbRIs2() const {
1480     if (!isMem() || Memory.OffsetRegNum != 0 ||
1481         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1482       return false;
1483     // Immediate offset, multiple of 4 in range [0, 62].
1484     if (!Memory.OffsetImm) return true;
1485     int64_t Val = Memory.OffsetImm->getValue();
1486     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1487   }
1488
1489   bool isMemThumbRIs1() const {
1490     if (!isMem() || Memory.OffsetRegNum != 0 ||
1491         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1492       return false;
1493     // Immediate offset in range [0, 31].
1494     if (!Memory.OffsetImm) return true;
1495     int64_t Val = Memory.OffsetImm->getValue();
1496     return Val >= 0 && Val <= 31;
1497   }
1498
1499   bool isMemThumbSPI() const {
1500     if (!isMem() || Memory.OffsetRegNum != 0 ||
1501         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1502       return false;
1503     // Immediate offset, multiple of 4 in range [0, 1020].
1504     if (!Memory.OffsetImm) return true;
1505     int64_t Val = Memory.OffsetImm->getValue();
1506     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1507   }
1508
1509   bool isMemImm8s4Offset() const {
1510     // If we have an immediate that's not a constant, treat it as a label
1511     // reference needing a fixup. If it is a constant, it's something else
1512     // and we reject it.
1513     if (isImm() && !isa<MCConstantExpr>(getImm()))
1514       return true;
1515     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1516       return false;
1517     // Immediate offset a multiple of 4 in range [-1020, 1020].
1518     if (!Memory.OffsetImm) return true;
1519     int64_t Val = Memory.OffsetImm->getValue();
1520     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1521     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1522            Val == std::numeric_limits<int32_t>::min();
1523   }
1524
1525   bool isMemImm0_1020s4Offset() const {
1526     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1527       return false;
1528     // Immediate offset a multiple of 4 in range [0, 1020].
1529     if (!Memory.OffsetImm) return true;
1530     int64_t Val = Memory.OffsetImm->getValue();
1531     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1532   }
1533
1534   bool isMemImm8Offset() const {
1535     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1536       return false;
1537     // Base reg of PC isn't allowed for these encodings.
1538     if (Memory.BaseRegNum == ARM::PC) return false;
1539     // Immediate offset in range [-255, 255].
1540     if (!Memory.OffsetImm) return true;
1541     int64_t Val = Memory.OffsetImm->getValue();
1542     return (Val == std::numeric_limits<int32_t>::min()) ||
1543            (Val > -256 && Val < 256);
1544   }
1545
1546   bool isMemPosImm8Offset() const {
1547     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1548       return false;
1549     // Immediate offset in range [0, 255].
1550     if (!Memory.OffsetImm) return true;
1551     int64_t Val = Memory.OffsetImm->getValue();
1552     return Val >= 0 && Val < 256;
1553   }
1554
1555   bool isMemNegImm8Offset() const {
1556     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1557       return false;
1558     // Base reg of PC isn't allowed for these encodings.
1559     if (Memory.BaseRegNum == ARM::PC) return false;
1560     // Immediate offset in range [-255, -1].
1561     if (!Memory.OffsetImm) return false;
1562     int64_t Val = Memory.OffsetImm->getValue();
1563     return (Val == std::numeric_limits<int32_t>::min()) ||
1564            (Val > -256 && Val < 0);
1565   }
1566
1567   bool isMemUImm12Offset() const {
1568     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1569       return false;
1570     // Immediate offset in range [0, 4095].
1571     if (!Memory.OffsetImm) return true;
1572     int64_t Val = Memory.OffsetImm->getValue();
1573     return (Val >= 0 && Val < 4096);
1574   }
1575
1576   bool isMemImm12Offset() const {
1577     // If we have an immediate that's not a constant, treat it as a label
1578     // reference needing a fixup. If it is a constant, it's something else
1579     // and we reject it.
1580
1581     if (isImm() && !isa<MCConstantExpr>(getImm()))
1582       return true;
1583
1584     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1585       return false;
1586     // Immediate offset in range [-4095, 4095].
1587     if (!Memory.OffsetImm) return true;
1588     int64_t Val = Memory.OffsetImm->getValue();
1589     return (Val > -4096 && Val < 4096) ||
1590            (Val == std::numeric_limits<int32_t>::min());
1591   }
1592
1593   bool isConstPoolAsmImm() const {
1594     // Delay processing of Constant Pool Immediate, this will turn into
1595     // a constant. Match no other operand
1596     return (isConstantPoolImm());
1597   }
1598
1599   bool isPostIdxImm8() const {
1600     if (!isImm()) return false;
1601     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1602     if (!CE) return false;
1603     int64_t Val = CE->getValue();
1604     return (Val > -256 && Val < 256) ||
1605            (Val == std::numeric_limits<int32_t>::min());
1606   }
1607
1608   bool isPostIdxImm8s4() const {
1609     if (!isImm()) return false;
1610     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1611     if (!CE) return false;
1612     int64_t Val = CE->getValue();
1613     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1614            (Val == std::numeric_limits<int32_t>::min());
1615   }
1616
1617   bool isMSRMask() const { return Kind == k_MSRMask; }
1618   bool isBankedReg() const { return Kind == k_BankedReg; }
1619   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1620
1621   // NEON operands.
1622   bool isSingleSpacedVectorList() const {
1623     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1624   }
1625
1626   bool isDoubleSpacedVectorList() const {
1627     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1628   }
1629
1630   bool isVecListOneD() const {
1631     if (!isSingleSpacedVectorList()) return false;
1632     return VectorList.Count == 1;
1633   }
1634
1635   bool isVecListDPair() const {
1636     if (!isSingleSpacedVectorList()) return false;
1637     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1638               .contains(VectorList.RegNum));
1639   }
1640
1641   bool isVecListThreeD() const {
1642     if (!isSingleSpacedVectorList()) return false;
1643     return VectorList.Count == 3;
1644   }
1645
1646   bool isVecListFourD() const {
1647     if (!isSingleSpacedVectorList()) return false;
1648     return VectorList.Count == 4;
1649   }
1650
1651   bool isVecListDPairSpaced() const {
1652     if (Kind != k_VectorList) return false;
1653     if (isSingleSpacedVectorList()) return false;
1654     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1655               .contains(VectorList.RegNum));
1656   }
1657
1658   bool isVecListThreeQ() const {
1659     if (!isDoubleSpacedVectorList()) return false;
1660     return VectorList.Count == 3;
1661   }
1662
1663   bool isVecListFourQ() const {
1664     if (!isDoubleSpacedVectorList()) return false;
1665     return VectorList.Count == 4;
1666   }
1667
1668   bool isSingleSpacedVectorAllLanes() const {
1669     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1670   }
1671
1672   bool isDoubleSpacedVectorAllLanes() const {
1673     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1674   }
1675
1676   bool isVecListOneDAllLanes() const {
1677     if (!isSingleSpacedVectorAllLanes()) return false;
1678     return VectorList.Count == 1;
1679   }
1680
1681   bool isVecListDPairAllLanes() const {
1682     if (!isSingleSpacedVectorAllLanes()) return false;
1683     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1684               .contains(VectorList.RegNum));
1685   }
1686
1687   bool isVecListDPairSpacedAllLanes() const {
1688     if (!isDoubleSpacedVectorAllLanes()) return false;
1689     return VectorList.Count == 2;
1690   }
1691
1692   bool isVecListThreeDAllLanes() const {
1693     if (!isSingleSpacedVectorAllLanes()) return false;
1694     return VectorList.Count == 3;
1695   }
1696
1697   bool isVecListThreeQAllLanes() const {
1698     if (!isDoubleSpacedVectorAllLanes()) return false;
1699     return VectorList.Count == 3;
1700   }
1701
1702   bool isVecListFourDAllLanes() const {
1703     if (!isSingleSpacedVectorAllLanes()) return false;
1704     return VectorList.Count == 4;
1705   }
1706
1707   bool isVecListFourQAllLanes() const {
1708     if (!isDoubleSpacedVectorAllLanes()) return false;
1709     return VectorList.Count == 4;
1710   }
1711
1712   bool isSingleSpacedVectorIndexed() const {
1713     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1714   }
1715
1716   bool isDoubleSpacedVectorIndexed() const {
1717     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1718   }
1719
1720   bool isVecListOneDByteIndexed() const {
1721     if (!isSingleSpacedVectorIndexed()) return false;
1722     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1723   }
1724
1725   bool isVecListOneDHWordIndexed() const {
1726     if (!isSingleSpacedVectorIndexed()) return false;
1727     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1728   }
1729
1730   bool isVecListOneDWordIndexed() const {
1731     if (!isSingleSpacedVectorIndexed()) return false;
1732     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1733   }
1734
1735   bool isVecListTwoDByteIndexed() const {
1736     if (!isSingleSpacedVectorIndexed()) return false;
1737     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1738   }
1739
1740   bool isVecListTwoDHWordIndexed() const {
1741     if (!isSingleSpacedVectorIndexed()) return false;
1742     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1743   }
1744
1745   bool isVecListTwoQWordIndexed() const {
1746     if (!isDoubleSpacedVectorIndexed()) return false;
1747     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1748   }
1749
1750   bool isVecListTwoQHWordIndexed() const {
1751     if (!isDoubleSpacedVectorIndexed()) return false;
1752     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1753   }
1754
1755   bool isVecListTwoDWordIndexed() const {
1756     if (!isSingleSpacedVectorIndexed()) return false;
1757     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1758   }
1759
1760   bool isVecListThreeDByteIndexed() const {
1761     if (!isSingleSpacedVectorIndexed()) return false;
1762     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1763   }
1764
1765   bool isVecListThreeDHWordIndexed() const {
1766     if (!isSingleSpacedVectorIndexed()) return false;
1767     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1768   }
1769
1770   bool isVecListThreeQWordIndexed() const {
1771     if (!isDoubleSpacedVectorIndexed()) return false;
1772     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1773   }
1774
1775   bool isVecListThreeQHWordIndexed() const {
1776     if (!isDoubleSpacedVectorIndexed()) return false;
1777     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1778   }
1779
1780   bool isVecListThreeDWordIndexed() const {
1781     if (!isSingleSpacedVectorIndexed()) return false;
1782     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1783   }
1784
1785   bool isVecListFourDByteIndexed() const {
1786     if (!isSingleSpacedVectorIndexed()) return false;
1787     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1788   }
1789
1790   bool isVecListFourDHWordIndexed() const {
1791     if (!isSingleSpacedVectorIndexed()) return false;
1792     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1793   }
1794
1795   bool isVecListFourQWordIndexed() const {
1796     if (!isDoubleSpacedVectorIndexed()) return false;
1797     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1798   }
1799
1800   bool isVecListFourQHWordIndexed() const {
1801     if (!isDoubleSpacedVectorIndexed()) return false;
1802     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1803   }
1804
1805   bool isVecListFourDWordIndexed() const {
1806     if (!isSingleSpacedVectorIndexed()) return false;
1807     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1808   }
1809
1810   bool isVectorIndex8() const {
1811     if (Kind != k_VectorIndex) return false;
1812     return VectorIndex.Val < 8;
1813   }
1814
1815   bool isVectorIndex16() const {
1816     if (Kind != k_VectorIndex) return false;
1817     return VectorIndex.Val < 4;
1818   }
1819
1820   bool isVectorIndex32() const {
1821     if (Kind != k_VectorIndex) return false;
1822     return VectorIndex.Val < 2;
1823   }
1824   bool isVectorIndex64() const {
1825     if (Kind != k_VectorIndex) return false;
1826     return VectorIndex.Val < 1;
1827   }
1828
1829   bool isNEONi8splat() const {
1830     if (!isImm()) return false;
1831     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1832     // Must be a constant.
1833     if (!CE) return false;
1834     int64_t Value = CE->getValue();
1835     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1836     // value.
1837     return Value >= 0 && Value < 256;
1838   }
1839
1840   bool isNEONi16splat() const {
1841     if (isNEONByteReplicate(2))
1842       return false; // Leave that for bytes replication and forbid by default.
1843     if (!isImm())
1844       return false;
1845     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1846     // Must be a constant.
1847     if (!CE) return false;
1848     unsigned Value = CE->getValue();
1849     return ARM_AM::isNEONi16splat(Value);
1850   }
1851
1852   bool isNEONi16splatNot() const {
1853     if (!isImm())
1854       return false;
1855     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1856     // Must be a constant.
1857     if (!CE) return false;
1858     unsigned Value = CE->getValue();
1859     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1860   }
1861
1862   bool isNEONi32splat() const {
1863     if (isNEONByteReplicate(4))
1864       return false; // Leave that for bytes replication and forbid by default.
1865     if (!isImm())
1866       return false;
1867     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1868     // Must be a constant.
1869     if (!CE) return false;
1870     unsigned Value = CE->getValue();
1871     return ARM_AM::isNEONi32splat(Value);
1872   }
1873
1874   bool isNEONi32splatNot() const {
1875     if (!isImm())
1876       return false;
1877     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1878     // Must be a constant.
1879     if (!CE) return false;
1880     unsigned Value = CE->getValue();
1881     return ARM_AM::isNEONi32splat(~Value);
1882   }
1883
1884   static bool isValidNEONi32vmovImm(int64_t Value) {
1885     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1886     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1887     return ((Value & 0xffffffffffffff00) == 0) ||
1888            ((Value & 0xffffffffffff00ff) == 0) ||
1889            ((Value & 0xffffffffff00ffff) == 0) ||
1890            ((Value & 0xffffffff00ffffff) == 0) ||
1891            ((Value & 0xffffffffffff00ff) == 0xff) ||
1892            ((Value & 0xffffffffff00ffff) == 0xffff);
1893   }
1894
1895   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
1896     assert((Width == 8 || Width == 16 || Width == 32) &&
1897            "Invalid element width");
1898     assert(NumElems * Width <= 64 && "Invalid result width");
1899
1900     if (!isImm())
1901       return false;
1902     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1903     // Must be a constant.
1904     if (!CE)
1905       return false;
1906     int64_t Value = CE->getValue();
1907     if (!Value)
1908       return false; // Don't bother with zero.
1909     if (Inv)
1910       Value = ~Value;
1911
1912     uint64_t Mask = (1ull << Width) - 1;
1913     uint64_t Elem = Value & Mask;
1914     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
1915       return false;
1916     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
1917       return false;
1918
1919     for (unsigned i = 1; i < NumElems; ++i) {
1920       Value >>= Width;
1921       if ((Value & Mask) != Elem)
1922         return false;
1923     }
1924     return true;
1925   }
1926
1927   bool isNEONByteReplicate(unsigned NumBytes) const {
1928     return isNEONReplicate(8, NumBytes, false);
1929   }
1930
1931   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
1932     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
1933            "Invalid source width");
1934     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
1935            "Invalid destination width");
1936     assert(FromW < ToW && "ToW is not less than FromW");
1937   }
1938
1939   template<unsigned FromW, unsigned ToW>
1940   bool isNEONmovReplicate() const {
1941     checkNeonReplicateArgs(FromW, ToW);
1942     if (ToW == 64 && isNEONi64splat())
1943       return false;
1944     return isNEONReplicate(FromW, ToW / FromW, false);
1945   }
1946
1947   template<unsigned FromW, unsigned ToW>
1948   bool isNEONinvReplicate() const {
1949     checkNeonReplicateArgs(FromW, ToW);
1950     return isNEONReplicate(FromW, ToW / FromW, true);
1951   }
1952
1953   bool isNEONi32vmov() const {
1954     if (isNEONByteReplicate(4))
1955       return false; // Let it to be classified as byte-replicate case.
1956     if (!isImm())
1957       return false;
1958     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1959     // Must be a constant.
1960     if (!CE)
1961       return false;
1962     return isValidNEONi32vmovImm(CE->getValue());
1963   }
1964
1965   bool isNEONi32vmovNeg() const {
1966     if (!isImm()) return false;
1967     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1968     // Must be a constant.
1969     if (!CE) return false;
1970     return isValidNEONi32vmovImm(~CE->getValue());
1971   }
1972
1973   bool isNEONi64splat() const {
1974     if (!isImm()) return false;
1975     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1976     // Must be a constant.
1977     if (!CE) return false;
1978     uint64_t Value = CE->getValue();
1979     // i64 value with each byte being either 0 or 0xff.
1980     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1981       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1982     return true;
1983   }
1984
1985   template<int64_t Angle, int64_t Remainder>
1986   bool isComplexRotation() const {
1987     if (!isImm()) return false;
1988
1989     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1990     if (!CE) return false;
1991     uint64_t Value = CE->getValue();
1992
1993     return (Value % Angle == Remainder && Value <= 270);
1994   }
1995
1996   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1997     // Add as immediates when possible.  Null MCExpr = 0.
1998     if (!Expr)
1999       Inst.addOperand(MCOperand::createImm(0));
2000     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
2001       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2002     else
2003       Inst.addOperand(MCOperand::createExpr(Expr));
2004   }
2005
2006   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2007     assert(N == 1 && "Invalid number of operands!");
2008     addExpr(Inst, getImm());
2009   }
2010
2011   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2012     assert(N == 1 && "Invalid number of operands!");
2013     addExpr(Inst, getImm());
2014   }
2015
2016   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2017     assert(N == 2 && "Invalid number of operands!");
2018     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2019     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2020     Inst.addOperand(MCOperand::createReg(RegNum));
2021   }
2022
2023   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2024     assert(N == 1 && "Invalid number of operands!");
2025     Inst.addOperand(MCOperand::createImm(getCoproc()));
2026   }
2027
2028   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2029     assert(N == 1 && "Invalid number of operands!");
2030     Inst.addOperand(MCOperand::createImm(getCoproc()));
2031   }
2032
2033   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2034     assert(N == 1 && "Invalid number of operands!");
2035     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2036   }
2037
2038   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2039     assert(N == 1 && "Invalid number of operands!");
2040     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2041   }
2042
2043   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2044     assert(N == 1 && "Invalid number of operands!");
2045     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2046   }
2047
2048   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2049     assert(N == 1 && "Invalid number of operands!");
2050     Inst.addOperand(MCOperand::createReg(getReg()));
2051   }
2052
2053   void addRegOperands(MCInst &Inst, unsigned N) const {
2054     assert(N == 1 && "Invalid number of operands!");
2055     Inst.addOperand(MCOperand::createReg(getReg()));
2056   }
2057
2058   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2059     assert(N == 3 && "Invalid number of operands!");
2060     assert(isRegShiftedReg() &&
2061            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2062     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2063     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2064     Inst.addOperand(MCOperand::createImm(
2065       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2066   }
2067
2068   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2069     assert(N == 2 && "Invalid number of operands!");
2070     assert(isRegShiftedImm() &&
2071            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2072     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2073     // Shift of #32 is encoded as 0 where permitted
2074     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2075     Inst.addOperand(MCOperand::createImm(
2076       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2077   }
2078
2079   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2080     assert(N == 1 && "Invalid number of operands!");
2081     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2082                                          ShifterImm.Imm));
2083   }
2084
2085   void addRegListOperands(MCInst &Inst, unsigned N) const {
2086     assert(N == 1 && "Invalid number of operands!");
2087     const SmallVectorImpl<unsigned> &RegList = getRegList();
2088     for (SmallVectorImpl<unsigned>::const_iterator
2089            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2090       Inst.addOperand(MCOperand::createReg(*I));
2091   }
2092
2093   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2094     addRegListOperands(Inst, N);
2095   }
2096
2097   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2098     addRegListOperands(Inst, N);
2099   }
2100
2101   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2102     assert(N == 1 && "Invalid number of operands!");
2103     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2104     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2105   }
2106
2107   void addModImmOperands(MCInst &Inst, unsigned N) const {
2108     assert(N == 1 && "Invalid number of operands!");
2109
2110     // Support for fixups (MCFixup)
2111     if (isImm())
2112       return addImmOperands(Inst, N);
2113
2114     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2115   }
2116
2117   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2118     assert(N == 1 && "Invalid number of operands!");
2119     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2120     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2121     Inst.addOperand(MCOperand::createImm(Enc));
2122   }
2123
2124   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2125     assert(N == 1 && "Invalid number of operands!");
2126     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2127     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2128     Inst.addOperand(MCOperand::createImm(Enc));
2129   }
2130
2131   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2132     assert(N == 1 && "Invalid number of operands!");
2133     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2134     uint32_t Val = -CE->getValue();
2135     Inst.addOperand(MCOperand::createImm(Val));
2136   }
2137
2138   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2139     assert(N == 1 && "Invalid number of operands!");
2140     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2141     uint32_t Val = -CE->getValue();
2142     Inst.addOperand(MCOperand::createImm(Val));
2143   }
2144
2145   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2146     assert(N == 1 && "Invalid number of operands!");
2147     // Munge the lsb/width into a bitfield mask.
2148     unsigned lsb = Bitfield.LSB;
2149     unsigned width = Bitfield.Width;
2150     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2151     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2152                       (32 - (lsb + width)));
2153     Inst.addOperand(MCOperand::createImm(Mask));
2154   }
2155
2156   void addImmOperands(MCInst &Inst, unsigned N) const {
2157     assert(N == 1 && "Invalid number of operands!");
2158     addExpr(Inst, getImm());
2159   }
2160
2161   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2162     assert(N == 1 && "Invalid number of operands!");
2163     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2164     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2165   }
2166
2167   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2168     assert(N == 1 && "Invalid number of operands!");
2169     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2170     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2171   }
2172
2173   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2174     assert(N == 1 && "Invalid number of operands!");
2175     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2176     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2177     Inst.addOperand(MCOperand::createImm(Val));
2178   }
2179
2180   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2181     assert(N == 1 && "Invalid number of operands!");
2182     // FIXME: We really want to scale the value here, but the LDRD/STRD
2183     // instruction don't encode operands that way yet.
2184     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2185     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2186   }
2187
2188   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2189     assert(N == 1 && "Invalid number of operands!");
2190     // The immediate is scaled by four in the encoding and is stored
2191     // in the MCInst as such. Lop off the low two bits here.
2192     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2193     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2194   }
2195
2196   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2197     assert(N == 1 && "Invalid number of operands!");
2198     // The immediate is scaled by four in the encoding and is stored
2199     // in the MCInst as such. Lop off the low two bits here.
2200     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2201     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2202   }
2203
2204   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2205     assert(N == 1 && "Invalid number of operands!");
2206     // The immediate is scaled by four in the encoding and is stored
2207     // in the MCInst as such. Lop off the low two bits here.
2208     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2209     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2210   }
2211
2212   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2213     assert(N == 1 && "Invalid number of operands!");
2214     // The constant encodes as the immediate-1, and we store in the instruction
2215     // the bits as encoded, so subtract off one here.
2216     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2217     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2218   }
2219
2220   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2221     assert(N == 1 && "Invalid number of operands!");
2222     // The constant encodes as the immediate-1, and we store in the instruction
2223     // the bits as encoded, so subtract off one here.
2224     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2225     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2226   }
2227
2228   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2229     assert(N == 1 && "Invalid number of operands!");
2230     // The constant encodes as the immediate, except for 32, which encodes as
2231     // zero.
2232     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2233     unsigned Imm = CE->getValue();
2234     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2235   }
2236
2237   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2238     assert(N == 1 && "Invalid number of operands!");
2239     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2240     // the instruction as well.
2241     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2242     int Val = CE->getValue();
2243     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2244   }
2245
2246   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2247     assert(N == 1 && "Invalid number of operands!");
2248     // The operand is actually a t2_so_imm, but we have its bitwise
2249     // negation in the assembly source, so twiddle it here.
2250     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2251     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2252   }
2253
2254   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2255     assert(N == 1 && "Invalid number of operands!");
2256     // The operand is actually a t2_so_imm, but we have its
2257     // negation in the assembly source, so twiddle it here.
2258     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2259     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2260   }
2261
2262   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2263     assert(N == 1 && "Invalid number of operands!");
2264     // The operand is actually an imm0_4095, but we have its
2265     // negation in the assembly source, so twiddle it here.
2266     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2267     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2268   }
2269
2270   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2271     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2272       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2273       return;
2274     }
2275
2276     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2277     assert(SR && "Unknown value type!");
2278     Inst.addOperand(MCOperand::createExpr(SR));
2279   }
2280
2281   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2282     assert(N == 1 && "Invalid number of operands!");
2283     if (isImm()) {
2284       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2285       if (CE) {
2286         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2287         return;
2288       }
2289
2290       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2291
2292       assert(SR && "Unknown value type!");
2293       Inst.addOperand(MCOperand::createExpr(SR));
2294       return;
2295     }
2296
2297     assert(isMem()  && "Unknown value type!");
2298     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2299     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2300   }
2301
2302   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2303     assert(N == 1 && "Invalid number of operands!");
2304     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2305   }
2306
2307   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2308     assert(N == 1 && "Invalid number of operands!");
2309     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2310   }
2311
2312   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2313     assert(N == 1 && "Invalid number of operands!");
2314     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2315   }
2316
2317   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2318     assert(N == 1 && "Invalid number of operands!");
2319     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2320   }
2321
2322   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2323     assert(N == 1 && "Invalid number of operands!");
2324     int32_t Imm = Memory.OffsetImm->getValue();
2325     Inst.addOperand(MCOperand::createImm(Imm));
2326   }
2327
2328   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2329     assert(N == 1 && "Invalid number of operands!");
2330     assert(isImm() && "Not an immediate!");
2331
2332     // If we have an immediate that's not a constant, treat it as a label
2333     // reference needing a fixup.
2334     if (!isa<MCConstantExpr>(getImm())) {
2335       Inst.addOperand(MCOperand::createExpr(getImm()));
2336       return;
2337     }
2338
2339     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2340     int Val = CE->getValue();
2341     Inst.addOperand(MCOperand::createImm(Val));
2342   }
2343
2344   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2345     assert(N == 2 && "Invalid number of operands!");
2346     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2347     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2348   }
2349
2350   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2351     addAlignedMemoryOperands(Inst, N);
2352   }
2353
2354   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2355     addAlignedMemoryOperands(Inst, N);
2356   }
2357
2358   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2359     addAlignedMemoryOperands(Inst, N);
2360   }
2361
2362   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2363     addAlignedMemoryOperands(Inst, N);
2364   }
2365
2366   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2367     addAlignedMemoryOperands(Inst, N);
2368   }
2369
2370   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2371     addAlignedMemoryOperands(Inst, N);
2372   }
2373
2374   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2375     addAlignedMemoryOperands(Inst, N);
2376   }
2377
2378   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2379     addAlignedMemoryOperands(Inst, N);
2380   }
2381
2382   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2383     addAlignedMemoryOperands(Inst, N);
2384   }
2385
2386   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2387     addAlignedMemoryOperands(Inst, N);
2388   }
2389
2390   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2391     addAlignedMemoryOperands(Inst, N);
2392   }
2393
2394   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2395     assert(N == 3 && "Invalid number of operands!");
2396     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2397     if (!Memory.OffsetRegNum) {
2398       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2399       // Special case for #-0
2400       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2401       if (Val < 0) Val = -Val;
2402       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2403     } else {
2404       // For register offset, we encode the shift type and negation flag
2405       // here.
2406       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2407                               Memory.ShiftImm, Memory.ShiftType);
2408     }
2409     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2410     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2411     Inst.addOperand(MCOperand::createImm(Val));
2412   }
2413
2414   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2415     assert(N == 2 && "Invalid number of operands!");
2416     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2417     assert(CE && "non-constant AM2OffsetImm operand!");
2418     int32_t Val = CE->getValue();
2419     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2420     // Special case for #-0
2421     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2422     if (Val < 0) Val = -Val;
2423     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2424     Inst.addOperand(MCOperand::createReg(0));
2425     Inst.addOperand(MCOperand::createImm(Val));
2426   }
2427
2428   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2429     assert(N == 3 && "Invalid number of operands!");
2430     // If we have an immediate that's not a constant, treat it as a label
2431     // reference needing a fixup. If it is a constant, it's something else
2432     // and we reject it.
2433     if (isImm()) {
2434       Inst.addOperand(MCOperand::createExpr(getImm()));
2435       Inst.addOperand(MCOperand::createReg(0));
2436       Inst.addOperand(MCOperand::createImm(0));
2437       return;
2438     }
2439
2440     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2441     if (!Memory.OffsetRegNum) {
2442       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2443       // Special case for #-0
2444       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2445       if (Val < 0) Val = -Val;
2446       Val = ARM_AM::getAM3Opc(AddSub, Val);
2447     } else {
2448       // For register offset, we encode the shift type and negation flag
2449       // here.
2450       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2451     }
2452     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2453     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2454     Inst.addOperand(MCOperand::createImm(Val));
2455   }
2456
2457   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2458     assert(N == 2 && "Invalid number of operands!");
2459     if (Kind == k_PostIndexRegister) {
2460       int32_t Val =
2461         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2462       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2463       Inst.addOperand(MCOperand::createImm(Val));
2464       return;
2465     }
2466
2467     // Constant offset.
2468     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2469     int32_t Val = CE->getValue();
2470     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2471     // Special case for #-0
2472     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2473     if (Val < 0) Val = -Val;
2474     Val = ARM_AM::getAM3Opc(AddSub, Val);
2475     Inst.addOperand(MCOperand::createReg(0));
2476     Inst.addOperand(MCOperand::createImm(Val));
2477   }
2478
2479   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2480     assert(N == 2 && "Invalid number of operands!");
2481     // If we have an immediate that's not a constant, treat it as a label
2482     // reference needing a fixup. If it is a constant, it's something else
2483     // and we reject it.
2484     if (isImm()) {
2485       Inst.addOperand(MCOperand::createExpr(getImm()));
2486       Inst.addOperand(MCOperand::createImm(0));
2487       return;
2488     }
2489
2490     // The lower two bits are always zero and as such are not encoded.
2491     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2492     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2493     // Special case for #-0
2494     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2495     if (Val < 0) Val = -Val;
2496     Val = ARM_AM::getAM5Opc(AddSub, Val);
2497     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2498     Inst.addOperand(MCOperand::createImm(Val));
2499   }
2500
2501   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2502     assert(N == 2 && "Invalid number of operands!");
2503     // If we have an immediate that's not a constant, treat it as a label
2504     // reference needing a fixup. If it is a constant, it's something else
2505     // and we reject it.
2506     if (isImm()) {
2507       Inst.addOperand(MCOperand::createExpr(getImm()));
2508       Inst.addOperand(MCOperand::createImm(0));
2509       return;
2510     }
2511
2512     // The lower bit is always zero and as such is not encoded.
2513     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2514     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2515     // Special case for #-0
2516     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2517     if (Val < 0) Val = -Val;
2518     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2519     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2520     Inst.addOperand(MCOperand::createImm(Val));
2521   }
2522
2523   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2524     assert(N == 2 && "Invalid number of operands!");
2525     // If we have an immediate that's not a constant, treat it as a label
2526     // reference needing a fixup. If it is a constant, it's something else
2527     // and we reject it.
2528     if (isImm()) {
2529       Inst.addOperand(MCOperand::createExpr(getImm()));
2530       Inst.addOperand(MCOperand::createImm(0));
2531       return;
2532     }
2533
2534     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2535     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2536     Inst.addOperand(MCOperand::createImm(Val));
2537   }
2538
2539   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2540     assert(N == 2 && "Invalid number of operands!");
2541     // The lower two bits are always zero and as such are not encoded.
2542     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2543     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2544     Inst.addOperand(MCOperand::createImm(Val));
2545   }
2546
2547   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2548     assert(N == 2 && "Invalid number of operands!");
2549     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2550     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2551     Inst.addOperand(MCOperand::createImm(Val));
2552   }
2553
2554   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2555     addMemImm8OffsetOperands(Inst, N);
2556   }
2557
2558   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2559     addMemImm8OffsetOperands(Inst, N);
2560   }
2561
2562   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2563     assert(N == 2 && "Invalid number of operands!");
2564     // If this is an immediate, it's a label reference.
2565     if (isImm()) {
2566       addExpr(Inst, getImm());
2567       Inst.addOperand(MCOperand::createImm(0));
2568       return;
2569     }
2570
2571     // Otherwise, it's a normal memory reg+offset.
2572     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2573     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2574     Inst.addOperand(MCOperand::createImm(Val));
2575   }
2576
2577   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2578     assert(N == 2 && "Invalid number of operands!");
2579     // If this is an immediate, it's a label reference.
2580     if (isImm()) {
2581       addExpr(Inst, getImm());
2582       Inst.addOperand(MCOperand::createImm(0));
2583       return;
2584     }
2585
2586     // Otherwise, it's a normal memory reg+offset.
2587     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2588     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2589     Inst.addOperand(MCOperand::createImm(Val));
2590   }
2591
2592   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2593     assert(N == 1 && "Invalid number of operands!");
2594     // This is container for the immediate that we will create the constant
2595     // pool from
2596     addExpr(Inst, getConstantPoolImm());
2597     return;
2598   }
2599
2600   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2601     assert(N == 2 && "Invalid number of operands!");
2602     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2603     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2604   }
2605
2606   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2607     assert(N == 2 && "Invalid number of operands!");
2608     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2609     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2610   }
2611
2612   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2613     assert(N == 3 && "Invalid number of operands!");
2614     unsigned Val =
2615       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2616                         Memory.ShiftImm, Memory.ShiftType);
2617     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2618     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2619     Inst.addOperand(MCOperand::createImm(Val));
2620   }
2621
2622   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2623     assert(N == 3 && "Invalid number of operands!");
2624     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2625     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2626     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2627   }
2628
2629   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2630     assert(N == 2 && "Invalid number of operands!");
2631     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2632     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2633   }
2634
2635   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2636     assert(N == 2 && "Invalid number of operands!");
2637     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2638     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2639     Inst.addOperand(MCOperand::createImm(Val));
2640   }
2641
2642   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2643     assert(N == 2 && "Invalid number of operands!");
2644     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2645     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2646     Inst.addOperand(MCOperand::createImm(Val));
2647   }
2648
2649   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2650     assert(N == 2 && "Invalid number of operands!");
2651     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2652     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2653     Inst.addOperand(MCOperand::createImm(Val));
2654   }
2655
2656   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2657     assert(N == 2 && "Invalid number of operands!");
2658     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2659     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2660     Inst.addOperand(MCOperand::createImm(Val));
2661   }
2662
2663   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2664     assert(N == 1 && "Invalid number of operands!");
2665     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2666     assert(CE && "non-constant post-idx-imm8 operand!");
2667     int Imm = CE->getValue();
2668     bool isAdd = Imm >= 0;
2669     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2670     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2671     Inst.addOperand(MCOperand::createImm(Imm));
2672   }
2673
2674   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2675     assert(N == 1 && "Invalid number of operands!");
2676     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2677     assert(CE && "non-constant post-idx-imm8s4 operand!");
2678     int Imm = CE->getValue();
2679     bool isAdd = Imm >= 0;
2680     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2681     // Immediate is scaled by 4.
2682     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2683     Inst.addOperand(MCOperand::createImm(Imm));
2684   }
2685
2686   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2687     assert(N == 2 && "Invalid number of operands!");
2688     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2689     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2690   }
2691
2692   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2693     assert(N == 2 && "Invalid number of operands!");
2694     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2695     // The sign, shift type, and shift amount are encoded in a single operand
2696     // using the AM2 encoding helpers.
2697     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2698     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2699                                      PostIdxReg.ShiftTy);
2700     Inst.addOperand(MCOperand::createImm(Imm));
2701   }
2702
2703   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2704     assert(N == 1 && "Invalid number of operands!");
2705     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2706   }
2707
2708   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2709     assert(N == 1 && "Invalid number of operands!");
2710     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2711   }
2712
2713   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2714     assert(N == 1 && "Invalid number of operands!");
2715     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2716   }
2717
2718   void addVecListOperands(MCInst &Inst, unsigned N) const {
2719     assert(N == 1 && "Invalid number of operands!");
2720     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2721   }
2722
2723   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2724     assert(N == 2 && "Invalid number of operands!");
2725     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2726     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2727   }
2728
2729   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2730     assert(N == 1 && "Invalid number of operands!");
2731     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2732   }
2733
2734   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2735     assert(N == 1 && "Invalid number of operands!");
2736     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2737   }
2738
2739   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2740     assert(N == 1 && "Invalid number of operands!");
2741     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2742   }
2743
2744   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
2745     assert(N == 1 && "Invalid number of operands!");
2746     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2747   }
2748
2749   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2750     assert(N == 1 && "Invalid number of operands!");
2751     // The immediate encodes the type of constant as well as the value.
2752     // Mask in that this is an i8 splat.
2753     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2754     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2755   }
2756
2757   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2758     assert(N == 1 && "Invalid number of operands!");
2759     // The immediate encodes the type of constant as well as the value.
2760     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2761     unsigned Value = CE->getValue();
2762     Value = ARM_AM::encodeNEONi16splat(Value);
2763     Inst.addOperand(MCOperand::createImm(Value));
2764   }
2765
2766   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2767     assert(N == 1 && "Invalid number of operands!");
2768     // The immediate encodes the type of constant as well as the value.
2769     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2770     unsigned Value = CE->getValue();
2771     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2772     Inst.addOperand(MCOperand::createImm(Value));
2773   }
2774
2775   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2776     assert(N == 1 && "Invalid number of operands!");
2777     // The immediate encodes the type of constant as well as the value.
2778     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2779     unsigned Value = CE->getValue();
2780     Value = ARM_AM::encodeNEONi32splat(Value);
2781     Inst.addOperand(MCOperand::createImm(Value));
2782   }
2783
2784   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2785     assert(N == 1 && "Invalid number of operands!");
2786     // The immediate encodes the type of constant as well as the value.
2787     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2788     unsigned Value = CE->getValue();
2789     Value = ARM_AM::encodeNEONi32splat(~Value);
2790     Inst.addOperand(MCOperand::createImm(Value));
2791   }
2792
2793   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
2794     // The immediate encodes the type of constant as well as the value.
2795     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2796     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2797             Inst.getOpcode() == ARM::VMOVv16i8) &&
2798           "All instructions that wants to replicate non-zero byte "
2799           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2800     unsigned Value = CE->getValue();
2801     if (Inv)
2802       Value = ~Value;
2803     unsigned B = Value & 0xff;
2804     B |= 0xe00; // cmode = 0b1110
2805     Inst.addOperand(MCOperand::createImm(B));
2806   }
2807
2808   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
2809     assert(N == 1 && "Invalid number of operands!");
2810     addNEONi8ReplicateOperands(Inst, true);
2811   }
2812
2813   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
2814     if (Value >= 256 && Value <= 0xffff)
2815       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2816     else if (Value > 0xffff && Value <= 0xffffff)
2817       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2818     else if (Value > 0xffffff)
2819       Value = (Value >> 24) | 0x600;
2820     return Value;
2821   }
2822
2823   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2824     assert(N == 1 && "Invalid number of operands!");
2825     // The immediate encodes the type of constant as well as the value.
2826     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2827     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
2828     Inst.addOperand(MCOperand::createImm(Value));
2829   }
2830
2831   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
2832     assert(N == 1 && "Invalid number of operands!");
2833     addNEONi8ReplicateOperands(Inst, false);
2834   }
2835
2836   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
2837     assert(N == 1 && "Invalid number of operands!");
2838     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2839     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
2840             Inst.getOpcode() == ARM::VMOVv8i16 ||
2841             Inst.getOpcode() == ARM::VMVNv4i16 ||
2842             Inst.getOpcode() == ARM::VMVNv8i16) &&
2843           "All instructions that want to replicate non-zero half-word "
2844           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
2845     uint64_t Value = CE->getValue();
2846     unsigned Elem = Value & 0xffff;
2847     if (Elem >= 256)
2848       Elem = (Elem >> 8) | 0x200;
2849     Inst.addOperand(MCOperand::createImm(Elem));
2850   }
2851
2852   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2853     assert(N == 1 && "Invalid number of operands!");
2854     // The immediate encodes the type of constant as well as the value.
2855     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2856     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
2857     Inst.addOperand(MCOperand::createImm(Value));
2858   }
2859
2860   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
2861     assert(N == 1 && "Invalid number of operands!");
2862     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2863     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
2864             Inst.getOpcode() == ARM::VMOVv4i32 ||
2865             Inst.getOpcode() == ARM::VMVNv2i32 ||
2866             Inst.getOpcode() == ARM::VMVNv4i32) &&
2867           "All instructions that want to replicate non-zero word "
2868           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
2869     uint64_t Value = CE->getValue();
2870     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
2871     Inst.addOperand(MCOperand::createImm(Elem));
2872   }
2873
2874   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2875     assert(N == 1 && "Invalid number of operands!");
2876     // The immediate encodes the type of constant as well as the value.
2877     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2878     uint64_t Value = CE->getValue();
2879     unsigned Imm = 0;
2880     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2881       Imm |= (Value & 1) << i;
2882     }
2883     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2884   }
2885
2886   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
2887     assert(N == 1 && "Invalid number of operands!");
2888     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2889     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
2890   }
2891
2892   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
2893     assert(N == 1 && "Invalid number of operands!");
2894     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2895     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
2896   }
2897
2898   void print(raw_ostream &OS) const override;
2899
2900   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2901     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2902     Op->ITMask.Mask = Mask;
2903     Op->StartLoc = S;
2904     Op->EndLoc = S;
2905     return Op;
2906   }
2907
2908   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2909                                                     SMLoc S) {
2910     auto Op = make_unique<ARMOperand>(k_CondCode);
2911     Op->CC.Val = CC;
2912     Op->StartLoc = S;
2913     Op->EndLoc = S;
2914     return Op;
2915   }
2916
2917   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2918     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2919     Op->Cop.Val = CopVal;
2920     Op->StartLoc = S;
2921     Op->EndLoc = S;
2922     return Op;
2923   }
2924
2925   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2926     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2927     Op->Cop.Val = CopVal;
2928     Op->StartLoc = S;
2929     Op->EndLoc = S;
2930     return Op;
2931   }
2932
2933   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2934                                                         SMLoc E) {
2935     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2936     Op->Cop.Val = Val;
2937     Op->StartLoc = S;
2938     Op->EndLoc = E;
2939     return Op;
2940   }
2941
2942   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2943     auto Op = make_unique<ARMOperand>(k_CCOut);
2944     Op->Reg.RegNum = RegNum;
2945     Op->StartLoc = S;
2946     Op->EndLoc = S;
2947     return Op;
2948   }
2949
2950   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2951     auto Op = make_unique<ARMOperand>(k_Token);
2952     Op->Tok.Data = Str.data();
2953     Op->Tok.Length = Str.size();
2954     Op->StartLoc = S;
2955     Op->EndLoc = S;
2956     return Op;
2957   }
2958
2959   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2960                                                SMLoc E) {
2961     auto Op = make_unique<ARMOperand>(k_Register);
2962     Op->Reg.RegNum = RegNum;
2963     Op->StartLoc = S;
2964     Op->EndLoc = E;
2965     return Op;
2966   }
2967
2968   static std::unique_ptr<ARMOperand>
2969   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2970                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2971                         SMLoc E) {
2972     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2973     Op->RegShiftedReg.ShiftTy = ShTy;
2974     Op->RegShiftedReg.SrcReg = SrcReg;
2975     Op->RegShiftedReg.ShiftReg = ShiftReg;
2976     Op->RegShiftedReg.ShiftImm = ShiftImm;
2977     Op->StartLoc = S;
2978     Op->EndLoc = E;
2979     return Op;
2980   }
2981
2982   static std::unique_ptr<ARMOperand>
2983   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2984                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2985     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2986     Op->RegShiftedImm.ShiftTy = ShTy;
2987     Op->RegShiftedImm.SrcReg = SrcReg;
2988     Op->RegShiftedImm.ShiftImm = ShiftImm;
2989     Op->StartLoc = S;
2990     Op->EndLoc = E;
2991     return Op;
2992   }
2993
2994   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2995                                                       SMLoc S, SMLoc E) {
2996     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2997     Op->ShifterImm.isASR = isASR;
2998     Op->ShifterImm.Imm = Imm;
2999     Op->StartLoc = S;
3000     Op->EndLoc = E;
3001     return Op;
3002   }
3003
3004   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3005                                                   SMLoc E) {
3006     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
3007     Op->RotImm.Imm = Imm;
3008     Op->StartLoc = S;
3009     Op->EndLoc = E;
3010     return Op;
3011   }
3012
3013   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3014                                                   SMLoc S, SMLoc E) {
3015     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
3016     Op->ModImm.Bits = Bits;
3017     Op->ModImm.Rot = Rot;
3018     Op->StartLoc = S;
3019     Op->EndLoc = E;
3020     return Op;
3021   }
3022
3023   static std::unique_ptr<ARMOperand>
3024   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3025     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
3026     Op->Imm.Val = Val;
3027     Op->StartLoc = S;
3028     Op->EndLoc = E;
3029     return Op;
3030   }
3031
3032   static std::unique_ptr<ARMOperand>
3033   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3034     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
3035     Op->Bitfield.LSB = LSB;
3036     Op->Bitfield.Width = Width;
3037     Op->StartLoc = S;
3038     Op->EndLoc = E;
3039     return Op;
3040   }
3041
3042   static std::unique_ptr<ARMOperand>
3043   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3044                 SMLoc StartLoc, SMLoc EndLoc) {
3045     assert(Regs.size() > 0 && "RegList contains no registers?");
3046     KindTy Kind = k_RegisterList;
3047
3048     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
3049       Kind = k_DPRRegisterList;
3050     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
3051              contains(Regs.front().second))
3052       Kind = k_SPRRegisterList;
3053
3054     // Sort based on the register encoding values.
3055     array_pod_sort(Regs.begin(), Regs.end());
3056
3057     auto Op = make_unique<ARMOperand>(Kind);
3058     for (SmallVectorImpl<std::pair<unsigned, unsigned>>::const_iterator
3059            I = Regs.begin(), E = Regs.end(); I != E; ++I)
3060       Op->Registers.push_back(I->second);
3061     Op->StartLoc = StartLoc;
3062     Op->EndLoc = EndLoc;
3063     return Op;
3064   }
3065
3066   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3067                                                       unsigned Count,
3068                                                       bool isDoubleSpaced,
3069                                                       SMLoc S, SMLoc E) {
3070     auto Op = make_unique<ARMOperand>(k_VectorList);
3071     Op->VectorList.RegNum = RegNum;
3072     Op->VectorList.Count = Count;
3073     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3074     Op->StartLoc = S;
3075     Op->EndLoc = E;
3076     return Op;
3077   }
3078
3079   static std::unique_ptr<ARMOperand>
3080   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3081                            SMLoc S, SMLoc E) {
3082     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
3083     Op->VectorList.RegNum = RegNum;
3084     Op->VectorList.Count = Count;
3085     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3086     Op->StartLoc = S;
3087     Op->EndLoc = E;
3088     return Op;
3089   }
3090
3091   static std::unique_ptr<ARMOperand>
3092   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3093                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3094     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
3095     Op->VectorList.RegNum = RegNum;
3096     Op->VectorList.Count = Count;
3097     Op->VectorList.LaneIndex = Index;
3098     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3099     Op->StartLoc = S;
3100     Op->EndLoc = E;
3101     return Op;
3102   }
3103
3104   static std::unique_ptr<ARMOperand>
3105   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3106     auto Op = make_unique<ARMOperand>(k_VectorIndex);
3107     Op->VectorIndex.Val = Idx;
3108     Op->StartLoc = S;
3109     Op->EndLoc = E;
3110     return Op;
3111   }
3112
3113   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3114                                                SMLoc E) {
3115     auto Op = make_unique<ARMOperand>(k_Immediate);
3116     Op->Imm.Val = Val;
3117     Op->StartLoc = S;
3118     Op->EndLoc = E;
3119     return Op;
3120   }
3121
3122   static std::unique_ptr<ARMOperand>
3123   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3124             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3125             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3126             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3127     auto Op = make_unique<ARMOperand>(k_Memory);
3128     Op->Memory.BaseRegNum = BaseRegNum;
3129     Op->Memory.OffsetImm = OffsetImm;
3130     Op->Memory.OffsetRegNum = OffsetRegNum;
3131     Op->Memory.ShiftType = ShiftType;
3132     Op->Memory.ShiftImm = ShiftImm;
3133     Op->Memory.Alignment = Alignment;
3134     Op->Memory.isNegative = isNegative;
3135     Op->StartLoc = S;
3136     Op->EndLoc = E;
3137     Op->AlignmentLoc = AlignmentLoc;
3138     return Op;
3139   }
3140
3141   static std::unique_ptr<ARMOperand>
3142   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3143                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3144     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
3145     Op->PostIdxReg.RegNum = RegNum;
3146     Op->PostIdxReg.isAdd = isAdd;
3147     Op->PostIdxReg.ShiftTy = ShiftTy;
3148     Op->PostIdxReg.ShiftImm = ShiftImm;
3149     Op->StartLoc = S;
3150     Op->EndLoc = E;
3151     return Op;
3152   }
3153
3154   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3155                                                          SMLoc S) {
3156     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
3157     Op->MBOpt.Val = Opt;
3158     Op->StartLoc = S;
3159     Op->EndLoc = S;
3160     return Op;
3161   }
3162
3163   static std::unique_ptr<ARMOperand>
3164   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3165     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3166     Op->ISBOpt.Val = Opt;
3167     Op->StartLoc = S;
3168     Op->EndLoc = S;
3169     return Op;
3170   }
3171
3172   static std::unique_ptr<ARMOperand>
3173   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3174     auto Op = make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3175     Op->TSBOpt.Val = Opt;
3176     Op->StartLoc = S;
3177     Op->EndLoc = S;
3178     return Op;
3179   }
3180
3181   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3182                                                       SMLoc S) {
3183     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
3184     Op->IFlags.Val = IFlags;
3185     Op->StartLoc = S;
3186     Op->EndLoc = S;
3187     return Op;
3188   }
3189
3190   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3191     auto Op = make_unique<ARMOperand>(k_MSRMask);
3192     Op->MMask.Val = MMask;
3193     Op->StartLoc = S;
3194     Op->EndLoc = S;
3195     return Op;
3196   }
3197
3198   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3199     auto Op = make_unique<ARMOperand>(k_BankedReg);
3200     Op->BankedReg.Val = Reg;
3201     Op->StartLoc = S;
3202     Op->EndLoc = S;
3203     return Op;
3204   }
3205 };
3206
3207 } // end anonymous namespace.
3208
3209 void ARMOperand::print(raw_ostream &OS) const {
3210   auto RegName = [](unsigned Reg) {
3211     if (Reg)
3212       return ARMInstPrinter::getRegisterName(Reg);
3213     else
3214       return "noreg";
3215   };
3216
3217   switch (Kind) {
3218   case k_CondCode:
3219     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3220     break;
3221   case k_CCOut:
3222     OS << "<ccout " << RegName(getReg()) << ">";
3223     break;
3224   case k_ITCondMask: {
3225     static const char *const MaskStr[] = {
3226       "(invalid)", "(teee)", "(tee)", "(teet)",
3227       "(te)",      "(tete)", "(tet)", "(tett)",
3228       "(t)",       "(ttee)", "(tte)", "(ttet)",
3229       "(tt)",      "(ttte)", "(ttt)", "(tttt)"
3230     };
3231     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3232     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3233     break;
3234   }
3235   case k_CoprocNum:
3236     OS << "<coprocessor number: " << getCoproc() << ">";
3237     break;
3238   case k_CoprocReg:
3239     OS << "<coprocessor register: " << getCoproc() << ">";
3240     break;
3241   case k_CoprocOption:
3242     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3243     break;
3244   case k_MSRMask:
3245     OS << "<mask: " << getMSRMask() << ">";
3246     break;
3247   case k_BankedReg:
3248     OS << "<banked reg: " << getBankedReg() << ">";
3249     break;
3250   case k_Immediate:
3251     OS << *getImm();
3252     break;
3253   case k_MemBarrierOpt:
3254     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3255     break;
3256   case k_InstSyncBarrierOpt:
3257     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3258     break;
3259   case k_TraceSyncBarrierOpt:
3260     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3261     break;
3262   case k_Memory:
3263     OS << "<memory";
3264     if (Memory.BaseRegNum)
3265       OS << " base:" << RegName(Memory.BaseRegNum);
3266     if (Memory.OffsetImm)
3267       OS << " offset-imm:" << *Memory.OffsetImm;
3268     if (Memory.OffsetRegNum)
3269       OS << " offset-reg:" << (Memory.isNegative ? "-" : "")
3270          << RegName(Memory.OffsetRegNum);
3271     if (Memory.ShiftType != ARM_AM::no_shift) {
3272       OS << " shift-type:" << ARM_AM::getShiftOpcStr(Memory.ShiftType);
3273       OS << " shift-imm:" << Memory.ShiftImm;
3274     }
3275     if (Memory.Alignment)
3276       OS << " alignment:" << Memory.Alignment;
3277     OS << ">";
3278     break;
3279   case k_PostIndexRegister:
3280     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3281        << RegName(PostIdxReg.RegNum);
3282     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3283       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3284          << PostIdxReg.ShiftImm;
3285     OS << ">";
3286     break;
3287   case k_ProcIFlags: {
3288     OS << "<ARM_PROC::";
3289     unsigned IFlags = getProcIFlags();
3290     for (int i=2; i >= 0; --i)
3291       if (IFlags & (1 << i))
3292         OS << ARM_PROC::IFlagsToString(1 << i);
3293     OS << ">";
3294     break;
3295   }
3296   case k_Register:
3297     OS << "<register " << RegName(getReg()) << ">";
3298     break;
3299   case k_ShifterImmediate:
3300     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3301        << " #" << ShifterImm.Imm << ">";
3302     break;
3303   case k_ShiftedRegister:
3304     OS << "<so_reg_reg " << RegName(RegShiftedReg.SrcReg) << " "
3305        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy) << " "
3306        << RegName(RegShiftedReg.ShiftReg) << ">";
3307     break;
3308   case k_ShiftedImmediate:
3309     OS << "<so_reg_imm " << RegName(RegShiftedImm.SrcReg) << " "
3310        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy) << " #"
3311        << RegShiftedImm.ShiftImm << ">";
3312     break;
3313   case k_RotateImmediate:
3314     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3315     break;
3316   case k_ModifiedImmediate:
3317     OS << "<mod_imm #" << ModImm.Bits << ", #"
3318        <<  ModImm.Rot << ")>";
3319     break;
3320   case k_ConstantPoolImmediate:
3321     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3322     break;
3323   case k_BitfieldDescriptor:
3324     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3325        << ", width: " << Bitfield.Width << ">";
3326     break;
3327   case k_RegisterList:
3328   case k_DPRRegisterList:
3329   case k_SPRRegisterList: {
3330     OS << "<register_list ";
3331
3332     const SmallVectorImpl<unsigned> &RegList = getRegList();
3333     for (SmallVectorImpl<unsigned>::const_iterator
3334            I = RegList.begin(), E = RegList.end(); I != E; ) {
3335       OS << RegName(*I);
3336       if (++I < E) OS << ", ";
3337     }
3338
3339     OS << ">";
3340     break;
3341   }
3342   case k_VectorList:
3343     OS << "<vector_list " << VectorList.Count << " * "
3344        << RegName(VectorList.RegNum) << ">";
3345     break;
3346   case k_VectorListAllLanes:
3347     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3348        << RegName(VectorList.RegNum) << ">";
3349     break;
3350   case k_VectorListIndexed:
3351     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3352        << VectorList.Count << " * " << RegName(VectorList.RegNum) << ">";
3353     break;
3354   case k_Token:
3355     OS << "'" << getToken() << "'";
3356     break;
3357   case k_VectorIndex:
3358     OS << "<vectorindex " << getVectorIndex() << ">";
3359     break;
3360   }
3361 }
3362
3363 /// @name Auto-generated Match Functions
3364 /// {
3365
3366 static unsigned MatchRegisterName(StringRef Name);
3367
3368 /// }
3369
3370 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3371                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3372   const AsmToken &Tok = getParser().getTok();
3373   StartLoc = Tok.getLoc();
3374   EndLoc = Tok.getEndLoc();
3375   RegNo = tryParseRegister();
3376
3377   return (RegNo == (unsigned)-1);
3378 }
3379
3380 /// Try to parse a register name.  The token must be an Identifier when called,
3381 /// and if it is a register name the token is eaten and the register number is
3382 /// returned.  Otherwise return -1.
3383 int ARMAsmParser::tryParseRegister() {
3384   MCAsmParser &Parser = getParser();
3385   const AsmToken &Tok = Parser.getTok();
3386   if (Tok.isNot(AsmToken::Identifier)) return -1;
3387
3388   std::string lowerCase = Tok.getString().lower();
3389   unsigned RegNum = MatchRegisterName(lowerCase);
3390   if (!RegNum) {
3391     RegNum = StringSwitch<unsigned>(lowerCase)
3392       .Case("r13", ARM::SP)
3393       .Case("r14", ARM::LR)
3394       .Case("r15", ARM::PC)
3395       .Case("ip", ARM::R12)
3396       // Additional register name aliases for 'gas' compatibility.
3397       .Case("a1", ARM::R0)
3398       .Case("a2", ARM::R1)
3399       .Case("a3", ARM::R2)
3400       .Case("a4", ARM::R3)
3401       .Case("v1", ARM::R4)
3402       .Case("v2", ARM::R5)
3403       .Case("v3", ARM::R6)
3404       .Case("v4", ARM::R7)
3405       .Case("v5", ARM::R8)
3406       .Case("v6", ARM::R9)
3407       .Case("v7", ARM::R10)
3408       .Case("v8", ARM::R11)
3409       .Case("sb", ARM::R9)
3410       .Case("sl", ARM::R10)
3411       .Case("fp", ARM::R11)
3412       .Default(0);
3413   }
3414   if (!RegNum) {
3415     // Check for aliases registered via .req. Canonicalize to lower case.
3416     // That's more consistent since register names are case insensitive, and
3417     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3418     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3419     // If no match, return failure.
3420     if (Entry == RegisterReqs.end())
3421       return -1;
3422     Parser.Lex(); // Eat identifier token.
3423     return Entry->getValue();
3424   }
3425
3426   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3427   if (!hasD32() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3428     return -1;
3429
3430   Parser.Lex(); // Eat identifier token.
3431
3432   return RegNum;
3433 }
3434
3435 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3436 // If a recoverable error occurs, return 1. If an irrecoverable error
3437 // occurs, return -1. An irrecoverable error is one where tokens have been
3438 // consumed in the process of trying to parse the shifter (i.e., when it is
3439 // indeed a shifter operand, but malformed).
3440 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3441   MCAsmParser &Parser = getParser();
3442   SMLoc S = Parser.getTok().getLoc();
3443   const AsmToken &Tok = Parser.getTok();
3444   if (Tok.isNot(AsmToken::Identifier))
3445     return -1;
3446
3447   std::string lowerCase = Tok.getString().lower();
3448   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3449       .Case("asl", ARM_AM::lsl)
3450       .Case("lsl", ARM_AM::lsl)
3451       .Case("lsr", ARM_AM::lsr)
3452       .Case("asr", ARM_AM::asr)
3453       .Case("ror", ARM_AM::ror)
3454       .Case("rrx", ARM_AM::rrx)
3455       .Default(ARM_AM::no_shift);
3456
3457   if (ShiftTy == ARM_AM::no_shift)
3458     return 1;
3459
3460   Parser.Lex(); // Eat the operator.
3461
3462   // The source register for the shift has already been added to the
3463   // operand list, so we need to pop it off and combine it into the shifted
3464   // register operand instead.
3465   std::unique_ptr<ARMOperand> PrevOp(
3466       (ARMOperand *)Operands.pop_back_val().release());
3467   if (!PrevOp->isReg())
3468     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3469   int SrcReg = PrevOp->getReg();
3470
3471   SMLoc EndLoc;
3472   int64_t Imm = 0;
3473   int ShiftReg = 0;
3474   if (ShiftTy == ARM_AM::rrx) {
3475     // RRX Doesn't have an explicit shift amount. The encoder expects
3476     // the shift register to be the same as the source register. Seems odd,
3477     // but OK.
3478     ShiftReg = SrcReg;
3479   } else {
3480     // Figure out if this is shifted by a constant or a register (for non-RRX).
3481     if (Parser.getTok().is(AsmToken::Hash) ||
3482         Parser.getTok().is(AsmToken::Dollar)) {
3483       Parser.Lex(); // Eat hash.
3484       SMLoc ImmLoc = Parser.getTok().getLoc();
3485       const MCExpr *ShiftExpr = nullptr;
3486       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3487         Error(ImmLoc, "invalid immediate shift value");
3488         return -1;
3489       }
3490       // The expression must be evaluatable as an immediate.
3491       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3492       if (!CE) {
3493         Error(ImmLoc, "invalid immediate shift value");
3494         return -1;
3495       }
3496       // Range check the immediate.
3497       // lsl, ror: 0 <= imm <= 31
3498       // lsr, asr: 0 <= imm <= 32
3499       Imm = CE->getValue();
3500       if (Imm < 0 ||
3501           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3502           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3503         Error(ImmLoc, "immediate shift value out of range");
3504         return -1;
3505       }
3506       // shift by zero is a nop. Always send it through as lsl.
3507       // ('as' compatibility)
3508       if (Imm == 0)
3509         ShiftTy = ARM_AM::lsl;
3510     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3511       SMLoc L = Parser.getTok().getLoc();
3512       EndLoc = Parser.getTok().getEndLoc();
3513       ShiftReg = tryParseRegister();
3514       if (ShiftReg == -1) {
3515         Error(L, "expected immediate or register in shift operand");
3516         return -1;
3517       }
3518     } else {
3519       Error(Parser.getTok().getLoc(),
3520             "expected immediate or register in shift operand");
3521       return -1;
3522     }
3523   }
3524
3525   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3526     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3527                                                          ShiftReg, Imm,
3528                                                          S, EndLoc));
3529   else
3530     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3531                                                           S, EndLoc));
3532
3533   return 0;
3534 }
3535
3536 /// Try to parse a register name.  The token must be an Identifier when called.
3537 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3538 /// if there is a "writeback". 'true' if it's not a register.
3539 ///
3540 /// TODO this is likely to change to allow different register types and or to
3541 /// parse for a specific register type.
3542 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3543   MCAsmParser &Parser = getParser();
3544   SMLoc RegStartLoc = Parser.getTok().getLoc();
3545   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
3546   int RegNo = tryParseRegister();
3547   if (RegNo == -1)
3548     return true;
3549
3550   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
3551
3552   const AsmToken &ExclaimTok = Parser.getTok();
3553   if (ExclaimTok.is(AsmToken::Exclaim)) {
3554     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3555                                                ExclaimTok.getLoc()));
3556     Parser.Lex(); // Eat exclaim token
3557     return false;
3558   }
3559
3560   // Also check for an index operand. This is only legal for vector registers,
3561   // but that'll get caught OK in operand matching, so we don't need to
3562   // explicitly filter everything else out here.
3563   if (Parser.getTok().is(AsmToken::LBrac)) {
3564     SMLoc SIdx = Parser.getTok().getLoc();
3565     Parser.Lex(); // Eat left bracket token.
3566
3567     const MCExpr *ImmVal;
3568     if (getParser().parseExpression(ImmVal))
3569       return true;
3570     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3571     if (!MCE)
3572       return TokError("immediate value expected for vector index");
3573
3574     if (Parser.getTok().isNot(AsmToken::RBrac))
3575       return Error(Parser.getTok().getLoc(), "']' expected");
3576
3577     SMLoc E = Parser.getTok().getEndLoc();
3578     Parser.Lex(); // Eat right bracket token.
3579
3580     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3581                                                      SIdx, E,
3582                                                      getContext()));
3583   }
3584
3585   return false;
3586 }
3587
3588 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3589 /// instruction with a symbolic operand name.
3590 /// We accept "crN" syntax for GAS compatibility.
3591 /// <operand-name> ::= <prefix><number>
3592 /// If CoprocOp is 'c', then:
3593 ///   <prefix> ::= c | cr
3594 /// If CoprocOp is 'p', then :
3595 ///   <prefix> ::= p
3596 /// <number> ::= integer in range [0, 15]
3597 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3598   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3599   // but efficient.
3600   if (Name.size() < 2 || Name[0] != CoprocOp)
3601     return -1;
3602   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3603
3604   switch (Name.size()) {
3605   default: return -1;
3606   case 1:
3607     switch (Name[0]) {
3608     default:  return -1;
3609     case '0': return 0;
3610     case '1': return 1;
3611     case '2': return 2;
3612     case '3': return 3;
3613     case '4': return 4;
3614     case '5': return 5;
3615     case '6': return 6;
3616     case '7': return 7;
3617     case '8': return 8;
3618     case '9': return 9;
3619     }
3620   case 2:
3621     if (Name[0] != '1')
3622       return -1;
3623     switch (Name[1]) {
3624     default:  return -1;
3625     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3626     // However, old cores (v5/v6) did use them in that way.
3627     case '0': return 10;
3628     case '1': return 11;
3629     case '2': return 12;
3630     case '3': return 13;
3631     case '4': return 14;
3632     case '5': return 15;
3633     }
3634   }
3635 }
3636
3637 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3638 OperandMatchResultTy
3639 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3640   MCAsmParser &Parser = getParser();
3641   SMLoc S = Parser.getTok().getLoc();
3642   const AsmToken &Tok = Parser.getTok();
3643   if (!Tok.is(AsmToken::Identifier))
3644     return MatchOperand_NoMatch;
3645   unsigned CC = ARMCondCodeFromString(Tok.getString());
3646   if (CC == ~0U)
3647     return MatchOperand_NoMatch;
3648   Parser.Lex(); // Eat the token.
3649
3650   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3651
3652   return MatchOperand_Success;
3653 }
3654
3655 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3656 /// token must be an Identifier when called, and if it is a coprocessor
3657 /// number, the token is eaten and the operand is added to the operand list.
3658 OperandMatchResultTy
3659 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3660   MCAsmParser &Parser = getParser();
3661   SMLoc S = Parser.getTok().getLoc();
3662   const AsmToken &Tok = Parser.getTok();
3663   if (Tok.isNot(AsmToken::Identifier))
3664     return MatchOperand_NoMatch;
3665
3666   int Num = MatchCoprocessorOperandName(Tok.getString().lower(), 'p');
3667   if (Num == -1)
3668     return MatchOperand_NoMatch;
3669   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3670   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3671     return MatchOperand_NoMatch;
3672
3673   Parser.Lex(); // Eat identifier token.
3674   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3675   return MatchOperand_Success;
3676 }
3677
3678 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3679 /// token must be an Identifier when called, and if it is a coprocessor
3680 /// number, the token is eaten and the operand is added to the operand list.
3681 OperandMatchResultTy
3682 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3683   MCAsmParser &Parser = getParser();
3684   SMLoc S = Parser.getTok().getLoc();
3685   const AsmToken &Tok = Parser.getTok();
3686   if (Tok.isNot(AsmToken::Identifier))
3687     return MatchOperand_NoMatch;
3688
3689   int Reg = MatchCoprocessorOperandName(Tok.getString().lower(), 'c');
3690   if (Reg == -1)
3691     return MatchOperand_NoMatch;
3692
3693   Parser.Lex(); // Eat identifier token.
3694   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3695   return MatchOperand_Success;
3696 }
3697
3698 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3699 /// coproc_option : '{' imm0_255 '}'
3700 OperandMatchResultTy
3701 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3702   MCAsmParser &Parser = getParser();
3703   SMLoc S = Parser.getTok().getLoc();
3704
3705   // If this isn't a '{', this isn't a coprocessor immediate operand.
3706   if (Parser.getTok().isNot(AsmToken::LCurly))
3707     return MatchOperand_NoMatch;
3708   Parser.Lex(); // Eat the '{'
3709
3710   const MCExpr *Expr;
3711   SMLoc Loc = Parser.getTok().getLoc();
3712   if (getParser().parseExpression(Expr)) {
3713     Error(Loc, "illegal expression");
3714     return MatchOperand_ParseFail;
3715   }
3716   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3717   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3718     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3719     return MatchOperand_ParseFail;
3720   }
3721   int Val = CE->getValue();
3722
3723   // Check for and consume the closing '}'
3724   if (Parser.getTok().isNot(AsmToken::RCurly))
3725     return MatchOperand_ParseFail;
3726   SMLoc E = Parser.getTok().getEndLoc();
3727   Parser.Lex(); // Eat the '}'
3728
3729   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3730   return MatchOperand_Success;
3731 }
3732
3733 // For register list parsing, we need to map from raw GPR register numbering
3734 // to the enumeration values. The enumeration values aren't sorted by
3735 // register number due to our using "sp", "lr" and "pc" as canonical names.
3736 static unsigned getNextRegister(unsigned Reg) {
3737   // If this is a GPR, we need to do it manually, otherwise we can rely
3738   // on the sort ordering of the enumeration since the other reg-classes
3739   // are sane.
3740   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3741     return Reg + 1;
3742   switch(Reg) {
3743   default: llvm_unreachable("Invalid GPR number!");
3744   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3745   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3746   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3747   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3748   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3749   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3750   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3751   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3752   }
3753 }
3754
3755 /// Parse a register list.
3756 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3757   MCAsmParser &Parser = getParser();
3758   if (Parser.getTok().isNot(AsmToken::LCurly))
3759     return TokError("Token is not a Left Curly Brace");
3760   SMLoc S = Parser.getTok().getLoc();
3761   Parser.Lex(); // Eat '{' token.
3762   SMLoc RegLoc = Parser.getTok().getLoc();
3763
3764   // Check the first register in the list to see what register class
3765   // this is a list of.
3766   int Reg = tryParseRegister();
3767   if (Reg == -1)
3768     return Error(RegLoc, "register expected");
3769
3770   // The reglist instructions have at most 16 registers, so reserve
3771   // space for that many.
3772   int EReg = 0;
3773   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3774
3775   // Allow Q regs and just interpret them as the two D sub-registers.
3776   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3777     Reg = getDRegFromQReg(Reg);
3778     EReg = MRI->getEncodingValue(Reg);
3779     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3780     ++Reg;
3781   }
3782   const MCRegisterClass *RC;
3783   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3784     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3785   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3786     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3787   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3788     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3789   else
3790     return Error(RegLoc, "invalid register in register list");
3791
3792   // Store the register.
3793   EReg = MRI->getEncodingValue(Reg);
3794   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3795
3796   // This starts immediately after the first register token in the list,
3797   // so we can see either a comma or a minus (range separator) as a legal
3798   // next token.
3799   while (Parser.getTok().is(AsmToken::Comma) ||
3800          Parser.getTok().is(AsmToken::Minus)) {
3801     if (Parser.getTok().is(AsmToken::Minus)) {
3802       Parser.Lex(); // Eat the minus.
3803       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3804       int EndReg = tryParseRegister();
3805       if (EndReg == -1)
3806         return Error(AfterMinusLoc, "register expected");
3807       // Allow Q regs and just interpret them as the two D sub-registers.
3808       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3809         EndReg = getDRegFromQReg(EndReg) + 1;
3810       // If the register is the same as the start reg, there's nothing
3811       // more to do.
3812       if (Reg == EndReg)
3813         continue;
3814       // The register must be in the same register class as the first.
3815       if (!RC->contains(EndReg))
3816         return Error(AfterMinusLoc, "invalid register in register list");
3817       // Ranges must go from low to high.
3818       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3819         return Error(AfterMinusLoc, "bad range in register list");
3820
3821       // Add all the registers in the range to the register list.
3822       while (Reg != EndReg) {
3823         Reg = getNextRegister(Reg);
3824         EReg = MRI->getEncodingValue(Reg);
3825         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3826       }
3827       continue;
3828     }
3829     Parser.Lex(); // Eat the comma.
3830     RegLoc = Parser.getTok().getLoc();
3831     int OldReg = Reg;
3832     const AsmToken RegTok = Parser.getTok();
3833     Reg = tryParseRegister();
3834     if (Reg == -1)
3835       return Error(RegLoc, "register expected");
3836     // Allow Q regs and just interpret them as the two D sub-registers.
3837     bool isQReg = false;
3838     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3839       Reg = getDRegFromQReg(Reg);
3840       isQReg = true;
3841     }
3842     // The register must be in the same register class as the first.
3843     if (!RC->contains(Reg))
3844       return Error(RegLoc, "invalid register in register list");
3845     // List must be monotonically increasing.
3846     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3847       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3848         Warning(RegLoc, "register list not in ascending order");
3849       else
3850         return Error(RegLoc, "register list not in ascending order");
3851     }
3852     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3853       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3854               ") in register list");
3855       continue;
3856     }
3857     // VFP register lists must also be contiguous.
3858     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3859         Reg != OldReg + 1)
3860       return Error(RegLoc, "non-contiguous register range");
3861     EReg = MRI->getEncodingValue(Reg);
3862     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3863     if (isQReg) {
3864       EReg = MRI->getEncodingValue(++Reg);
3865       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3866     }
3867   }
3868
3869   if (Parser.getTok().isNot(AsmToken::RCurly))
3870     return Error(Parser.getTok().getLoc(), "'}' expected");
3871   SMLoc E = Parser.getTok().getEndLoc();
3872   Parser.Lex(); // Eat '}' token.
3873
3874   // Push the register list operand.
3875   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3876
3877   // The ARM system instruction variants for LDM/STM have a '^' token here.
3878   if (Parser.getTok().is(AsmToken::Caret)) {
3879     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3880     Parser.Lex(); // Eat '^' token.
3881   }
3882
3883   return false;
3884 }
3885
3886 // Helper function to parse the lane index for vector lists.
3887 OperandMatchResultTy ARMAsmParser::
3888 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3889   MCAsmParser &Parser = getParser();
3890   Index = 0; // Always return a defined index value.
3891   if (Parser.getTok().is(AsmToken::LBrac)) {
3892     Parser.Lex(); // Eat the '['.
3893     if (Parser.getTok().is(AsmToken::RBrac)) {
3894       // "Dn[]" is the 'all lanes' syntax.
3895       LaneKind = AllLanes;
3896       EndLoc = Parser.getTok().getEndLoc();
3897       Parser.Lex(); // Eat the ']'.
3898       return MatchOperand_Success;
3899     }
3900
3901     // There's an optional '#' token here. Normally there wouldn't be, but
3902     // inline assemble puts one in, and it's friendly to accept that.
3903     if (Parser.getTok().is(AsmToken::Hash))
3904       Parser.Lex(); // Eat '#' or '$'.
3905
3906     const MCExpr *LaneIndex;
3907     SMLoc Loc = Parser.getTok().getLoc();
3908     if (getParser().parseExpression(LaneIndex)) {
3909       Error(Loc, "illegal expression");
3910       return MatchOperand_ParseFail;
3911     }
3912     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3913     if (!CE) {
3914       Error(Loc, "lane index must be empty or an integer");
3915       return MatchOperand_ParseFail;
3916     }
3917     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3918       Error(Parser.getTok().getLoc(), "']' expected");
3919       return MatchOperand_ParseFail;
3920     }
3921     EndLoc = Parser.getTok().getEndLoc();
3922     Parser.Lex(); // Eat the ']'.
3923     int64_t Val = CE->getValue();
3924
3925     // FIXME: Make this range check context sensitive for .8, .16, .32.
3926     if (Val < 0 || Val > 7) {
3927       Error(Parser.getTok().getLoc(), "lane index out of range");
3928       return MatchOperand_ParseFail;
3929     }
3930     Index = Val;
3931     LaneKind = IndexedLane;
3932     return MatchOperand_Success;
3933   }
3934   LaneKind = NoLanes;
3935   return MatchOperand_Success;
3936 }
3937
3938 // parse a vector register list
3939 OperandMatchResultTy
3940 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3941   MCAsmParser &Parser = getParser();
3942   VectorLaneTy LaneKind;
3943   unsigned LaneIndex;
3944   SMLoc S = Parser.getTok().getLoc();
3945   // As an extension (to match gas), support a plain D register or Q register
3946   // (without encosing curly braces) as a single or double entry list,
3947   // respectively.
3948   if (Parser.getTok().is(AsmToken::Identifier)) {
3949     SMLoc E = Parser.getTok().getEndLoc();
3950     int Reg = tryParseRegister();
3951     if (Reg == -1)
3952       return MatchOperand_NoMatch;
3953     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3954       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3955       if (Res != MatchOperand_Success)
3956         return Res;
3957       switch (LaneKind) {
3958       case NoLanes:
3959         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3960         break;
3961       case AllLanes:
3962         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3963                                                                 S, E));
3964         break;
3965       case IndexedLane:
3966         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3967                                                                LaneIndex,
3968                                                                false, S, E));
3969         break;
3970       }
3971       return MatchOperand_Success;
3972     }
3973     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3974       Reg = getDRegFromQReg(Reg);
3975       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3976       if (Res != MatchOperand_Success)
3977         return Res;
3978       switch (LaneKind) {
3979       case NoLanes:
3980         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3981                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3982         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3983         break;
3984       case AllLanes:
3985         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3986                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3987         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3988                                                                 S, E));
3989         break;
3990       case IndexedLane:
3991         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3992                                                                LaneIndex,
3993                                                                false, S, E));
3994         break;
3995       }
3996       return MatchOperand_Success;
3997     }
3998     Error(S, "vector register expected");
3999     return MatchOperand_ParseFail;
4000   }
4001
4002   if (Parser.getTok().isNot(AsmToken::LCurly))
4003     return MatchOperand_NoMatch;
4004
4005   Parser.Lex(); // Eat '{' token.
4006   SMLoc RegLoc = Parser.getTok().getLoc();
4007
4008   int Reg = tryParseRegister();
4009   if (Reg == -1) {
4010     Error(RegLoc, "register expected");
4011     return MatchOperand_ParseFail;
4012   }
4013   unsigned Count = 1;
4014   int Spacing = 0;
4015   unsigned FirstReg = Reg;
4016   // The list is of D registers, but we also allow Q regs and just interpret
4017   // them as the two D sub-registers.
4018   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4019     FirstReg = Reg = getDRegFromQReg(Reg);
4020     Spacing = 1; // double-spacing requires explicit D registers, otherwise
4021                  // it's ambiguous with four-register single spaced.
4022     ++Reg;
4023     ++Count;
4024   }
4025
4026   SMLoc E;
4027   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4028     return MatchOperand_ParseFail;
4029
4030   while (Parser.getTok().is(AsmToken::Comma) ||
4031          Parser.getTok().is(AsmToken::Minus)) {
4032     if (Parser.getTok().is(AsmToken::Minus)) {
4033       if (!Spacing)
4034         Spacing = 1; // Register range implies a single spaced list.
4035       else if (Spacing == 2) {
4036         Error(Parser.getTok().getLoc(),
4037               "sequential registers in double spaced list");
4038         return MatchOperand_ParseFail;
4039       }
4040       Parser.Lex(); // Eat the minus.
4041       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4042       int EndReg = tryParseRegister();
4043       if (EndReg == -1) {
4044         Error(AfterMinusLoc, "register expected");
4045         return MatchOperand_ParseFail;
4046       }
4047       // Allow Q regs and just interpret them as the two D sub-registers.
4048       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4049         EndReg = getDRegFromQReg(EndReg) + 1;
4050       // If the register is the same as the start reg, there's nothing
4051       // more to do.
4052       if (Reg == EndReg)
4053         continue;
4054       // The register must be in the same register class as the first.
4055       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
4056         Error(AfterMinusLoc, "invalid register in register list");
4057         return MatchOperand_ParseFail;
4058       }
4059       // Ranges must go from low to high.
4060       if (Reg > EndReg) {
4061         Error(AfterMinusLoc, "bad range in register list");
4062         return MatchOperand_ParseFail;
4063       }
4064       // Parse the lane specifier if present.
4065       VectorLaneTy NextLaneKind;
4066       unsigned NextLaneIndex;
4067       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4068           MatchOperand_Success)
4069         return MatchOperand_ParseFail;
4070       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4071         Error(AfterMinusLoc, "mismatched lane index in register list");
4072         return MatchOperand_ParseFail;
4073       }
4074
4075       // Add all the registers in the range to the register list.
4076       Count += EndReg - Reg;
4077       Reg = EndReg;
4078       continue;
4079     }
4080     Parser.Lex(); // Eat the comma.
4081     RegLoc = Parser.getTok().getLoc();
4082     int OldReg = Reg;
4083     Reg = tryParseRegister();
4084     if (Reg == -1) {
4085       Error(RegLoc, "register expected");
4086       return MatchOperand_ParseFail;
4087     }
4088     // vector register lists must be contiguous.
4089     // It's OK to use the enumeration values directly here rather, as the
4090     // VFP register classes have the enum sorted properly.
4091     //
4092     // The list is of D registers, but we also allow Q regs and just interpret
4093     // them as the two D sub-registers.
4094     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4095       if (!Spacing)
4096         Spacing = 1; // Register range implies a single spaced list.
4097       else if (Spacing == 2) {
4098         Error(RegLoc,
4099               "invalid register in double-spaced list (must be 'D' register')");
4100         return MatchOperand_ParseFail;
4101       }
4102       Reg = getDRegFromQReg(Reg);
4103       if (Reg != OldReg + 1) {
4104         Error(RegLoc, "non-contiguous register range");
4105         return MatchOperand_ParseFail;
4106       }
4107       ++Reg;
4108       Count += 2;
4109       // Parse the lane specifier if present.
4110       VectorLaneTy NextLaneKind;
4111       unsigned NextLaneIndex;
4112       SMLoc LaneLoc = Parser.getTok().getLoc();
4113       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4114           MatchOperand_Success)
4115         return MatchOperand_ParseFail;
4116       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4117         Error(LaneLoc, "mismatched lane index in register list");
4118         return MatchOperand_ParseFail;
4119       }
4120       continue;
4121     }
4122     // Normal D register.
4123     // Figure out the register spacing (single or double) of the list if
4124     // we don't know it already.
4125     if (!Spacing)
4126       Spacing = 1 + (Reg == OldReg + 2);
4127
4128     // Just check that it's contiguous and keep going.
4129     if (Reg != OldReg + Spacing) {
4130       Error(RegLoc, "non-contiguous register range");
4131       return MatchOperand_ParseFail;
4132     }
4133     ++Count;
4134     // Parse the lane specifier if present.
4135     VectorLaneTy NextLaneKind;
4136     unsigned NextLaneIndex;
4137     SMLoc EndLoc = Parser.getTok().getLoc();
4138     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4139       return MatchOperand_ParseFail;
4140     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4141       Error(EndLoc, "mismatched lane index in register list");
4142       return MatchOperand_ParseFail;
4143     }
4144   }
4145
4146   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4147     Error(Parser.getTok().getLoc(), "'}' expected");
4148     return MatchOperand_ParseFail;
4149   }
4150   E = Parser.getTok().getEndLoc();
4151   Parser.Lex(); // Eat '}' token.
4152
4153   switch (LaneKind) {
4154   case NoLanes:
4155     // Two-register operands have been converted to the
4156     // composite register classes.
4157     if (Count == 2) {
4158       const MCRegisterClass *RC = (Spacing == 1) ?
4159         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4160         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4161       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4162     }
4163     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
4164                                                     (Spacing == 2), S, E));
4165     break;
4166   case AllLanes:
4167     // Two-register operands have been converted to the
4168     // composite register classes.
4169     if (Count == 2) {
4170       const MCRegisterClass *RC = (Spacing == 1) ?
4171         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4172         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4173       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4174     }
4175     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
4176                                                             (Spacing == 2),
4177                                                             S, E));
4178     break;
4179   case IndexedLane:
4180     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4181                                                            LaneIndex,
4182                                                            (Spacing == 2),
4183                                                            S, E));
4184     break;
4185   }
4186   return MatchOperand_Success;
4187 }
4188
4189 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4190 OperandMatchResultTy
4191 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4192   MCAsmParser &Parser = getParser();
4193   SMLoc S = Parser.getTok().getLoc();
4194   const AsmToken &Tok = Parser.getTok();
4195   unsigned Opt;
4196
4197   if (Tok.is(AsmToken::Identifier)) {
4198     StringRef OptStr = Tok.getString();
4199
4200     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4201       .Case("sy",    ARM_MB::SY)
4202       .Case("st",    ARM_MB::ST)
4203       .Case("ld",    ARM_MB::LD)
4204       .Case("sh",    ARM_MB::ISH)
4205       .Case("ish",   ARM_MB::ISH)
4206       .Case("shst",  ARM_MB::ISHST)
4207       .Case("ishst", ARM_MB::ISHST)
4208       .Case("ishld", ARM_MB::ISHLD)
4209       .Case("nsh",   ARM_MB::NSH)
4210       .Case("un",    ARM_MB::NSH)
4211       .Case("nshst", ARM_MB::NSHST)
4212       .Case("nshld", ARM_MB::NSHLD)
4213       .Case("unst",  ARM_MB::NSHST)
4214       .Case("osh",   ARM_MB::OSH)
4215       .Case("oshst", ARM_MB::OSHST)
4216       .Case("oshld", ARM_MB::OSHLD)
4217       .Default(~0U);
4218
4219     // ishld, oshld, nshld and ld are only available from ARMv8.
4220     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4221                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4222       Opt = ~0U;
4223
4224     if (Opt == ~0U)
4225       return MatchOperand_NoMatch;
4226
4227     Parser.Lex(); // Eat identifier token.
4228   } else if (Tok.is(AsmToken::Hash) ||
4229              Tok.is(AsmToken::Dollar) ||
4230              Tok.is(AsmToken::Integer)) {
4231     if (Parser.getTok().isNot(AsmToken::Integer))
4232       Parser.Lex(); // Eat '#' or '$'.
4233     SMLoc Loc = Parser.getTok().getLoc();
4234
4235     const MCExpr *MemBarrierID;
4236     if (getParser().parseExpression(MemBarrierID)) {
4237       Error(Loc, "illegal expression");
4238       return MatchOperand_ParseFail;
4239     }
4240
4241     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4242     if (!CE) {
4243       Error(Loc, "constant expression expected");
4244       return MatchOperand_ParseFail;
4245     }
4246
4247     int Val = CE->getValue();
4248     if (Val & ~0xf) {
4249       Error(Loc, "immediate value out of range");
4250       return MatchOperand_ParseFail;
4251     }
4252
4253     Opt = ARM_MB::RESERVED_0 + Val;
4254   } else
4255     return MatchOperand_ParseFail;
4256
4257   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4258   return MatchOperand_Success;
4259 }
4260
4261 OperandMatchResultTy
4262 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
4263   MCAsmParser &Parser = getParser();
4264   SMLoc S = Parser.getTok().getLoc();
4265   const AsmToken &Tok = Parser.getTok();
4266
4267   if (Tok.isNot(AsmToken::Identifier))
4268      return MatchOperand_NoMatch;
4269
4270   if (!Tok.getString().equals_lower("csync"))
4271     return MatchOperand_NoMatch;
4272
4273   Parser.Lex(); // Eat identifier token.
4274
4275   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
4276   return MatchOperand_Success;
4277 }
4278
4279 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4280 OperandMatchResultTy
4281 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4282   MCAsmParser &Parser = getParser();
4283   SMLoc S = Parser.getTok().getLoc();
4284   const AsmToken &Tok = Parser.getTok();
4285   unsigned Opt;
4286
4287   if (Tok.is(AsmToken::Identifier)) {
4288     StringRef OptStr = Tok.getString();
4289
4290     if (OptStr.equals_lower("sy"))
4291       Opt = ARM_ISB::SY;
4292     else
4293       return MatchOperand_NoMatch;
4294
4295     Parser.Lex(); // Eat identifier token.
4296   } else if (Tok.is(AsmToken::Hash) ||
4297              Tok.is(AsmToken::Dollar) ||
4298              Tok.is(AsmToken::Integer)) {
4299     if (Parser.getTok().isNot(AsmToken::Integer))
4300       Parser.Lex(); // Eat '#' or '$'.
4301     SMLoc Loc = Parser.getTok().getLoc();
4302
4303     const MCExpr *ISBarrierID;
4304     if (getParser().parseExpression(ISBarrierID)) {
4305       Error(Loc, "illegal expression");
4306       return MatchOperand_ParseFail;
4307     }
4308
4309     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4310     if (!CE) {
4311       Error(Loc, "constant expression expected");
4312       return MatchOperand_ParseFail;
4313     }
4314
4315     int Val = CE->getValue();
4316     if (Val & ~0xf) {
4317       Error(Loc, "immediate value out of range");
4318       return MatchOperand_ParseFail;
4319     }
4320
4321     Opt = ARM_ISB::RESERVED_0 + Val;
4322   } else
4323     return MatchOperand_ParseFail;
4324
4325   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4326           (ARM_ISB::InstSyncBOpt)Opt, S));
4327   return MatchOperand_Success;
4328 }
4329
4330
4331 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4332 OperandMatchResultTy
4333 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4334   MCAsmParser &Parser = getParser();
4335   SMLoc S = Parser.getTok().getLoc();
4336   const AsmToken &Tok = Parser.getTok();
4337   if (!Tok.is(AsmToken::Identifier))
4338     return MatchOperand_NoMatch;
4339   StringRef IFlagsStr = Tok.getString();
4340
4341   // An iflags string of "none" is interpreted to mean that none of the AIF
4342   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4343   unsigned IFlags = 0;
4344   if (IFlagsStr != "none") {
4345         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4346       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4347         .Case("a", ARM_PROC::A)
4348         .Case("i", ARM_PROC::I)
4349         .Case("f", ARM_PROC::F)
4350         .Default(~0U);
4351
4352       // If some specific iflag is already set, it means that some letter is
4353       // present more than once, this is not acceptable.
4354       if (Flag == ~0U || (IFlags & Flag))
4355         return MatchOperand_NoMatch;
4356
4357       IFlags |= Flag;
4358     }
4359   }
4360
4361   Parser.Lex(); // Eat identifier token.
4362   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4363   return MatchOperand_Success;
4364 }
4365
4366 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4367 OperandMatchResultTy
4368 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4369   MCAsmParser &Parser = getParser();
4370   SMLoc S = Parser.getTok().getLoc();
4371   const AsmToken &Tok = Parser.getTok();
4372
4373   if (Tok.is(AsmToken::Integer)) {
4374     int64_t Val = Tok.getIntVal();
4375     if (Val > 255 || Val < 0) {
4376       return MatchOperand_NoMatch;
4377     }
4378     unsigned SYSmvalue = Val & 0xFF;
4379     Parser.Lex();
4380     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4381     return MatchOperand_Success;
4382   }
4383
4384   if (!Tok.is(AsmToken::Identifier))
4385     return MatchOperand_NoMatch;
4386   StringRef Mask = Tok.getString();
4387
4388   if (isMClass()) {
4389     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4390     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4391       return MatchOperand_NoMatch;
4392
4393     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4394
4395     Parser.Lex(); // Eat identifier token.
4396     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4397     return MatchOperand_Success;
4398   }
4399
4400   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4401   size_t Start = 0, Next = Mask.find('_');
4402   StringRef Flags = "";
4403   std::string SpecReg = Mask.slice(Start, Next).lower();
4404   if (Next != StringRef::npos)
4405     Flags = Mask.slice(Next+1, Mask.size());
4406
4407   // FlagsVal contains the complete mask:
4408   // 3-0: Mask
4409   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4410   unsigned FlagsVal = 0;
4411
4412   if (SpecReg == "apsr") {
4413     FlagsVal = StringSwitch<unsigned>(Flags)
4414     .Case("nzcvq",  0x8) // same as CPSR_f
4415     .Case("g",      0x4) // same as CPSR_s
4416     .Case("nzcvqg", 0xc) // same as CPSR_fs
4417     .Default(~0U);
4418
4419     if (FlagsVal == ~0U) {
4420       if (!Flags.empty())
4421         return MatchOperand_NoMatch;
4422       else
4423         FlagsVal = 8; // No flag
4424     }
4425   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4426     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4427     if (Flags == "all" || Flags == "")
4428       Flags = "fc";
4429     for (int i = 0, e = Flags.size(); i != e; ++i) {
4430       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4431       .Case("c", 1)
4432       .Case("x", 2)
4433       .Case("s", 4)
4434       .Case("f", 8)
4435       .Default(~0U);
4436
4437       // If some specific flag is already set, it means that some letter is
4438       // present more than once, this is not acceptable.
4439       if (Flag == ~0U || (FlagsVal & Flag))
4440         return MatchOperand_NoMatch;
4441       FlagsVal |= Flag;
4442     }
4443   } else // No match for special register.
4444     return MatchOperand_NoMatch;
4445
4446   // Special register without flags is NOT equivalent to "fc" flags.
4447   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4448   // two lines would enable gas compatibility at the expense of breaking
4449   // round-tripping.
4450   //
4451   // if (!FlagsVal)
4452   //  FlagsVal = 0x9;
4453
4454   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4455   if (SpecReg == "spsr")
4456     FlagsVal |= 16;
4457
4458   Parser.Lex(); // Eat identifier token.
4459   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4460   return MatchOperand_Success;
4461 }
4462
4463 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4464 /// use in the MRS/MSR instructions added to support virtualization.
4465 OperandMatchResultTy
4466 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4467   MCAsmParser &Parser = getParser();
4468   SMLoc S = Parser.getTok().getLoc();
4469   const AsmToken &Tok = Parser.getTok();
4470   if (!Tok.is(AsmToken::Identifier))
4471     return MatchOperand_NoMatch;
4472   StringRef RegName = Tok.getString();
4473
4474   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
4475   if (!TheReg)
4476     return MatchOperand_NoMatch;
4477   unsigned Encoding = TheReg->Encoding;
4478
4479   Parser.Lex(); // Eat identifier token.
4480   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4481   return MatchOperand_Success;
4482 }
4483
4484 OperandMatchResultTy
4485 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4486                           int High) {
4487   MCAsmParser &Parser = getParser();
4488   const AsmToken &Tok = Parser.getTok();
4489   if (Tok.isNot(AsmToken::Identifier)) {
4490     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4491     return MatchOperand_ParseFail;
4492   }
4493   StringRef ShiftName = Tok.getString();
4494   std::string LowerOp = Op.lower();
4495   std::string UpperOp = Op.upper();
4496   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4497     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4498     return MatchOperand_ParseFail;
4499   }
4500   Parser.Lex(); // Eat shift type token.
4501
4502   // There must be a '#' and a shift amount.
4503   if (Parser.getTok().isNot(AsmToken::Hash) &&
4504       Parser.getTok().isNot(AsmToken::Dollar)) {
4505     Error(Parser.getTok().getLoc(), "'#' expected");
4506     return MatchOperand_ParseFail;
4507   }
4508   Parser.Lex(); // Eat hash token.
4509
4510   const MCExpr *ShiftAmount;
4511   SMLoc Loc = Parser.getTok().getLoc();
4512   SMLoc EndLoc;
4513   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4514     Error(Loc, "illegal expression");
4515     return MatchOperand_ParseFail;
4516   }
4517   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4518   if (!CE) {
4519     Error(Loc, "constant expression expected");
4520     return MatchOperand_ParseFail;
4521   }
4522   int Val = CE->getValue();
4523   if (Val < Low || Val > High) {
4524     Error(Loc, "immediate value out of range");
4525     return MatchOperand_ParseFail;
4526   }
4527
4528   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4529
4530   return MatchOperand_Success;
4531 }
4532
4533 OperandMatchResultTy
4534 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4535   MCAsmParser &Parser = getParser();
4536   const AsmToken &Tok = Parser.getTok();
4537   SMLoc S = Tok.getLoc();
4538   if (Tok.isNot(AsmToken::Identifier)) {
4539     Error(S, "'be' or 'le' operand expected");
4540     return MatchOperand_ParseFail;
4541   }
4542   int Val = StringSwitch<int>(Tok.getString().lower())
4543     .Case("be", 1)
4544     .Case("le", 0)
4545     .Default(-1);
4546   Parser.Lex(); // Eat the token.
4547
4548   if (Val == -1) {
4549     Error(S, "'be' or 'le' operand expected");
4550     return MatchOperand_ParseFail;
4551   }
4552   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4553                                                                   getContext()),
4554                                            S, Tok.getEndLoc()));
4555   return MatchOperand_Success;
4556 }
4557
4558 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4559 /// instructions. Legal values are:
4560 ///     lsl #n  'n' in [0,31]
4561 ///     asr #n  'n' in [1,32]
4562 ///             n == 32 encoded as n == 0.
4563 OperandMatchResultTy
4564 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4565   MCAsmParser &Parser = getParser();
4566   const AsmToken &Tok = Parser.getTok();
4567   SMLoc S = Tok.getLoc();
4568   if (Tok.isNot(AsmToken::Identifier)) {
4569     Error(S, "shift operator 'asr' or 'lsl' expected");
4570     return MatchOperand_ParseFail;
4571   }
4572   StringRef ShiftName = Tok.getString();
4573   bool isASR;
4574   if (ShiftName == "lsl" || ShiftName == "LSL")
4575     isASR = false;
4576   else if (ShiftName == "asr" || ShiftName == "ASR")
4577     isASR = true;
4578   else {
4579     Error(S, "shift operator 'asr' or 'lsl' expected");
4580     return MatchOperand_ParseFail;
4581   }
4582   Parser.Lex(); // Eat the operator.
4583
4584   // A '#' and a shift amount.
4585   if (Parser.getTok().isNot(AsmToken::Hash) &&
4586       Parser.getTok().isNot(AsmToken::Dollar)) {
4587     Error(Parser.getTok().getLoc(), "'#' expected");
4588     return MatchOperand_ParseFail;
4589   }
4590   Parser.Lex(); // Eat hash token.
4591   SMLoc ExLoc = Parser.getTok().getLoc();
4592
4593   const MCExpr *ShiftAmount;
4594   SMLoc EndLoc;
4595   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4596     Error(ExLoc, "malformed shift expression");
4597     return MatchOperand_ParseFail;
4598   }
4599   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4600   if (!CE) {
4601     Error(ExLoc, "shift amount must be an immediate");
4602     return MatchOperand_ParseFail;
4603   }
4604
4605   int64_t Val = CE->getValue();
4606   if (isASR) {
4607     // Shift amount must be in [1,32]
4608     if (Val < 1 || Val > 32) {
4609       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4610       return MatchOperand_ParseFail;
4611     }
4612     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4613     if (isThumb() && Val == 32) {
4614       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4615       return MatchOperand_ParseFail;
4616     }
4617     if (Val == 32) Val = 0;
4618   } else {
4619     // Shift amount must be in [1,32]
4620     if (Val < 0 || Val > 31) {
4621       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4622       return MatchOperand_ParseFail;
4623     }
4624   }
4625
4626   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4627
4628   return MatchOperand_Success;
4629 }
4630
4631 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4632 /// of instructions. Legal values are:
4633 ///     ror #n  'n' in {0, 8, 16, 24}
4634 OperandMatchResultTy
4635 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4636   MCAsmParser &Parser = getParser();
4637   const AsmToken &Tok = Parser.getTok();
4638   SMLoc S = Tok.getLoc();
4639   if (Tok.isNot(AsmToken::Identifier))
4640     return MatchOperand_NoMatch;
4641   StringRef ShiftName = Tok.getString();
4642   if (ShiftName != "ror" && ShiftName != "ROR")
4643     return MatchOperand_NoMatch;
4644   Parser.Lex(); // Eat the operator.
4645
4646   // A '#' and a rotate amount.
4647   if (Parser.getTok().isNot(AsmToken::Hash) &&
4648       Parser.getTok().isNot(AsmToken::Dollar)) {
4649     Error(Parser.getTok().getLoc(), "'#' expected");
4650     return MatchOperand_ParseFail;
4651   }
4652   Parser.Lex(); // Eat hash token.
4653   SMLoc ExLoc = Parser.getTok().getLoc();
4654
4655   const MCExpr *ShiftAmount;
4656   SMLoc EndLoc;
4657   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4658     Error(ExLoc, "malformed rotate expression");
4659     return MatchOperand_ParseFail;
4660   }
4661   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4662   if (!CE) {
4663     Error(ExLoc, "rotate amount must be an immediate");
4664     return MatchOperand_ParseFail;
4665   }
4666
4667   int64_t Val = CE->getValue();
4668   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4669   // normally, zero is represented in asm by omitting the rotate operand
4670   // entirely.
4671   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4672     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4673     return MatchOperand_ParseFail;
4674   }
4675
4676   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4677
4678   return MatchOperand_Success;
4679 }
4680
4681 OperandMatchResultTy
4682 ARMAsmParser::parseModImm(OperandVector &Operands) {
4683   MCAsmParser &Parser = getParser();
4684   MCAsmLexer &Lexer = getLexer();
4685   int64_t Imm1, Imm2;
4686
4687   SMLoc S = Parser.getTok().getLoc();
4688
4689   // 1) A mod_imm operand can appear in the place of a register name:
4690   //   add r0, #mod_imm
4691   //   add r0, r0, #mod_imm
4692   // to correctly handle the latter, we bail out as soon as we see an
4693   // identifier.
4694   //
4695   // 2) Similarly, we do not want to parse into complex operands:
4696   //   mov r0, #mod_imm
4697   //   mov r0, :lower16:(_foo)
4698   if (Parser.getTok().is(AsmToken::Identifier) ||
4699       Parser.getTok().is(AsmToken::Colon))
4700     return MatchOperand_NoMatch;
4701
4702   // Hash (dollar) is optional as per the ARMARM
4703   if (Parser.getTok().is(AsmToken::Hash) ||
4704       Parser.getTok().is(AsmToken::Dollar)) {
4705     // Avoid parsing into complex operands (#:)
4706     if (Lexer.peekTok().is(AsmToken::Colon))
4707       return MatchOperand_NoMatch;
4708
4709     // Eat the hash (dollar)
4710     Parser.Lex();
4711   }
4712
4713   SMLoc Sx1, Ex1;
4714   Sx1 = Parser.getTok().getLoc();
4715   const MCExpr *Imm1Exp;
4716   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4717     Error(Sx1, "malformed expression");
4718     return MatchOperand_ParseFail;
4719   }
4720
4721   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4722
4723   if (CE) {
4724     // Immediate must fit within 32-bits
4725     Imm1 = CE->getValue();
4726     int Enc = ARM_AM::getSOImmVal(Imm1);
4727     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4728       // We have a match!
4729       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4730                                                   (Enc & 0xF00) >> 7,
4731                                                   Sx1, Ex1));
4732       return MatchOperand_Success;
4733     }
4734
4735     // We have parsed an immediate which is not for us, fallback to a plain
4736     // immediate. This can happen for instruction aliases. For an example,
4737     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4738     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4739     // instruction with a mod_imm operand. The alias is defined such that the
4740     // parser method is shared, that's why we have to do this here.
4741     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4742       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4743       return MatchOperand_Success;
4744     }
4745   } else {
4746     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4747     // MCFixup). Fallback to a plain immediate.
4748     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4749     return MatchOperand_Success;
4750   }
4751
4752   // From this point onward, we expect the input to be a (#bits, #rot) pair
4753   if (Parser.getTok().isNot(AsmToken::Comma)) {
4754     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4755     return MatchOperand_ParseFail;
4756   }
4757
4758   if (Imm1 & ~0xFF) {
4759     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4760     return MatchOperand_ParseFail;
4761   }
4762
4763   // Eat the comma
4764   Parser.Lex();
4765
4766   // Repeat for #rot
4767   SMLoc Sx2, Ex2;
4768   Sx2 = Parser.getTok().getLoc();
4769
4770   // Eat the optional hash (dollar)
4771   if (Parser.getTok().is(AsmToken::Hash) ||
4772       Parser.getTok().is(AsmToken::Dollar))
4773     Parser.Lex();
4774
4775   const MCExpr *Imm2Exp;
4776   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4777     Error(Sx2, "malformed expression");
4778     return MatchOperand_ParseFail;
4779   }
4780
4781   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4782
4783   if (CE) {
4784     Imm2 = CE->getValue();
4785     if (!(Imm2 & ~0x1E)) {
4786       // We have a match!
4787       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4788       return MatchOperand_Success;
4789     }
4790     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4791     return MatchOperand_ParseFail;
4792   } else {
4793     Error(Sx2, "constant expression expected");
4794     return MatchOperand_ParseFail;
4795   }
4796 }
4797
4798 OperandMatchResultTy
4799 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4800   MCAsmParser &Parser = getParser();
4801   SMLoc S = Parser.getTok().getLoc();
4802   // The bitfield descriptor is really two operands, the LSB and the width.
4803   if (Parser.getTok().isNot(AsmToken::Hash) &&
4804       Parser.getTok().isNot(AsmToken::Dollar)) {
4805     Error(Parser.getTok().getLoc(), "'#' expected");
4806     return MatchOperand_ParseFail;
4807   }
4808   Parser.Lex(); // Eat hash token.
4809
4810   const MCExpr *LSBExpr;
4811   SMLoc E = Parser.getTok().getLoc();
4812   if (getParser().parseExpression(LSBExpr)) {
4813     Error(E, "malformed immediate expression");
4814     return MatchOperand_ParseFail;
4815   }
4816   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4817   if (!CE) {
4818     Error(E, "'lsb' operand must be an immediate");
4819     return MatchOperand_ParseFail;
4820   }
4821
4822   int64_t LSB = CE->getValue();
4823   // The LSB must be in the range [0,31]
4824   if (LSB < 0 || LSB > 31) {
4825     Error(E, "'lsb' operand must be in the range [0,31]");
4826     return MatchOperand_ParseFail;
4827   }
4828   E = Parser.getTok().getLoc();
4829
4830   // Expect another immediate operand.
4831   if (Parser.getTok().isNot(AsmToken::Comma)) {
4832     Error(Parser.getTok().getLoc(), "too few operands");
4833     return MatchOperand_ParseFail;
4834   }
4835   Parser.Lex(); // Eat hash token.
4836   if (Parser.getTok().isNot(AsmToken::Hash) &&
4837       Parser.getTok().isNot(AsmToken::Dollar)) {
4838     Error(Parser.getTok().getLoc(), "'#' expected");
4839     return MatchOperand_ParseFail;
4840   }
4841   Parser.Lex(); // Eat hash token.
4842
4843   const MCExpr *WidthExpr;
4844   SMLoc EndLoc;
4845   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4846     Error(E, "malformed immediate expression");
4847     return MatchOperand_ParseFail;
4848   }
4849   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4850   if (!CE) {
4851     Error(E, "'width' operand must be an immediate");
4852     return MatchOperand_ParseFail;
4853   }
4854
4855   int64_t Width = CE->getValue();
4856   // The LSB must be in the range [1,32-lsb]
4857   if (Width < 1 || Width > 32 - LSB) {
4858     Error(E, "'width' operand must be in the range [1,32-lsb]");
4859     return MatchOperand_ParseFail;
4860   }
4861
4862   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4863
4864   return MatchOperand_Success;
4865 }
4866
4867 OperandMatchResultTy
4868 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4869   // Check for a post-index addressing register operand. Specifically:
4870   // postidx_reg := '+' register {, shift}
4871   //              | '-' register {, shift}
4872   //              | register {, shift}
4873
4874   // This method must return MatchOperand_NoMatch without consuming any tokens
4875   // in the case where there is no match, as other alternatives take other
4876   // parse methods.
4877   MCAsmParser &Parser = getParser();
4878   AsmToken Tok = Parser.getTok();
4879   SMLoc S = Tok.getLoc();
4880   bool haveEaten = false;
4881   bool isAdd = true;
4882   if (Tok.is(AsmToken::Plus)) {
4883     Parser.Lex(); // Eat the '+' token.
4884     haveEaten = true;
4885   } else if (Tok.is(AsmToken::Minus)) {
4886     Parser.Lex(); // Eat the '-' token.
4887     isAdd = false;
4888     haveEaten = true;
4889   }
4890
4891   SMLoc E = Parser.getTok().getEndLoc();
4892   int Reg = tryParseRegister();
4893   if (Reg == -1) {
4894     if (!haveEaten)
4895       return MatchOperand_NoMatch;
4896     Error(Parser.getTok().getLoc(), "register expected");
4897     return MatchOperand_ParseFail;
4898   }
4899
4900   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4901   unsigned ShiftImm = 0;
4902   if (Parser.getTok().is(AsmToken::Comma)) {
4903     Parser.Lex(); // Eat the ','.
4904     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4905       return MatchOperand_ParseFail;
4906
4907     // FIXME: Only approximates end...may include intervening whitespace.
4908     E = Parser.getTok().getLoc();
4909   }
4910
4911   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4912                                                   ShiftImm, S, E));
4913
4914   return MatchOperand_Success;
4915 }
4916
4917 OperandMatchResultTy
4918 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4919   // Check for a post-index addressing register operand. Specifically:
4920   // am3offset := '+' register
4921   //              | '-' register
4922   //              | register
4923   //              | # imm
4924   //              | # + imm
4925   //              | # - imm
4926
4927   // This method must return MatchOperand_NoMatch without consuming any tokens
4928   // in the case where there is no match, as other alternatives take other
4929   // parse methods.
4930   MCAsmParser &Parser = getParser();
4931   AsmToken Tok = Parser.getTok();
4932   SMLoc S = Tok.getLoc();
4933
4934   // Do immediates first, as we always parse those if we have a '#'.
4935   if (Parser.getTok().is(AsmToken::Hash) ||
4936       Parser.getTok().is(AsmToken::Dollar)) {
4937     Parser.Lex(); // Eat '#' or '$'.
4938     // Explicitly look for a '-', as we need to encode negative zero
4939     // differently.
4940     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4941     const MCExpr *Offset;
4942     SMLoc E;
4943     if (getParser().parseExpression(Offset, E))
4944       return MatchOperand_ParseFail;
4945     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4946     if (!CE) {
4947       Error(S, "constant expression expected");
4948       return MatchOperand_ParseFail;
4949     }
4950     // Negative zero is encoded as the flag value
4951     // std::numeric_limits<int32_t>::min().
4952     int32_t Val = CE->getValue();
4953     if (isNegative && Val == 0)
4954       Val = std::numeric_limits<int32_t>::min();
4955
4956     Operands.push_back(
4957       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4958
4959     return MatchOperand_Success;
4960   }
4961
4962   bool haveEaten = false;
4963   bool isAdd = true;
4964   if (Tok.is(AsmToken::Plus)) {
4965     Parser.Lex(); // Eat the '+' token.
4966     haveEaten = true;
4967   } else if (Tok.is(AsmToken::Minus)) {
4968     Parser.Lex(); // Eat the '-' token.
4969     isAdd = false;
4970     haveEaten = true;
4971   }
4972
4973   Tok = Parser.getTok();
4974   int Reg = tryParseRegister();
4975   if (Reg == -1) {
4976     if (!haveEaten)
4977       return MatchOperand_NoMatch;
4978     Error(Tok.getLoc(), "register expected");
4979     return MatchOperand_ParseFail;
4980   }
4981
4982   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4983                                                   0, S, Tok.getEndLoc()));
4984
4985   return MatchOperand_Success;
4986 }
4987
4988 /// Convert parsed operands to MCInst.  Needed here because this instruction
4989 /// only has two register operands, but multiplication is commutative so
4990 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4991 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4992                                     const OperandVector &Operands) {
4993   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4994   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4995   // If we have a three-operand form, make sure to set Rn to be the operand
4996   // that isn't the same as Rd.
4997   unsigned RegOp = 4;
4998   if (Operands.size() == 6 &&
4999       ((ARMOperand &)*Operands[4]).getReg() ==
5000           ((ARMOperand &)*Operands[3]).getReg())
5001     RegOp = 5;
5002   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
5003   Inst.addOperand(Inst.getOperand(0));
5004   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
5005 }
5006
5007 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
5008                                     const OperandVector &Operands) {
5009   int CondOp = -1, ImmOp = -1;
5010   switch(Inst.getOpcode()) {
5011     case ARM::tB:
5012     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
5013
5014     case ARM::t2B:
5015     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
5016
5017     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
5018   }
5019   // first decide whether or not the branch should be conditional
5020   // by looking at it's location relative to an IT block
5021   if(inITBlock()) {
5022     // inside an IT block we cannot have any conditional branches. any
5023     // such instructions needs to be converted to unconditional form
5024     switch(Inst.getOpcode()) {
5025       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5026       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5027     }
5028   } else {
5029     // outside IT blocks we can only have unconditional branches with AL
5030     // condition code or conditional branches with non-AL condition code
5031     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5032     switch(Inst.getOpcode()) {
5033       case ARM::tB:
5034       case ARM::tBcc:
5035         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5036         break;
5037       case ARM::t2B:
5038       case ARM::t2Bcc:
5039         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5040         break;
5041     }
5042   }
5043
5044   // now decide on encoding size based on branch target range
5045   switch(Inst.getOpcode()) {
5046     // classify tB as either t2B or t1B based on range of immediate operand
5047     case ARM::tB: {
5048       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5049       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5050         Inst.setOpcode(ARM::t2B);
5051       break;
5052     }
5053     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5054     case ARM::tBcc: {
5055       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5056       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5057         Inst.setOpcode(ARM::t2Bcc);
5058       break;
5059     }
5060   }
5061   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5062   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5063 }
5064
5065 /// Parse an ARM memory expression, return false if successful else return true
5066 /// or an error.  The first token must be a '[' when called.
5067 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5068   MCAsmParser &Parser = getParser();
5069   SMLoc S, E;
5070   if (Parser.getTok().isNot(AsmToken::LBrac))
5071     return TokError("Token is not a Left Bracket");
5072   S = Parser.getTok().getLoc();
5073   Parser.Lex(); // Eat left bracket token.
5074
5075   const AsmToken &BaseRegTok = Parser.getTok();
5076   int BaseRegNum = tryParseRegister();
5077   if (BaseRegNum == -1)
5078     return Error(BaseRegTok.getLoc(), "register expected");
5079
5080   // The next token must either be a comma, a colon or a closing bracket.
5081   const AsmToken &Tok = Parser.getTok();
5082   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5083       !Tok.is(AsmToken::RBrac))
5084     return Error(Tok.getLoc(), "malformed memory operand");
5085
5086   if (Tok.is(AsmToken::RBrac)) {
5087     E = Tok.getEndLoc();
5088     Parser.Lex(); // Eat right bracket token.
5089
5090     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5091                                              ARM_AM::no_shift, 0, 0, false,
5092                                              S, E));
5093
5094     // If there's a pre-indexing writeback marker, '!', just add it as a token
5095     // operand. It's rather odd, but syntactically valid.
5096     if (Parser.getTok().is(AsmToken::Exclaim)) {
5097       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5098       Parser.Lex(); // Eat the '!'.
5099     }
5100
5101     return false;
5102   }
5103
5104   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5105          "Lost colon or comma in memory operand?!");
5106   if (Tok.is(AsmToken::Comma)) {
5107     Parser.Lex(); // Eat the comma.
5108   }
5109
5110   // If we have a ':', it's an alignment specifier.
5111   if (Parser.getTok().is(AsmToken::Colon)) {
5112     Parser.Lex(); // Eat the ':'.
5113     E = Parser.getTok().getLoc();
5114     SMLoc AlignmentLoc = Tok.getLoc();
5115
5116     const MCExpr *Expr;
5117     if (getParser().parseExpression(Expr))
5118      return true;
5119
5120     // The expression has to be a constant. Memory references with relocations
5121     // don't come through here, as they use the <label> forms of the relevant
5122     // instructions.
5123     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5124     if (!CE)
5125       return Error (E, "constant expression expected");
5126
5127     unsigned Align = 0;
5128     switch (CE->getValue()) {
5129     default:
5130       return Error(E,
5131                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5132     case 16:  Align = 2; break;
5133     case 32:  Align = 4; break;
5134     case 64:  Align = 8; break;
5135     case 128: Align = 16; break;
5136     case 256: Align = 32; break;
5137     }
5138
5139     // Now we should have the closing ']'
5140     if (Parser.getTok().isNot(AsmToken::RBrac))
5141       return Error(Parser.getTok().getLoc(), "']' expected");
5142     E = Parser.getTok().getEndLoc();
5143     Parser.Lex(); // Eat right bracket token.
5144
5145     // Don't worry about range checking the value here. That's handled by
5146     // the is*() predicates.
5147     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5148                                              ARM_AM::no_shift, 0, Align,
5149                                              false, S, E, AlignmentLoc));
5150
5151     // If there's a pre-indexing writeback marker, '!', just add it as a token
5152     // operand.
5153     if (Parser.getTok().is(AsmToken::Exclaim)) {
5154       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5155       Parser.Lex(); // Eat the '!'.
5156     }
5157
5158     return false;
5159   }
5160
5161   // If we have a '#', it's an immediate offset, else assume it's a register
5162   // offset. Be friendly and also accept a plain integer (without a leading
5163   // hash) for gas compatibility.
5164   if (Parser.getTok().is(AsmToken::Hash) ||
5165       Parser.getTok().is(AsmToken::Dollar) ||
5166       Parser.getTok().is(AsmToken::Integer)) {
5167     if (Parser.getTok().isNot(AsmToken::Integer))
5168       Parser.Lex(); // Eat '#' or '$'.
5169     E = Parser.getTok().getLoc();
5170
5171     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5172     const MCExpr *Offset;
5173     if (getParser().parseExpression(Offset))
5174      return true;
5175
5176     // The expression has to be a constant. Memory references with relocations
5177     // don't come through here, as they use the <label> forms of the relevant
5178     // instructions.
5179     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5180     if (!CE)
5181       return Error (E, "constant expression expected");
5182
5183     // If the constant was #-0, represent it as
5184     // std::numeric_limits<int32_t>::min().
5185     int32_t Val = CE->getValue();
5186     if (isNegative && Val == 0)
5187       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5188                                   getContext());
5189
5190     // Now we should have the closing ']'
5191     if (Parser.getTok().isNot(AsmToken::RBrac))
5192       return Error(Parser.getTok().getLoc(), "']' expected");
5193     E = Parser.getTok().getEndLoc();
5194     Parser.Lex(); // Eat right bracket token.
5195
5196     // Don't worry about range checking the value here. That's handled by
5197     // the is*() predicates.
5198     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5199                                              ARM_AM::no_shift, 0, 0,
5200                                              false, S, E));
5201
5202     // If there's a pre-indexing writeback marker, '!', just add it as a token
5203     // operand.
5204     if (Parser.getTok().is(AsmToken::Exclaim)) {
5205       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5206       Parser.Lex(); // Eat the '!'.
5207     }
5208
5209     return false;
5210   }
5211
5212   // The register offset is optionally preceded by a '+' or '-'
5213   bool isNegative = false;
5214   if (Parser.getTok().is(AsmToken::Minus)) {
5215     isNegative = true;
5216     Parser.Lex(); // Eat the '-'.
5217   } else if (Parser.getTok().is(AsmToken::Plus)) {
5218     // Nothing to do.
5219     Parser.Lex(); // Eat the '+'.
5220   }
5221
5222   E = Parser.getTok().getLoc();
5223   int OffsetRegNum = tryParseRegister();
5224   if (OffsetRegNum == -1)
5225     return Error(E, "register expected");
5226
5227   // If there's a shift operator, handle it.
5228   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5229   unsigned ShiftImm = 0;
5230   if (Parser.getTok().is(AsmToken::Comma)) {
5231     Parser.Lex(); // Eat the ','.
5232     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5233       return true;
5234   }
5235
5236   // Now we should have the closing ']'
5237   if (Parser.getTok().isNot(AsmToken::RBrac))
5238     return Error(Parser.getTok().getLoc(), "']' expected");
5239   E = Parser.getTok().getEndLoc();
5240   Parser.Lex(); // Eat right bracket token.
5241
5242   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5243                                            ShiftType, ShiftImm, 0, isNegative,
5244                                            S, E));
5245
5246   // If there's a pre-indexing writeback marker, '!', just add it as a token
5247   // operand.
5248   if (Parser.getTok().is(AsmToken::Exclaim)) {
5249     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5250     Parser.Lex(); // Eat the '!'.
5251   }
5252
5253   return false;
5254 }
5255
5256 /// parseMemRegOffsetShift - one of these two:
5257 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5258 ///   rrx
5259 /// return true if it parses a shift otherwise it returns false.
5260 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5261                                           unsigned &Amount) {
5262   MCAsmParser &Parser = getParser();
5263   SMLoc Loc = Parser.getTok().getLoc();
5264   const AsmToken &Tok = Parser.getTok();
5265   if (Tok.isNot(AsmToken::Identifier))
5266     return Error(Loc, "illegal shift operator");
5267   StringRef ShiftName = Tok.getString();
5268   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5269       ShiftName == "asl" || ShiftName == "ASL")
5270     St = ARM_AM::lsl;
5271   else if (ShiftName == "lsr" || ShiftName == "LSR")
5272     St = ARM_AM::lsr;
5273   else if (ShiftName == "asr" || ShiftName == "ASR")
5274     St = ARM_AM::asr;
5275   else if (ShiftName == "ror" || ShiftName == "ROR")
5276     St = ARM_AM::ror;
5277   else if (ShiftName == "rrx" || ShiftName == "RRX")
5278     St = ARM_AM::rrx;
5279   else
5280     return Error(Loc, "illegal shift operator");
5281   Parser.Lex(); // Eat shift type token.
5282
5283   // rrx stands alone.
5284   Amount = 0;
5285   if (St != ARM_AM::rrx) {
5286     Loc = Parser.getTok().getLoc();
5287     // A '#' and a shift amount.
5288     const AsmToken &HashTok = Parser.getTok();
5289     if (HashTok.isNot(AsmToken::Hash) &&
5290         HashTok.isNot(AsmToken::Dollar))
5291       return Error(HashTok.getLoc(), "'#' expected");
5292     Parser.Lex(); // Eat hash token.
5293
5294     const MCExpr *Expr;
5295     if (getParser().parseExpression(Expr))
5296       return true;
5297     // Range check the immediate.
5298     // lsl, ror: 0 <= imm <= 31
5299     // lsr, asr: 0 <= imm <= 32
5300     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5301     if (!CE)
5302       return Error(Loc, "shift amount must be an immediate");
5303     int64_t Imm = CE->getValue();
5304     if (Imm < 0 ||
5305         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5306         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5307       return Error(Loc, "immediate shift value out of range");
5308     // If <ShiftTy> #0, turn it into a no_shift.
5309     if (Imm == 0)
5310       St = ARM_AM::lsl;
5311     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5312     if (Imm == 32)
5313       Imm = 0;
5314     Amount = Imm;
5315   }
5316
5317   return false;
5318 }
5319
5320 /// parseFPImm - A floating point immediate expression operand.
5321 OperandMatchResultTy
5322 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5323   MCAsmParser &Parser = getParser();
5324   // Anything that can accept a floating point constant as an operand
5325   // needs to go through here, as the regular parseExpression is
5326   // integer only.
5327   //
5328   // This routine still creates a generic Immediate operand, containing
5329   // a bitcast of the 64-bit floating point value. The various operands
5330   // that accept floats can check whether the value is valid for them
5331   // via the standard is*() predicates.
5332
5333   SMLoc S = Parser.getTok().getLoc();
5334
5335   if (Parser.getTok().isNot(AsmToken::Hash) &&
5336       Parser.getTok().isNot(AsmToken::Dollar))
5337     return MatchOperand_NoMatch;
5338
5339   // Disambiguate the VMOV forms that can accept an FP immediate.
5340   // vmov.f32 <sreg>, #imm
5341   // vmov.f64 <dreg>, #imm
5342   // vmov.f32 <dreg>, #imm  @ vector f32x2
5343   // vmov.f32 <qreg>, #imm  @ vector f32x4
5344   //
5345   // There are also the NEON VMOV instructions which expect an
5346   // integer constant. Make sure we don't try to parse an FPImm
5347   // for these:
5348   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5349   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5350   bool isVmovf = TyOp.isToken() &&
5351                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5352                   TyOp.getToken() == ".f16");
5353   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5354   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5355                                          Mnemonic.getToken() == "fconsts");
5356   if (!(isVmovf || isFconst))
5357     return MatchOperand_NoMatch;
5358
5359   Parser.Lex(); // Eat '#' or '$'.
5360
5361   // Handle negation, as that still comes through as a separate token.
5362   bool isNegative = false;
5363   if (Parser.getTok().is(AsmToken::Minus)) {
5364     isNegative = true;
5365     Parser.Lex();
5366   }
5367   const AsmToken &Tok = Parser.getTok();
5368   SMLoc Loc = Tok.getLoc();
5369   if (Tok.is(AsmToken::Real) && isVmovf) {
5370     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5371     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5372     // If we had a '-' in front, toggle the sign bit.
5373     IntVal ^= (uint64_t)isNegative << 31;
5374     Parser.Lex(); // Eat the token.
5375     Operands.push_back(ARMOperand::CreateImm(
5376           MCConstantExpr::create(IntVal, getContext()),
5377           S, Parser.getTok().getLoc()));
5378     return MatchOperand_Success;
5379   }
5380   // Also handle plain integers. Instructions which allow floating point
5381   // immediates also allow a raw encoded 8-bit value.
5382   if (Tok.is(AsmToken::Integer) && isFconst) {
5383     int64_t Val = Tok.getIntVal();
5384     Parser.Lex(); // Eat the token.
5385     if (Val > 255 || Val < 0) {
5386       Error(Loc, "encoded floating point value out of range");
5387       return MatchOperand_ParseFail;
5388     }
5389     float RealVal = ARM_AM::getFPImmFloat(Val);
5390     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5391
5392     Operands.push_back(ARMOperand::CreateImm(
5393         MCConstantExpr::create(Val, getContext()), S,
5394         Parser.getTok().getLoc()));
5395     return MatchOperand_Success;
5396   }
5397
5398   Error(Loc, "invalid floating point immediate");
5399   return MatchOperand_ParseFail;
5400 }
5401
5402 /// Parse a arm instruction operand.  For now this parses the operand regardless
5403 /// of the mnemonic.
5404 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5405   MCAsmParser &Parser = getParser();
5406   SMLoc S, E;
5407
5408   // Check if the current operand has a custom associated parser, if so, try to
5409   // custom parse the operand, or fallback to the general approach.
5410   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5411   if (ResTy == MatchOperand_Success)
5412     return false;
5413   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5414   // there was a match, but an error occurred, in which case, just return that
5415   // the operand parsing failed.
5416   if (ResTy == MatchOperand_ParseFail)
5417     return true;
5418
5419   switch (getLexer().getKind()) {
5420   default:
5421     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5422     return true;
5423   case AsmToken::Identifier: {
5424     // If we've seen a branch mnemonic, the next operand must be a label.  This
5425     // is true even if the label is a register name.  So "br r1" means branch to
5426     // label "r1".
5427     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5428     if (!ExpectLabel) {
5429       if (!tryParseRegisterWithWriteBack(Operands))
5430         return false;
5431       int Res = tryParseShiftRegister(Operands);
5432       if (Res == 0) // success
5433         return false;
5434       else if (Res == -1) // irrecoverable error
5435         return true;
5436       // If this is VMRS, check for the apsr_nzcv operand.
5437       if (Mnemonic == "vmrs" &&
5438           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5439         S = Parser.getTok().getLoc();
5440         Parser.Lex();
5441         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5442         return false;
5443       }
5444     }
5445
5446     // Fall though for the Identifier case that is not a register or a
5447     // special name.
5448     LLVM_FALLTHROUGH;
5449   }
5450   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5451   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5452   case AsmToken::String:  // quoted label names.
5453   case AsmToken::Dot: {   // . as a branch target
5454     // This was not a register so parse other operands that start with an
5455     // identifier (like labels) as expressions and create them as immediates.
5456     const MCExpr *IdVal;
5457     S = Parser.getTok().getLoc();
5458     if (getParser().parseExpression(IdVal))
5459       return true;
5460     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5461     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5462     return false;
5463   }
5464   case AsmToken::LBrac:
5465     return parseMemory(Operands);
5466   case AsmToken::LCurly:
5467     return parseRegisterList(Operands);
5468   case AsmToken::Dollar:
5469   case AsmToken::Hash:
5470     // #42 -> immediate.
5471     S = Parser.getTok().getLoc();
5472     Parser.Lex();
5473
5474     if (Parser.getTok().isNot(AsmToken::Colon)) {
5475       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5476       const MCExpr *ImmVal;
5477       if (getParser().parseExpression(ImmVal))
5478         return true;
5479       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5480       if (CE) {
5481         int32_t Val = CE->getValue();
5482         if (isNegative && Val == 0)
5483           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5484                                           getContext());
5485       }
5486       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5487       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5488
5489       // There can be a trailing '!' on operands that we want as a separate
5490       // '!' Token operand. Handle that here. For example, the compatibility
5491       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5492       if (Parser.getTok().is(AsmToken::Exclaim)) {
5493         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5494                                                    Parser.getTok().getLoc()));
5495         Parser.Lex(); // Eat exclaim token
5496       }
5497       return false;
5498     }
5499     // w/ a ':' after the '#', it's just like a plain ':'.
5500     LLVM_FALLTHROUGH;
5501
5502   case AsmToken::Colon: {
5503     S = Parser.getTok().getLoc();
5504     // ":lower16:" and ":upper16:" expression prefixes
5505     // FIXME: Check it's an expression prefix,
5506     // e.g. (FOO - :lower16:BAR) isn't legal.
5507     ARMMCExpr::VariantKind RefKind;
5508     if (parsePrefix(RefKind))
5509       return true;
5510
5511     const MCExpr *SubExprVal;
5512     if (getParser().parseExpression(SubExprVal))
5513       return true;
5514
5515     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5516                                               getContext());
5517     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5518     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5519     return false;
5520   }
5521   case AsmToken::Equal: {
5522     S = Parser.getTok().getLoc();
5523     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5524       return Error(S, "unexpected token in operand");
5525     Parser.Lex(); // Eat '='
5526     const MCExpr *SubExprVal;
5527     if (getParser().parseExpression(SubExprVal))
5528       return true;
5529     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5530
5531     // execute-only: we assume that assembly programmers know what they are
5532     // doing and allow literal pool creation here
5533     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5534     return false;
5535   }
5536   }
5537 }
5538
5539 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5540 //  :lower16: and :upper16:.
5541 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5542   MCAsmParser &Parser = getParser();
5543   RefKind = ARMMCExpr::VK_ARM_None;
5544
5545   // consume an optional '#' (GNU compatibility)
5546   if (getLexer().is(AsmToken::Hash))
5547     Parser.Lex();
5548
5549   // :lower16: and :upper16: modifiers
5550   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5551   Parser.Lex(); // Eat ':'
5552
5553   if (getLexer().isNot(AsmToken::Identifier)) {
5554     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5555     return true;
5556   }
5557
5558   enum {
5559     COFF = (1 << MCObjectFileInfo::IsCOFF),
5560     ELF = (1 << MCObjectFileInfo::IsELF),
5561     MACHO = (1 << MCObjectFileInfo::IsMachO),
5562     WASM = (1 << MCObjectFileInfo::IsWasm),
5563   };
5564   static const struct PrefixEntry {
5565     const char *Spelling;
5566     ARMMCExpr::VariantKind VariantKind;
5567     uint8_t SupportedFormats;
5568   } PrefixEntries[] = {
5569     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5570     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5571   };
5572
5573   StringRef IDVal = Parser.getTok().getIdentifier();
5574
5575   const auto &Prefix =
5576       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5577                    [&IDVal](const PrefixEntry &PE) {
5578                       return PE.Spelling == IDVal;
5579                    });
5580   if (Prefix == std::end(PrefixEntries)) {
5581     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5582     return true;
5583   }
5584
5585   uint8_t CurrentFormat;
5586   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5587   case MCObjectFileInfo::IsMachO:
5588     CurrentFormat = MACHO;
5589     break;
5590   case MCObjectFileInfo::IsELF:
5591     CurrentFormat = ELF;
5592     break;
5593   case MCObjectFileInfo::IsCOFF:
5594     CurrentFormat = COFF;
5595     break;
5596   case MCObjectFileInfo::IsWasm:
5597     CurrentFormat = WASM;
5598     break;
5599   case MCObjectFileInfo::IsXCOFF:
5600     llvm_unreachable("unexpected object format");
5601     break;
5602   }
5603
5604   if (~Prefix->SupportedFormats & CurrentFormat) {
5605     Error(Parser.getTok().getLoc(),
5606           "cannot represent relocation in the current file format");
5607     return true;
5608   }
5609
5610   RefKind = Prefix->VariantKind;
5611   Parser.Lex();
5612
5613   if (getLexer().isNot(AsmToken::Colon)) {
5614     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5615     return true;
5616   }
5617   Parser.Lex(); // Eat the last ':'
5618
5619   return false;
5620 }
5621
5622 /// Given a mnemonic, split out possible predication code and carry
5623 /// setting letters to form a canonical mnemonic and flags.
5624 //
5625 // FIXME: Would be nice to autogen this.
5626 // FIXME: This is a bit of a maze of special cases.
5627 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5628                                       unsigned &PredicationCode,
5629                                       bool &CarrySetting,
5630                                       unsigned &ProcessorIMod,
5631                                       StringRef &ITMask) {
5632   PredicationCode = ARMCC::AL;
5633   CarrySetting = false;
5634   ProcessorIMod = 0;
5635
5636   // Ignore some mnemonics we know aren't predicated forms.
5637   //
5638   // FIXME: Would be nice to autogen this.
5639   if ((Mnemonic == "movs" && isThumb()) ||
5640       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5641       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5642       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5643       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5644       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5645       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5646       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5647       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5648       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5649       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5650       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5651       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5652       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5653       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
5654       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5655       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
5656       Mnemonic == "vfmal" || Mnemonic == "vfmsl")
5657     return Mnemonic;
5658
5659   // First, split out any predication code. Ignore mnemonics we know aren't
5660   // predicated but do have a carry-set and so weren't caught above.
5661   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5662       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5663       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5664       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5665     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
5666     if (CC != ~0U) {
5667       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5668       PredicationCode = CC;
5669     }
5670   }
5671
5672   // Next, determine if we have a carry setting bit. We explicitly ignore all
5673   // the instructions we know end in 's'.
5674   if (Mnemonic.endswith("s") &&
5675       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5676         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5677         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5678         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5679         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5680         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5681         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5682         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5683         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5684         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5685         (Mnemonic == "movs" && isThumb()))) {
5686     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5687     CarrySetting = true;
5688   }
5689
5690   // The "cps" instruction can have a interrupt mode operand which is glued into
5691   // the mnemonic. Check if this is the case, split it and parse the imod op
5692   if (Mnemonic.startswith("cps")) {
5693     // Split out any imod code.
5694     unsigned IMod =
5695       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5696       .Case("ie", ARM_PROC::IE)
5697       .Case("id", ARM_PROC::ID)
5698       .Default(~0U);
5699     if (IMod != ~0U) {
5700       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5701       ProcessorIMod = IMod;
5702     }
5703   }
5704
5705   // The "it" instruction has the condition mask on the end of the mnemonic.
5706   if (Mnemonic.startswith("it")) {
5707     ITMask = Mnemonic.slice(2, Mnemonic.size());
5708     Mnemonic = Mnemonic.slice(0, 2);
5709   }
5710
5711   return Mnemonic;
5712 }
5713
5714 /// Given a canonical mnemonic, determine if the instruction ever allows
5715 /// inclusion of carry set or predication code operands.
5716 //
5717 // FIXME: It would be nice to autogen this.
5718 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5719                                          bool &CanAcceptCarrySet,
5720                                          bool &CanAcceptPredicationCode) {
5721   CanAcceptCarrySet =
5722       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5723       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5724       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5725       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5726       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5727       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5728       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5729       (!isThumb() &&
5730        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5731         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5732
5733   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5734       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5735       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5736       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5737       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5738       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5739       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5740       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5741       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5742       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5743       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5744       Mnemonic == "vmovx" || Mnemonic == "vins" ||
5745       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5746       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
5747       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
5748       Mnemonic == "sb"    || Mnemonic == "ssbb"  ||
5749       Mnemonic == "pssbb") {
5750     // These mnemonics are never predicable
5751     CanAcceptPredicationCode = false;
5752   } else if (!isThumb()) {
5753     // Some instructions are only predicable in Thumb mode
5754     CanAcceptPredicationCode =
5755         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5756         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5757         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
5758         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
5759         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
5760         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
5761         Mnemonic != "tsb" &&
5762         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
5763   } else if (isThumbOne()) {
5764     if (hasV6MOps())
5765       CanAcceptPredicationCode = Mnemonic != "movs";
5766     else
5767       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5768   } else
5769     CanAcceptPredicationCode = true;
5770 }
5771
5772 // Some Thumb instructions have two operand forms that are not
5773 // available as three operand, convert to two operand form if possible.
5774 //
5775 // FIXME: We would really like to be able to tablegen'erate this.
5776 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5777                                                  bool CarrySetting,
5778                                                  OperandVector &Operands) {
5779   if (Operands.size() != 6)
5780     return;
5781
5782   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5783         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5784   if (!Op3.isReg() || !Op4.isReg())
5785     return;
5786
5787   auto Op3Reg = Op3.getReg();
5788   auto Op4Reg = Op4.getReg();
5789
5790   // For most Thumb2 cases we just generate the 3 operand form and reduce
5791   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5792   // won't accept SP or PC so we do the transformation here taking care
5793   // with immediate range in the 'add sp, sp #imm' case.
5794   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5795   if (isThumbTwo()) {
5796     if (Mnemonic != "add")
5797       return;
5798     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5799                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5800     if (!TryTransform) {
5801       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5802                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5803                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5804                        Op5.isImm() && !Op5.isImm0_508s4());
5805     }
5806     if (!TryTransform)
5807       return;
5808   } else if (!isThumbOne())
5809     return;
5810
5811   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5812         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5813         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5814         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5815     return;
5816
5817   // If first 2 operands of a 3 operand instruction are the same
5818   // then transform to 2 operand version of the same instruction
5819   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5820   bool Transform = Op3Reg == Op4Reg;
5821
5822   // For communtative operations, we might be able to transform if we swap
5823   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5824   // as tADDrsp.
5825   const ARMOperand *LastOp = &Op5;
5826   bool Swap = false;
5827   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5828       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5829        Mnemonic == "and" || Mnemonic == "eor" ||
5830        Mnemonic == "adc" || Mnemonic == "orr")) {
5831     Swap = true;
5832     LastOp = &Op4;
5833     Transform = true;
5834   }
5835
5836   // If both registers are the same then remove one of them from
5837   // the operand list, with certain exceptions.
5838   if (Transform) {
5839     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5840     // 2 operand forms don't exist.
5841     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5842         LastOp->isReg())
5843       Transform = false;
5844
5845     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5846     // 3-bits because the ARMARM says not to.
5847     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5848       Transform = false;
5849   }
5850
5851   if (Transform) {
5852     if (Swap)
5853       std::swap(Op4, Op5);
5854     Operands.erase(Operands.begin() + 3);
5855   }
5856 }
5857
5858 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5859                                           OperandVector &Operands) {
5860   // FIXME: This is all horribly hacky. We really need a better way to deal
5861   // with optional operands like this in the matcher table.
5862
5863   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5864   // another does not. Specifically, the MOVW instruction does not. So we
5865   // special case it here and remove the defaulted (non-setting) cc_out
5866   // operand if that's the instruction we're trying to match.
5867   //
5868   // We do this as post-processing of the explicit operands rather than just
5869   // conditionally adding the cc_out in the first place because we need
5870   // to check the type of the parsed immediate operand.
5871   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5872       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5873       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5874       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5875     return true;
5876
5877   // Register-register 'add' for thumb does not have a cc_out operand
5878   // when there are only two register operands.
5879   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5880       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5881       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5882       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5883     return true;
5884   // Register-register 'add' for thumb does not have a cc_out operand
5885   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5886   // have to check the immediate range here since Thumb2 has a variant
5887   // that can handle a different range and has a cc_out operand.
5888   if (((isThumb() && Mnemonic == "add") ||
5889        (isThumbTwo() && Mnemonic == "sub")) &&
5890       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5891       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5892       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5893       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5894       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5895        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5896     return true;
5897   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5898   // imm0_4095 variant. That's the least-preferred variant when
5899   // selecting via the generic "add" mnemonic, so to know that we
5900   // should remove the cc_out operand, we have to explicitly check that
5901   // it's not one of the other variants. Ugh.
5902   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5903       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5904       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5905       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5906     // Nest conditions rather than one big 'if' statement for readability.
5907     //
5908     // If both registers are low, we're in an IT block, and the immediate is
5909     // in range, we should use encoding T1 instead, which has a cc_out.
5910     if (inITBlock() &&
5911         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5912         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5913         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5914       return false;
5915     // Check against T3. If the second register is the PC, this is an
5916     // alternate form of ADR, which uses encoding T4, so check for that too.
5917     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5918         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5919       return false;
5920
5921     // Otherwise, we use encoding T4, which does not have a cc_out
5922     // operand.
5923     return true;
5924   }
5925
5926   // The thumb2 multiply instruction doesn't have a CCOut register, so
5927   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5928   // use the 16-bit encoding or not.
5929   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5930       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5931       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5932       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5933       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5934       // If the registers aren't low regs, the destination reg isn't the
5935       // same as one of the source regs, or the cc_out operand is zero
5936       // outside of an IT block, we have to use the 32-bit encoding, so
5937       // remove the cc_out operand.
5938       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5939        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5940        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5941        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5942                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5943                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5944                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5945     return true;
5946
5947   // Also check the 'mul' syntax variant that doesn't specify an explicit
5948   // destination register.
5949   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5950       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5951       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5952       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5953       // If the registers aren't low regs  or the cc_out operand is zero
5954       // outside of an IT block, we have to use the 32-bit encoding, so
5955       // remove the cc_out operand.
5956       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5957        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5958        !inITBlock()))
5959     return true;
5960
5961   // Register-register 'add/sub' for thumb does not have a cc_out operand
5962   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5963   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5964   // right, this will result in better diagnostics (which operand is off)
5965   // anyway.
5966   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5967       (Operands.size() == 5 || Operands.size() == 6) &&
5968       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5969       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5970       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5971       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5972        (Operands.size() == 6 &&
5973         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5974     return true;
5975
5976   return false;
5977 }
5978
5979 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5980                                               OperandVector &Operands) {
5981   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
5982   unsigned RegIdx = 3;
5983   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx") &&
5984       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5985        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5986     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5987         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5988          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5989       RegIdx = 4;
5990
5991     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5992         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5993              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5994          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5995              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5996       return true;
5997   }
5998   return false;
5999 }
6000
6001 static bool isDataTypeToken(StringRef Tok) {
6002   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
6003     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
6004     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
6005     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
6006     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
6007     Tok == ".f" || Tok == ".d";
6008 }
6009
6010 // FIXME: This bit should probably be handled via an explicit match class
6011 // in the .td files that matches the suffix instead of having it be
6012 // a literal string token the way it is now.
6013 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
6014   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
6015 }
6016
6017 static void applyMnemonicAliases(StringRef &Mnemonic,
6018                                  const FeatureBitset &Features,
6019                                  unsigned VariantID);
6020
6021 // The GNU assembler has aliases of ldrd and strd with the second register
6022 // omitted. We don't have a way to do that in tablegen, so fix it up here.
6023 //
6024 // We have to be careful to not emit an invalid Rt2 here, because the rest of
6025 // the assmebly parser could then generate confusing diagnostics refering to
6026 // it. If we do find anything that prevents us from doing the transformation we
6027 // bail out, and let the assembly parser report an error on the instruction as
6028 // it is written.
6029 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6030                                      OperandVector &Operands) {
6031   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6032     return;
6033   if (Operands.size() < 4)
6034     return;
6035
6036   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6037   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6038
6039   if (!Op2.isReg())
6040     return;
6041   if (!Op3.isMem())
6042     return;
6043
6044   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6045   if (!GPR.contains(Op2.getReg()))
6046     return;
6047
6048   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6049   if (!isThumb() && (RtEncoding & 1)) {
6050     // In ARM mode, the registers must be from an aligned pair, this
6051     // restriction does not apply in Thumb mode.
6052     return;
6053   }
6054   if (Op2.getReg() == ARM::PC)
6055     return;
6056   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6057   if (!PairedReg || PairedReg == ARM::PC ||
6058       (PairedReg == ARM::SP && !hasV8Ops()))
6059     return;
6060
6061   Operands.insert(
6062       Operands.begin() + 3,
6063       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6064 }
6065
6066 /// Parse an arm instruction mnemonic followed by its operands.
6067 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
6068                                     SMLoc NameLoc, OperandVector &Operands) {
6069   MCAsmParser &Parser = getParser();
6070
6071   // Apply mnemonic aliases before doing anything else, as the destination
6072   // mnemonic may include suffices and we want to handle them normally.
6073   // The generic tblgen'erated code does this later, at the start of
6074   // MatchInstructionImpl(), but that's too late for aliases that include
6075   // any sort of suffix.
6076   const FeatureBitset &AvailableFeatures = getAvailableFeatures();
6077   unsigned AssemblerDialect = getParser().getAssemblerDialect();
6078   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
6079
6080   // First check for the ARM-specific .req directive.
6081   if (Parser.getTok().is(AsmToken::Identifier) &&
6082       Parser.getTok().getIdentifier() == ".req") {
6083     parseDirectiveReq(Name, NameLoc);
6084     // We always return 'error' for this, as we're done with this
6085     // statement and don't need to match the 'instruction."
6086     return true;
6087   }
6088
6089   // Create the leading tokens for the mnemonic, split by '.' characters.
6090   size_t Start = 0, Next = Name.find('.');
6091   StringRef Mnemonic = Name.slice(Start, Next);
6092
6093   // Split out the predication code and carry setting flag from the mnemonic.
6094   unsigned PredicationCode;
6095   unsigned ProcessorIMod;
6096   bool CarrySetting;
6097   StringRef ITMask;
6098   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
6099                            ProcessorIMod, ITMask);
6100
6101   // In Thumb1, only the branch (B) instruction can be predicated.
6102   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
6103     return Error(NameLoc, "conditional execution not supported in Thumb1");
6104   }
6105
6106   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
6107
6108   // Handle the IT instruction ITMask. Convert it to a bitmask. This
6109   // is the mask as it will be for the IT encoding if the conditional
6110   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
6111   // where the conditional bit0 is zero, the instruction post-processing
6112   // will adjust the mask accordingly.
6113   if (Mnemonic == "it") {
6114     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
6115     if (ITMask.size() > 3) {
6116       return Error(Loc, "too many conditions on IT instruction");
6117     }
6118     unsigned Mask = 8;
6119     for (unsigned i = ITMask.size(); i != 0; --i) {
6120       char pos = ITMask[i - 1];
6121       if (pos != 't' && pos != 'e') {
6122         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
6123       }
6124       Mask >>= 1;
6125       if (ITMask[i - 1] == 't')
6126         Mask |= 8;
6127     }
6128     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
6129   }
6130
6131   // FIXME: This is all a pretty gross hack. We should automatically handle
6132   // optional operands like this via tblgen.
6133
6134   // Next, add the CCOut and ConditionCode operands, if needed.
6135   //
6136   // For mnemonics which can ever incorporate a carry setting bit or predication
6137   // code, our matching model involves us always generating CCOut and
6138   // ConditionCode operands to match the mnemonic "as written" and then we let
6139   // the matcher deal with finding the right instruction or generating an
6140   // appropriate error.
6141   bool CanAcceptCarrySet, CanAcceptPredicationCode;
6142   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
6143
6144   // If we had a carry-set on an instruction that can't do that, issue an
6145   // error.
6146   if (!CanAcceptCarrySet && CarrySetting) {
6147     return Error(NameLoc, "instruction '" + Mnemonic +
6148                  "' can not set flags, but 's' suffix specified");
6149   }
6150   // If we had a predication code on an instruction that can't do that, issue an
6151   // error.
6152   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
6153     return Error(NameLoc, "instruction '" + Mnemonic +
6154                  "' is not predicable, but condition code specified");
6155   }
6156
6157   // Add the carry setting operand, if necessary.
6158   if (CanAcceptCarrySet) {
6159     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
6160     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
6161                                                Loc));
6162   }
6163
6164   // Add the predication code operand, if necessary.
6165   if (CanAcceptPredicationCode) {
6166     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6167                                       CarrySetting);
6168     Operands.push_back(ARMOperand::CreateCondCode(
6169                          ARMCC::CondCodes(PredicationCode), Loc));
6170   }
6171
6172   // Add the processor imod operand, if necessary.
6173   if (ProcessorIMod) {
6174     Operands.push_back(ARMOperand::CreateImm(
6175           MCConstantExpr::create(ProcessorIMod, getContext()),
6176                                  NameLoc, NameLoc));
6177   } else if (Mnemonic == "cps" && isMClass()) {
6178     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
6179   }
6180
6181   // Add the remaining tokens in the mnemonic.
6182   while (Next != StringRef::npos) {
6183     Start = Next;
6184     Next = Name.find('.', Start + 1);
6185     StringRef ExtraToken = Name.slice(Start, Next);
6186
6187     // Some NEON instructions have an optional datatype suffix that is
6188     // completely ignored. Check for that.
6189     if (isDataTypeToken(ExtraToken) &&
6190         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
6191       continue;
6192
6193     // For for ARM mode generate an error if the .n qualifier is used.
6194     if (ExtraToken == ".n" && !isThumb()) {
6195       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6196       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6197                    "arm mode");
6198     }
6199
6200     // The .n qualifier is always discarded as that is what the tables
6201     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6202     // so discard it to avoid errors that can be caused by the matcher.
6203     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6204       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6205       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6206     }
6207   }
6208
6209   // Read the remaining operands.
6210   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6211     // Read the first operand.
6212     if (parseOperand(Operands, Mnemonic)) {
6213       return true;
6214     }
6215
6216     while (parseOptionalToken(AsmToken::Comma)) {
6217       // Parse and remember the operand.
6218       if (parseOperand(Operands, Mnemonic)) {
6219         return true;
6220       }
6221     }
6222   }
6223
6224   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6225     return true;
6226
6227   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6228
6229   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6230   // do and don't have a cc_out optional-def operand. With some spot-checks
6231   // of the operand list, we can figure out which variant we're trying to
6232   // parse and adjust accordingly before actually matching. We shouldn't ever
6233   // try to remove a cc_out operand that was explicitly set on the
6234   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6235   // table driven matcher doesn't fit well with the ARM instruction set.
6236   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6237     Operands.erase(Operands.begin() + 1);
6238
6239   // Some instructions have the same mnemonic, but don't always
6240   // have a predicate. Distinguish them here and delete the
6241   // predicate if needed.
6242   if (PredicationCode == ARMCC::AL &&
6243       shouldOmitPredicateOperand(Mnemonic, Operands))
6244     Operands.erase(Operands.begin() + 1);
6245
6246   // ARM mode 'blx' need special handling, as the register operand version
6247   // is predicable, but the label operand version is not. So, we can't rely
6248   // on the Mnemonic based checking to correctly figure out when to put
6249   // a k_CondCode operand in the list. If we're trying to match the label
6250   // version, remove the k_CondCode operand here.
6251   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6252       static_cast<ARMOperand &>(*Operands[2]).isImm())
6253     Operands.erase(Operands.begin() + 1);
6254
6255   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6256   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6257   // a single GPRPair reg operand is used in the .td file to replace the two
6258   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6259   // expressed as a GPRPair, so we have to manually merge them.
6260   // FIXME: We would really like to be able to tablegen'erate this.
6261   if (!isThumb() && Operands.size() > 4 &&
6262       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6263        Mnemonic == "stlexd")) {
6264     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6265     unsigned Idx = isLoad ? 2 : 3;
6266     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6267     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6268
6269     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6270     // Adjust only if Op1 and Op2 are GPRs.
6271     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6272         MRC.contains(Op2.getReg())) {
6273       unsigned Reg1 = Op1.getReg();
6274       unsigned Reg2 = Op2.getReg();
6275       unsigned Rt = MRI->getEncodingValue(Reg1);
6276       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6277
6278       // Rt2 must be Rt + 1 and Rt must be even.
6279       if (Rt + 1 != Rt2 || (Rt & 1)) {
6280         return Error(Op2.getStartLoc(),
6281                      isLoad ? "destination operands must be sequential"
6282                             : "source operands must be sequential");
6283       }
6284       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6285           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6286       Operands[Idx] =
6287           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6288       Operands.erase(Operands.begin() + Idx + 1);
6289     }
6290   }
6291
6292   // GNU Assembler extension (compatibility).
6293   fixupGNULDRDAlias(Mnemonic, Operands);
6294
6295   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6296   // does not fit with other "subs" and tblgen.
6297   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6298   // so the Mnemonic is the original name "subs" and delete the predicate
6299   // operand so it will match the table entry.
6300   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6301       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6302       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6303       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6304       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6305       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6306     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6307     Operands.erase(Operands.begin() + 1);
6308   }
6309   return false;
6310 }
6311
6312 // Validate context-sensitive operand constraints.
6313
6314 // return 'true' if register list contains non-low GPR registers,
6315 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6316 // 'containsReg' to true.
6317 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6318                                  unsigned Reg, unsigned HiReg,
6319                                  bool &containsReg) {
6320   containsReg = false;
6321   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6322     unsigned OpReg = Inst.getOperand(i).getReg();
6323     if (OpReg == Reg)
6324       containsReg = true;
6325     // Anything other than a low register isn't legal here.
6326     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6327       return true;
6328   }
6329   return false;
6330 }
6331
6332 // Check if the specified regisgter is in the register list of the inst,
6333 // starting at the indicated operand number.
6334 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6335   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6336     unsigned OpReg = Inst.getOperand(i).getReg();
6337     if (OpReg == Reg)
6338       return true;
6339   }
6340   return false;
6341 }
6342
6343 // Return true if instruction has the interesting property of being
6344 // allowed in IT blocks, but not being predicable.
6345 static bool instIsBreakpoint(const MCInst &Inst) {
6346     return Inst.getOpcode() == ARM::tBKPT ||
6347            Inst.getOpcode() == ARM::BKPT ||
6348            Inst.getOpcode() == ARM::tHLT ||
6349            Inst.getOpcode() == ARM::HLT;
6350 }
6351
6352 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6353                                        const OperandVector &Operands,
6354                                        unsigned ListNo, bool IsARPop) {
6355   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6356   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6357
6358   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6359   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6360   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6361
6362   if (!IsARPop && ListContainsSP)
6363     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6364                  "SP may not be in the register list");
6365   else if (ListContainsPC && ListContainsLR)
6366     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6367                  "PC and LR may not be in the register list simultaneously");
6368   return false;
6369 }
6370
6371 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6372                                        const OperandVector &Operands,
6373                                        unsigned ListNo) {
6374   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6375   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6376
6377   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6378   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6379
6380   if (ListContainsSP && ListContainsPC)
6381     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6382                  "SP and PC may not be in the register list");
6383   else if (ListContainsSP)
6384     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6385                  "SP may not be in the register list");
6386   else if (ListContainsPC)
6387     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6388                  "PC may not be in the register list");
6389   return false;
6390 }
6391
6392 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
6393                                     const OperandVector &Operands,
6394                                     bool Load, bool ARMMode, bool Writeback) {
6395   unsigned RtIndex = Load || !Writeback ? 0 : 1;
6396   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
6397   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
6398
6399   if (ARMMode) {
6400     // Rt can't be R14.
6401     if (Rt == 14)
6402       return Error(Operands[3]->getStartLoc(),
6403                   "Rt can't be R14");
6404
6405     // Rt must be even-numbered.
6406     if ((Rt & 1) == 1)
6407       return Error(Operands[3]->getStartLoc(),
6408                    "Rt must be even-numbered");
6409
6410     // Rt2 must be Rt + 1.
6411     if (Rt2 != Rt + 1) {
6412       if (Load)
6413         return Error(Operands[3]->getStartLoc(),
6414                      "destination operands must be sequential");
6415       else
6416         return Error(Operands[3]->getStartLoc(),
6417                      "source operands must be sequential");
6418     }
6419
6420     // FIXME: Diagnose m == 15
6421     // FIXME: Diagnose ldrd with m == t || m == t2.
6422   }
6423
6424   if (!ARMMode && Load) {
6425     if (Rt2 == Rt)
6426       return Error(Operands[3]->getStartLoc(),
6427                    "destination operands can't be identical");
6428   }
6429
6430   if (Writeback) {
6431     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6432
6433     if (Rn == Rt || Rn == Rt2) {
6434       if (Load)
6435         return Error(Operands[3]->getStartLoc(),
6436                      "base register needs to be different from destination "
6437                      "registers");
6438       else
6439         return Error(Operands[3]->getStartLoc(),
6440                      "source register and base register can't be identical");
6441     }
6442
6443     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
6444     // (Except the immediate form of ldrd?)
6445   }
6446
6447   return false;
6448 }
6449
6450
6451 // FIXME: We would really like to be able to tablegen'erate this.
6452 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6453                                        const OperandVector &Operands) {
6454   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6455   SMLoc Loc = Operands[0]->getStartLoc();
6456
6457   // Check the IT block state first.
6458   // NOTE: BKPT and HLT instructions have the interesting property of being
6459   // allowed in IT blocks, but not being predicable. They just always execute.
6460   if (inITBlock() && !instIsBreakpoint(Inst)) {
6461     // The instruction must be predicable.
6462     if (!MCID.isPredicable())
6463       return Error(Loc, "instructions in IT block must be predicable");
6464     ARMCC::CondCodes Cond = ARMCC::CondCodes(
6465         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
6466     if (Cond != currentITCond()) {
6467       // Find the condition code Operand to get its SMLoc information.
6468       SMLoc CondLoc;
6469       for (unsigned I = 1; I < Operands.size(); ++I)
6470         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6471           CondLoc = Operands[I]->getStartLoc();
6472       return Error(CondLoc, "incorrect condition in IT block; got '" +
6473                                 StringRef(ARMCondCodeToString(Cond)) +
6474                                 "', but expected '" +
6475                                 ARMCondCodeToString(currentITCond()) + "'");
6476     }
6477   // Check for non-'al' condition codes outside of the IT block.
6478   } else if (isThumbTwo() && MCID.isPredicable() &&
6479              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6480              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6481              Inst.getOpcode() != ARM::t2Bcc) {
6482     return Error(Loc, "predicated instructions must be in IT block");
6483   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6484              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6485                  ARMCC::AL) {
6486     return Warning(Loc, "predicated instructions should be in IT block");
6487   } else if (!MCID.isPredicable()) {
6488     // Check the instruction doesn't have a predicate operand anyway
6489     // that it's not allowed to use. Sometimes this happens in order
6490     // to keep instructions the same shape even though one cannot
6491     // legally be predicated, e.g. vmul.f16 vs vmul.f32.
6492     for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
6493       if (MCID.OpInfo[i].isPredicate()) {
6494         if (Inst.getOperand(i).getImm() != ARMCC::AL)
6495           return Error(Loc, "instruction is not predicable");
6496         break;
6497       }
6498     }
6499   }
6500
6501   // PC-setting instructions in an IT block, but not the last instruction of
6502   // the block, are UNPREDICTABLE.
6503   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6504     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6505   }
6506
6507   const unsigned Opcode = Inst.getOpcode();
6508   switch (Opcode) {
6509   case ARM::t2IT: {
6510     // Encoding is unpredictable if it ever results in a notional 'NV'
6511     // predicate. Since we don't parse 'NV' directly this means an 'AL'
6512     // predicate with an "else" mask bit.
6513     unsigned Cond = Inst.getOperand(0).getImm();
6514     unsigned Mask = Inst.getOperand(1).getImm();
6515
6516     // Mask hasn't been modified to the IT instruction encoding yet so
6517     // conditions only allowing a 't' are a block of 1s starting at bit 3
6518     // followed by all 0s. Easiest way is to just list the 4 possibilities.
6519     if (Cond == ARMCC::AL && Mask != 8 && Mask != 12 && Mask != 14 &&
6520         Mask != 15)
6521       return Error(Loc, "unpredictable IT predicate sequence");
6522     break;
6523   }
6524   case ARM::LDRD:
6525     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
6526                          /*Writeback*/false))
6527       return true;
6528     break;
6529   case ARM::LDRD_PRE:
6530   case ARM::LDRD_POST:
6531     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
6532                          /*Writeback*/true))
6533       return true;
6534     break;
6535   case ARM::t2LDRDi8:
6536     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
6537                          /*Writeback*/false))
6538       return true;
6539     break;
6540   case ARM::t2LDRD_PRE:
6541   case ARM::t2LDRD_POST:
6542     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
6543                          /*Writeback*/true))
6544       return true;
6545     break;
6546   case ARM::t2BXJ: {
6547     const unsigned RmReg = Inst.getOperand(0).getReg();
6548     // Rm = SP is no longer unpredictable in v8-A
6549     if (RmReg == ARM::SP && !hasV8Ops())
6550       return Error(Operands[2]->getStartLoc(),
6551                    "r13 (SP) is an unpredictable operand to BXJ");
6552     return false;
6553   }
6554   case ARM::STRD:
6555     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
6556                          /*Writeback*/false))
6557       return true;
6558     break;
6559   case ARM::STRD_PRE:
6560   case ARM::STRD_POST:
6561     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
6562                          /*Writeback*/true))
6563       return true;
6564     break;
6565   case ARM::t2STRD_PRE:
6566   case ARM::t2STRD_POST:
6567     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
6568                          /*Writeback*/true))
6569       return true;
6570     break;
6571   case ARM::STR_PRE_IMM:
6572   case ARM::STR_PRE_REG:
6573   case ARM::t2STR_PRE:
6574   case ARM::STR_POST_IMM:
6575   case ARM::STR_POST_REG:
6576   case ARM::t2STR_POST:
6577   case ARM::STRH_PRE:
6578   case ARM::t2STRH_PRE:
6579   case ARM::STRH_POST:
6580   case ARM::t2STRH_POST:
6581   case ARM::STRB_PRE_IMM:
6582   case ARM::STRB_PRE_REG:
6583   case ARM::t2STRB_PRE:
6584   case ARM::STRB_POST_IMM:
6585   case ARM::STRB_POST_REG:
6586   case ARM::t2STRB_POST: {
6587     // Rt must be different from Rn.
6588     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6589     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6590
6591     if (Rt == Rn)
6592       return Error(Operands[3]->getStartLoc(),
6593                    "source register and base register can't be identical");
6594     return false;
6595   }
6596   case ARM::LDR_PRE_IMM:
6597   case ARM::LDR_PRE_REG:
6598   case ARM::t2LDR_PRE:
6599   case ARM::LDR_POST_IMM:
6600   case ARM::LDR_POST_REG:
6601   case ARM::t2LDR_POST:
6602   case ARM::LDRH_PRE:
6603   case ARM::t2LDRH_PRE:
6604   case ARM::LDRH_POST:
6605   case ARM::t2LDRH_POST:
6606   case ARM::LDRSH_PRE:
6607   case ARM::t2LDRSH_PRE:
6608   case ARM::LDRSH_POST:
6609   case ARM::t2LDRSH_POST:
6610   case ARM::LDRB_PRE_IMM:
6611   case ARM::LDRB_PRE_REG:
6612   case ARM::t2LDRB_PRE:
6613   case ARM::LDRB_POST_IMM:
6614   case ARM::LDRB_POST_REG:
6615   case ARM::t2LDRB_POST:
6616   case ARM::LDRSB_PRE:
6617   case ARM::t2LDRSB_PRE:
6618   case ARM::LDRSB_POST:
6619   case ARM::t2LDRSB_POST: {
6620     // Rt must be different from Rn.
6621     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6622     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6623
6624     if (Rt == Rn)
6625       return Error(Operands[3]->getStartLoc(),
6626                    "destination register and base register can't be identical");
6627     return false;
6628   }
6629   case ARM::SBFX:
6630   case ARM::t2SBFX:
6631   case ARM::UBFX:
6632   case ARM::t2UBFX: {
6633     // Width must be in range [1, 32-lsb].
6634     unsigned LSB = Inst.getOperand(2).getImm();
6635     unsigned Widthm1 = Inst.getOperand(3).getImm();
6636     if (Widthm1 >= 32 - LSB)
6637       return Error(Operands[5]->getStartLoc(),
6638                    "bitfield width must be in range [1,32-lsb]");
6639     return false;
6640   }
6641   // Notionally handles ARM::tLDMIA_UPD too.
6642   case ARM::tLDMIA: {
6643     // If we're parsing Thumb2, the .w variant is available and handles
6644     // most cases that are normally illegal for a Thumb1 LDM instruction.
6645     // We'll make the transformation in processInstruction() if necessary.
6646     //
6647     // Thumb LDM instructions are writeback iff the base register is not
6648     // in the register list.
6649     unsigned Rn = Inst.getOperand(0).getReg();
6650     bool HasWritebackToken =
6651         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6652          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6653     bool ListContainsBase;
6654     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6655       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6656                    "registers must be in range r0-r7");
6657     // If we should have writeback, then there should be a '!' token.
6658     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6659       return Error(Operands[2]->getStartLoc(),
6660                    "writeback operator '!' expected");
6661     // If we should not have writeback, there must not be a '!'. This is
6662     // true even for the 32-bit wide encodings.
6663     if (ListContainsBase && HasWritebackToken)
6664       return Error(Operands[3]->getStartLoc(),
6665                    "writeback operator '!' not allowed when base register "
6666                    "in register list");
6667
6668     if (validatetLDMRegList(Inst, Operands, 3))
6669       return true;
6670     break;
6671   }
6672   case ARM::LDMIA_UPD:
6673   case ARM::LDMDB_UPD:
6674   case ARM::LDMIB_UPD:
6675   case ARM::LDMDA_UPD:
6676     // ARM variants loading and updating the same register are only officially
6677     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6678     if (!hasV7Ops())
6679       break;
6680     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6681       return Error(Operands.back()->getStartLoc(),
6682                    "writeback register not allowed in register list");
6683     break;
6684   case ARM::t2LDMIA:
6685   case ARM::t2LDMDB:
6686     if (validatetLDMRegList(Inst, Operands, 3))
6687       return true;
6688     break;
6689   case ARM::t2STMIA:
6690   case ARM::t2STMDB:
6691     if (validatetSTMRegList(Inst, Operands, 3))
6692       return true;
6693     break;
6694   case ARM::t2LDMIA_UPD:
6695   case ARM::t2LDMDB_UPD:
6696   case ARM::t2STMIA_UPD:
6697   case ARM::t2STMDB_UPD:
6698     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6699       return Error(Operands.back()->getStartLoc(),
6700                    "writeback register not allowed in register list");
6701
6702     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6703       if (validatetLDMRegList(Inst, Operands, 3))
6704         return true;
6705     } else {
6706       if (validatetSTMRegList(Inst, Operands, 3))
6707         return true;
6708     }
6709     break;
6710
6711   case ARM::sysLDMIA_UPD:
6712   case ARM::sysLDMDA_UPD:
6713   case ARM::sysLDMDB_UPD:
6714   case ARM::sysLDMIB_UPD:
6715     if (!listContainsReg(Inst, 3, ARM::PC))
6716       return Error(Operands[4]->getStartLoc(),
6717                    "writeback register only allowed on system LDM "
6718                    "if PC in register-list");
6719     break;
6720   case ARM::sysSTMIA_UPD:
6721   case ARM::sysSTMDA_UPD:
6722   case ARM::sysSTMDB_UPD:
6723   case ARM::sysSTMIB_UPD:
6724     return Error(Operands[2]->getStartLoc(),
6725                  "system STM cannot have writeback register");
6726   case ARM::tMUL:
6727     // The second source operand must be the same register as the destination
6728     // operand.
6729     //
6730     // In this case, we must directly check the parsed operands because the
6731     // cvtThumbMultiply() function is written in such a way that it guarantees
6732     // this first statement is always true for the new Inst.  Essentially, the
6733     // destination is unconditionally copied into the second source operand
6734     // without checking to see if it matches what we actually parsed.
6735     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6736                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6737         (((ARMOperand &)*Operands[3]).getReg() !=
6738          ((ARMOperand &)*Operands[4]).getReg())) {
6739       return Error(Operands[3]->getStartLoc(),
6740                    "destination register must match source register");
6741     }
6742     break;
6743
6744   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6745   // so only issue a diagnostic for thumb1. The instructions will be
6746   // switched to the t2 encodings in processInstruction() if necessary.
6747   case ARM::tPOP: {
6748     bool ListContainsBase;
6749     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6750         !isThumbTwo())
6751       return Error(Operands[2]->getStartLoc(),
6752                    "registers must be in range r0-r7 or pc");
6753     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6754       return true;
6755     break;
6756   }
6757   case ARM::tPUSH: {
6758     bool ListContainsBase;
6759     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6760         !isThumbTwo())
6761       return Error(Operands[2]->getStartLoc(),
6762                    "registers must be in range r0-r7 or lr");
6763     if (validatetSTMRegList(Inst, Operands, 2))
6764       return true;
6765     break;
6766   }
6767   case ARM::tSTMIA_UPD: {
6768     bool ListContainsBase, InvalidLowList;
6769     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6770                                           0, ListContainsBase);
6771     if (InvalidLowList && !isThumbTwo())
6772       return Error(Operands[4]->getStartLoc(),
6773                    "registers must be in range r0-r7");
6774
6775     // This would be converted to a 32-bit stm, but that's not valid if the
6776     // writeback register is in the list.
6777     if (InvalidLowList && ListContainsBase)
6778       return Error(Operands[4]->getStartLoc(),
6779                    "writeback operator '!' not allowed when base register "
6780                    "in register list");
6781
6782     if (validatetSTMRegList(Inst, Operands, 4))
6783       return true;
6784     break;
6785   }
6786   case ARM::tADDrSP:
6787     // If the non-SP source operand and the destination operand are not the
6788     // same, we need thumb2 (for the wide encoding), or we have an error.
6789     if (!isThumbTwo() &&
6790         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6791       return Error(Operands[4]->getStartLoc(),
6792                    "source register must be the same as destination");
6793     }
6794     break;
6795
6796   case ARM::t2ADDri:
6797   case ARM::t2ADDri12:
6798   case ARM::t2ADDrr:
6799   case ARM::t2ADDrs:
6800   case ARM::t2SUBri:
6801   case ARM::t2SUBri12:
6802   case ARM::t2SUBrr:
6803   case ARM::t2SUBrs:
6804     if (Inst.getOperand(0).getReg() == ARM::SP &&
6805         Inst.getOperand(1).getReg() != ARM::SP)
6806       return Error(Operands[4]->getStartLoc(),
6807                    "source register must be sp if destination is sp");
6808     break;
6809
6810   // Final range checking for Thumb unconditional branch instructions.
6811   case ARM::tB:
6812     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6813       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6814     break;
6815   case ARM::t2B: {
6816     int op = (Operands[2]->isImm()) ? 2 : 3;
6817     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6818       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6819     break;
6820   }
6821   // Final range checking for Thumb conditional branch instructions.
6822   case ARM::tBcc:
6823     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6824       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6825     break;
6826   case ARM::t2Bcc: {
6827     int Op = (Operands[2]->isImm()) ? 2 : 3;
6828     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6829       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6830     break;
6831   }
6832   case ARM::tCBZ:
6833   case ARM::tCBNZ: {
6834     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6835       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6836     break;
6837   }
6838   case ARM::MOVi16:
6839   case ARM::MOVTi16:
6840   case ARM::t2MOVi16:
6841   case ARM::t2MOVTi16:
6842     {
6843     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6844     // especially when we turn it into a movw and the expression <symbol> does
6845     // not have a :lower16: or :upper16 as part of the expression.  We don't
6846     // want the behavior of silently truncating, which can be unexpected and
6847     // lead to bugs that are difficult to find since this is an easy mistake
6848     // to make.
6849     int i = (Operands[3]->isImm()) ? 3 : 4;
6850     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6851     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6852     if (CE) break;
6853     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6854     if (!E) break;
6855     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6856     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6857                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6858       return Error(
6859           Op.getStartLoc(),
6860           "immediate expression for mov requires :lower16: or :upper16");
6861     break;
6862   }
6863   case ARM::HINT:
6864   case ARM::t2HINT: {
6865     unsigned Imm8 = Inst.getOperand(0).getImm();
6866     unsigned Pred = Inst.getOperand(1).getImm();
6867     // ESB is not predicable (pred must be AL). Without the RAS extension, this
6868     // behaves as any other unallocated hint.
6869     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
6870       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6871                                                "predicable, but condition "
6872                                                "code specified");
6873     if (Imm8 == 0x14 && Pred != ARMCC::AL)
6874       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
6875                                                "predicable, but condition "
6876                                                "code specified");
6877     break;
6878   }
6879   case ARM::DSB:
6880   case ARM::t2DSB: {
6881
6882     if (Inst.getNumOperands() < 2)
6883       break;
6884
6885     unsigned Option = Inst.getOperand(0).getImm();
6886     unsigned Pred = Inst.getOperand(1).getImm();
6887
6888     // SSBB and PSSBB (DSB #0|#4) are not predicable (pred must be AL).
6889     if (Option == 0 && Pred != ARMCC::AL)
6890       return Error(Operands[1]->getStartLoc(),
6891                    "instruction 'ssbb' is not predicable, but condition code "
6892                    "specified");
6893     if (Option == 4 && Pred != ARMCC::AL)
6894       return Error(Operands[1]->getStartLoc(),
6895                    "instruction 'pssbb' is not predicable, but condition code "
6896                    "specified");
6897     break;
6898   }
6899   case ARM::VMOVRRS: {
6900     // Source registers must be sequential.
6901     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6902     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6903     if (Sm1 != Sm + 1)
6904       return Error(Operands[5]->getStartLoc(),
6905                    "source operands must be sequential");
6906     break;
6907   }
6908   case ARM::VMOVSRR: {
6909     // Destination registers must be sequential.
6910     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6911     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6912     if (Sm1 != Sm + 1)
6913       return Error(Operands[3]->getStartLoc(),
6914                    "destination operands must be sequential");
6915     break;
6916   }
6917   case ARM::VLDMDIA:
6918   case ARM::VSTMDIA: {
6919     ARMOperand &Op = static_cast<ARMOperand&>(*Operands[3]);
6920     auto &RegList = Op.getRegList();
6921     if (RegList.size() < 1 || RegList.size() > 16)
6922       return Error(Operands[3]->getStartLoc(),
6923                    "list of registers must be at least 1 and at most 16");
6924     break;
6925   }
6926   }
6927
6928   return false;
6929 }
6930
6931 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6932   switch(Opc) {
6933   default: llvm_unreachable("unexpected opcode!");
6934   // VST1LN
6935   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6936   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6937   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6938   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6939   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6940   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6941   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6942   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6943   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6944
6945   // VST2LN
6946   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6947   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6948   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6949   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6950   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6951
6952   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6953   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6954   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6955   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6956   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6957
6958   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6959   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6960   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6961   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6962   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6963
6964   // VST3LN
6965   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6966   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6967   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6968   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6969   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6970   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6971   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6972   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6973   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6974   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6975   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6976   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6977   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6978   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6979   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6980
6981   // VST3
6982   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6983   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6984   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6985   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6986   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6987   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6988   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6989   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6990   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6991   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6992   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6993   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6994   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6995   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6996   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6997   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6998   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6999   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
7000
7001   // VST4LN
7002   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
7003   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
7004   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
7005   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
7006   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
7007   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
7008   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
7009   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
7010   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
7011   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
7012   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
7013   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
7014   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
7015   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
7016   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
7017
7018   // VST4
7019   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
7020   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
7021   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
7022   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
7023   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
7024   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
7025   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
7026   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
7027   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
7028   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
7029   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
7030   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
7031   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
7032   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
7033   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
7034   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
7035   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
7036   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
7037   }
7038 }
7039
7040 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
7041   switch(Opc) {
7042   default: llvm_unreachable("unexpected opcode!");
7043   // VLD1LN
7044   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
7045   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
7046   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
7047   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
7048   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
7049   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
7050   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
7051   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
7052   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
7053
7054   // VLD2LN
7055   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
7056   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
7057   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
7058   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
7059   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
7060   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
7061   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
7062   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
7063   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
7064   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
7065   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
7066   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
7067   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
7068   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
7069   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
7070
7071   // VLD3DUP
7072   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
7073   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
7074   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
7075   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
7076   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
7077   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
7078   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
7079   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
7080   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
7081   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
7082   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
7083   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
7084   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
7085   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
7086   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
7087   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
7088   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
7089   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
7090
7091   // VLD3LN
7092   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
7093   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
7094   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
7095   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
7096   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
7097   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
7098   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
7099   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
7100   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
7101   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
7102   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
7103   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
7104   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
7105   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
7106   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
7107
7108   // VLD3
7109   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
7110   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
7111   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
7112   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
7113   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
7114   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
7115   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
7116   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
7117   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
7118   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
7119   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
7120   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
7121   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
7122   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
7123   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
7124   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
7125   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
7126   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
7127
7128   // VLD4LN
7129   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
7130   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
7131   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
7132   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
7133   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
7134   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
7135   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
7136   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
7137   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
7138   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
7139   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
7140   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
7141   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
7142   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
7143   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
7144
7145   // VLD4DUP
7146   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
7147   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
7148   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
7149   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
7150   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
7151   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
7152   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
7153   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
7154   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
7155   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
7156   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
7157   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
7158   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
7159   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
7160   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
7161   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
7162   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
7163   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
7164
7165   // VLD4
7166   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
7167   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
7168   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
7169   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
7170   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
7171   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
7172   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
7173   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
7174   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
7175   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
7176   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
7177   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
7178   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
7179   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
7180   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
7181   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
7182   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
7183   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
7184   }
7185 }
7186
7187 bool ARMAsmParser::processInstruction(MCInst &Inst,
7188                                       const OperandVector &Operands,
7189                                       MCStreamer &Out) {
7190   // Check if we have the wide qualifier, because if it's present we
7191   // must avoid selecting a 16-bit thumb instruction.
7192   bool HasWideQualifier = false;
7193   for (auto &Op : Operands) {
7194     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
7195     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
7196       HasWideQualifier = true;
7197       break;
7198     }
7199   }
7200
7201   switch (Inst.getOpcode()) {
7202   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
7203   case ARM::LDRT_POST:
7204   case ARM::LDRBT_POST: {
7205     const unsigned Opcode =
7206       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
7207                                            : ARM::LDRBT_POST_IMM;
7208     MCInst TmpInst;
7209     TmpInst.setOpcode(Opcode);
7210     TmpInst.addOperand(Inst.getOperand(0));
7211     TmpInst.addOperand(Inst.getOperand(1));
7212     TmpInst.addOperand(Inst.getOperand(1));
7213     TmpInst.addOperand(MCOperand::createReg(0));
7214     TmpInst.addOperand(MCOperand::createImm(0));
7215     TmpInst.addOperand(Inst.getOperand(2));
7216     TmpInst.addOperand(Inst.getOperand(3));
7217     Inst = TmpInst;
7218     return true;
7219   }
7220   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
7221   case ARM::STRT_POST:
7222   case ARM::STRBT_POST: {
7223     const unsigned Opcode =
7224       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
7225                                            : ARM::STRBT_POST_IMM;
7226     MCInst TmpInst;
7227     TmpInst.setOpcode(Opcode);
7228     TmpInst.addOperand(Inst.getOperand(1));
7229     TmpInst.addOperand(Inst.getOperand(0));
7230     TmpInst.addOperand(Inst.getOperand(1));
7231     TmpInst.addOperand(MCOperand::createReg(0));
7232     TmpInst.addOperand(MCOperand::createImm(0));
7233     TmpInst.addOperand(Inst.getOperand(2));
7234     TmpInst.addOperand(Inst.getOperand(3));
7235     Inst = TmpInst;
7236     return true;
7237   }
7238   // Alias for alternate form of 'ADR Rd, #imm' instruction.
7239   case ARM::ADDri: {
7240     if (Inst.getOperand(1).getReg() != ARM::PC ||
7241         Inst.getOperand(5).getReg() != 0 ||
7242         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
7243       return false;
7244     MCInst TmpInst;
7245     TmpInst.setOpcode(ARM::ADR);
7246     TmpInst.addOperand(Inst.getOperand(0));
7247     if (Inst.getOperand(2).isImm()) {
7248       // Immediate (mod_imm) will be in its encoded form, we must unencode it
7249       // before passing it to the ADR instruction.
7250       unsigned Enc = Inst.getOperand(2).getImm();
7251       TmpInst.addOperand(MCOperand::createImm(
7252         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
7253     } else {
7254       // Turn PC-relative expression into absolute expression.
7255       // Reading PC provides the start of the current instruction + 8 and
7256       // the transform to adr is biased by that.
7257       MCSymbol *Dot = getContext().createTempSymbol();
7258       Out.EmitLabel(Dot);
7259       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
7260       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
7261                                                      MCSymbolRefExpr::VK_None,
7262                                                      getContext());
7263       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
7264       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
7265                                                      getContext());
7266       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
7267                                                         getContext());
7268       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
7269     }
7270     TmpInst.addOperand(Inst.getOperand(3));
7271     TmpInst.addOperand(Inst.getOperand(4));
7272     Inst = TmpInst;
7273     return true;
7274   }
7275   // Aliases for alternate PC+imm syntax of LDR instructions.
7276   case ARM::t2LDRpcrel:
7277     // Select the narrow version if the immediate will fit.
7278     if (Inst.getOperand(1).getImm() > 0 &&
7279         Inst.getOperand(1).getImm() <= 0xff &&
7280         !HasWideQualifier)
7281       Inst.setOpcode(ARM::tLDRpci);
7282     else
7283       Inst.setOpcode(ARM::t2LDRpci);
7284     return true;
7285   case ARM::t2LDRBpcrel:
7286     Inst.setOpcode(ARM::t2LDRBpci);
7287     return true;
7288   case ARM::t2LDRHpcrel:
7289     Inst.setOpcode(ARM::t2LDRHpci);
7290     return true;
7291   case ARM::t2LDRSBpcrel:
7292     Inst.setOpcode(ARM::t2LDRSBpci);
7293     return true;
7294   case ARM::t2LDRSHpcrel:
7295     Inst.setOpcode(ARM::t2LDRSHpci);
7296     return true;
7297   case ARM::LDRConstPool:
7298   case ARM::tLDRConstPool:
7299   case ARM::t2LDRConstPool: {
7300     // Pseudo instruction ldr rt, =immediate is converted to a
7301     // MOV rt, immediate if immediate is known and representable
7302     // otherwise we create a constant pool entry that we load from.
7303     MCInst TmpInst;
7304     if (Inst.getOpcode() == ARM::LDRConstPool)
7305       TmpInst.setOpcode(ARM::LDRi12);
7306     else if (Inst.getOpcode() == ARM::tLDRConstPool)
7307       TmpInst.setOpcode(ARM::tLDRpci);
7308     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
7309       TmpInst.setOpcode(ARM::t2LDRpci);
7310     const ARMOperand &PoolOperand =
7311       (HasWideQualifier ?
7312        static_cast<ARMOperand &>(*Operands[4]) :
7313        static_cast<ARMOperand &>(*Operands[3]));
7314     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
7315     // If SubExprVal is a constant we may be able to use a MOV
7316     if (isa<MCConstantExpr>(SubExprVal) &&
7317         Inst.getOperand(0).getReg() != ARM::PC &&
7318         Inst.getOperand(0).getReg() != ARM::SP) {
7319       int64_t Value =
7320         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
7321       bool UseMov  = true;
7322       bool MovHasS = true;
7323       if (Inst.getOpcode() == ARM::LDRConstPool) {
7324         // ARM Constant
7325         if (ARM_AM::getSOImmVal(Value) != -1) {
7326           Value = ARM_AM::getSOImmVal(Value);
7327           TmpInst.setOpcode(ARM::MOVi);
7328         }
7329         else if (ARM_AM::getSOImmVal(~Value) != -1) {
7330           Value = ARM_AM::getSOImmVal(~Value);
7331           TmpInst.setOpcode(ARM::MVNi);
7332         }
7333         else if (hasV6T2Ops() &&
7334                  Value >=0 && Value < 65536) {
7335           TmpInst.setOpcode(ARM::MOVi16);
7336           MovHasS = false;
7337         }
7338         else
7339           UseMov = false;
7340       }
7341       else {
7342         // Thumb/Thumb2 Constant
7343         if (hasThumb2() &&
7344             ARM_AM::getT2SOImmVal(Value) != -1)
7345           TmpInst.setOpcode(ARM::t2MOVi);
7346         else if (hasThumb2() &&
7347                  ARM_AM::getT2SOImmVal(~Value) != -1) {
7348           TmpInst.setOpcode(ARM::t2MVNi);
7349           Value = ~Value;
7350         }
7351         else if (hasV8MBaseline() &&
7352                  Value >=0 && Value < 65536) {
7353           TmpInst.setOpcode(ARM::t2MOVi16);
7354           MovHasS = false;
7355         }
7356         else
7357           UseMov = false;
7358       }
7359       if (UseMov) {
7360         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7361         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7362         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7363         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7364         if (MovHasS)
7365           TmpInst.addOperand(MCOperand::createReg(0));    // S
7366         Inst = TmpInst;
7367         return true;
7368       }
7369     }
7370     // No opportunity to use MOV/MVN create constant pool
7371     const MCExpr *CPLoc =
7372       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7373                                                PoolOperand.getStartLoc());
7374     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7375     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7376     if (TmpInst.getOpcode() == ARM::LDRi12)
7377       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7378     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7379     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7380     Inst = TmpInst;
7381     return true;
7382   }
7383   // Handle NEON VST complex aliases.
7384   case ARM::VST1LNdWB_register_Asm_8:
7385   case ARM::VST1LNdWB_register_Asm_16:
7386   case ARM::VST1LNdWB_register_Asm_32: {
7387     MCInst TmpInst;
7388     // Shuffle the operands around so the lane index operand is in the
7389     // right place.
7390     unsigned Spacing;
7391     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7392     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7393     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7394     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7395     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7396     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7397     TmpInst.addOperand(Inst.getOperand(1)); // lane
7398     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7399     TmpInst.addOperand(Inst.getOperand(6));
7400     Inst = TmpInst;
7401     return true;
7402   }
7403
7404   case ARM::VST2LNdWB_register_Asm_8:
7405   case ARM::VST2LNdWB_register_Asm_16:
7406   case ARM::VST2LNdWB_register_Asm_32:
7407   case ARM::VST2LNqWB_register_Asm_16:
7408   case ARM::VST2LNqWB_register_Asm_32: {
7409     MCInst TmpInst;
7410     // Shuffle the operands around so the lane index operand is in the
7411     // right place.
7412     unsigned Spacing;
7413     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7414     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7415     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7416     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7417     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7418     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7419     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7420                                             Spacing));
7421     TmpInst.addOperand(Inst.getOperand(1)); // lane
7422     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7423     TmpInst.addOperand(Inst.getOperand(6));
7424     Inst = TmpInst;
7425     return true;
7426   }
7427
7428   case ARM::VST3LNdWB_register_Asm_8:
7429   case ARM::VST3LNdWB_register_Asm_16:
7430   case ARM::VST3LNdWB_register_Asm_32:
7431   case ARM::VST3LNqWB_register_Asm_16:
7432   case ARM::VST3LNqWB_register_Asm_32: {
7433     MCInst TmpInst;
7434     // Shuffle the operands around so the lane index operand is in the
7435     // right place.
7436     unsigned Spacing;
7437     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7438     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7439     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7440     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7441     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7442     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7443     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7444                                             Spacing));
7445     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7446                                             Spacing * 2));
7447     TmpInst.addOperand(Inst.getOperand(1)); // lane
7448     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7449     TmpInst.addOperand(Inst.getOperand(6));
7450     Inst = TmpInst;
7451     return true;
7452   }
7453
7454   case ARM::VST4LNdWB_register_Asm_8:
7455   case ARM::VST4LNdWB_register_Asm_16:
7456   case ARM::VST4LNdWB_register_Asm_32:
7457   case ARM::VST4LNqWB_register_Asm_16:
7458   case ARM::VST4LNqWB_register_Asm_32: {
7459     MCInst TmpInst;
7460     // Shuffle the operands around so the lane index operand is in the
7461     // right place.
7462     unsigned Spacing;
7463     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7464     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7465     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7466     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7467     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7468     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7469     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7470                                             Spacing));
7471     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7472                                             Spacing * 2));
7473     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7474                                             Spacing * 3));
7475     TmpInst.addOperand(Inst.getOperand(1)); // lane
7476     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7477     TmpInst.addOperand(Inst.getOperand(6));
7478     Inst = TmpInst;
7479     return true;
7480   }
7481
7482   case ARM::VST1LNdWB_fixed_Asm_8:
7483   case ARM::VST1LNdWB_fixed_Asm_16:
7484   case ARM::VST1LNdWB_fixed_Asm_32: {
7485     MCInst TmpInst;
7486     // Shuffle the operands around so the lane index operand is in the
7487     // right place.
7488     unsigned Spacing;
7489     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7490     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7491     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7492     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7493     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7494     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7495     TmpInst.addOperand(Inst.getOperand(1)); // lane
7496     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7497     TmpInst.addOperand(Inst.getOperand(5));
7498     Inst = TmpInst;
7499     return true;
7500   }
7501
7502   case ARM::VST2LNdWB_fixed_Asm_8:
7503   case ARM::VST2LNdWB_fixed_Asm_16:
7504   case ARM::VST2LNdWB_fixed_Asm_32:
7505   case ARM::VST2LNqWB_fixed_Asm_16:
7506   case ARM::VST2LNqWB_fixed_Asm_32: {
7507     MCInst TmpInst;
7508     // Shuffle the operands around so the lane index operand is in the
7509     // right place.
7510     unsigned Spacing;
7511     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7512     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7513     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7514     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7515     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7516     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7517     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7518                                             Spacing));
7519     TmpInst.addOperand(Inst.getOperand(1)); // lane
7520     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7521     TmpInst.addOperand(Inst.getOperand(5));
7522     Inst = TmpInst;
7523     return true;
7524   }
7525
7526   case ARM::VST3LNdWB_fixed_Asm_8:
7527   case ARM::VST3LNdWB_fixed_Asm_16:
7528   case ARM::VST3LNdWB_fixed_Asm_32:
7529   case ARM::VST3LNqWB_fixed_Asm_16:
7530   case ARM::VST3LNqWB_fixed_Asm_32: {
7531     MCInst TmpInst;
7532     // Shuffle the operands around so the lane index operand is in the
7533     // right place.
7534     unsigned Spacing;
7535     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7536     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7537     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7538     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7539     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7540     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7541     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7542                                             Spacing));
7543     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7544                                             Spacing * 2));
7545     TmpInst.addOperand(Inst.getOperand(1)); // lane
7546     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7547     TmpInst.addOperand(Inst.getOperand(5));
7548     Inst = TmpInst;
7549     return true;
7550   }
7551
7552   case ARM::VST4LNdWB_fixed_Asm_8:
7553   case ARM::VST4LNdWB_fixed_Asm_16:
7554   case ARM::VST4LNdWB_fixed_Asm_32:
7555   case ARM::VST4LNqWB_fixed_Asm_16:
7556   case ARM::VST4LNqWB_fixed_Asm_32: {
7557     MCInst TmpInst;
7558     // Shuffle the operands around so the lane index operand is in the
7559     // right place.
7560     unsigned Spacing;
7561     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7562     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7563     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7564     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7565     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7566     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7567     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7568                                             Spacing));
7569     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7570                                             Spacing * 2));
7571     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7572                                             Spacing * 3));
7573     TmpInst.addOperand(Inst.getOperand(1)); // lane
7574     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7575     TmpInst.addOperand(Inst.getOperand(5));
7576     Inst = TmpInst;
7577     return true;
7578   }
7579
7580   case ARM::VST1LNdAsm_8:
7581   case ARM::VST1LNdAsm_16:
7582   case ARM::VST1LNdAsm_32: {
7583     MCInst TmpInst;
7584     // Shuffle the operands around so the lane index operand is in the
7585     // right place.
7586     unsigned Spacing;
7587     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7588     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7589     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7590     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7591     TmpInst.addOperand(Inst.getOperand(1)); // lane
7592     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7593     TmpInst.addOperand(Inst.getOperand(5));
7594     Inst = TmpInst;
7595     return true;
7596   }
7597
7598   case ARM::VST2LNdAsm_8:
7599   case ARM::VST2LNdAsm_16:
7600   case ARM::VST2LNdAsm_32:
7601   case ARM::VST2LNqAsm_16:
7602   case ARM::VST2LNqAsm_32: {
7603     MCInst TmpInst;
7604     // Shuffle the operands around so the lane index operand is in the
7605     // right place.
7606     unsigned Spacing;
7607     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7608     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7609     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7610     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7611     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7612                                             Spacing));
7613     TmpInst.addOperand(Inst.getOperand(1)); // lane
7614     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7615     TmpInst.addOperand(Inst.getOperand(5));
7616     Inst = TmpInst;
7617     return true;
7618   }
7619
7620   case ARM::VST3LNdAsm_8:
7621   case ARM::VST3LNdAsm_16:
7622   case ARM::VST3LNdAsm_32:
7623   case ARM::VST3LNqAsm_16:
7624   case ARM::VST3LNqAsm_32: {
7625     MCInst TmpInst;
7626     // Shuffle the operands around so the lane index operand is in the
7627     // right place.
7628     unsigned Spacing;
7629     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7630     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7631     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7632     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7633     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7634                                             Spacing));
7635     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7636                                             Spacing * 2));
7637     TmpInst.addOperand(Inst.getOperand(1)); // lane
7638     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7639     TmpInst.addOperand(Inst.getOperand(5));
7640     Inst = TmpInst;
7641     return true;
7642   }
7643
7644   case ARM::VST4LNdAsm_8:
7645   case ARM::VST4LNdAsm_16:
7646   case ARM::VST4LNdAsm_32:
7647   case ARM::VST4LNqAsm_16:
7648   case ARM::VST4LNqAsm_32: {
7649     MCInst TmpInst;
7650     // Shuffle the operands around so the lane index operand is in the
7651     // right place.
7652     unsigned Spacing;
7653     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7654     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7655     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7656     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7657     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7658                                             Spacing));
7659     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7660                                             Spacing * 2));
7661     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7662                                             Spacing * 3));
7663     TmpInst.addOperand(Inst.getOperand(1)); // lane
7664     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7665     TmpInst.addOperand(Inst.getOperand(5));
7666     Inst = TmpInst;
7667     return true;
7668   }
7669
7670   // Handle NEON VLD complex aliases.
7671   case ARM::VLD1LNdWB_register_Asm_8:
7672   case ARM::VLD1LNdWB_register_Asm_16:
7673   case ARM::VLD1LNdWB_register_Asm_32: {
7674     MCInst TmpInst;
7675     // Shuffle the operands around so the lane index operand is in the
7676     // right place.
7677     unsigned Spacing;
7678     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7679     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7680     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7681     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7682     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7683     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7684     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7685     TmpInst.addOperand(Inst.getOperand(1)); // lane
7686     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7687     TmpInst.addOperand(Inst.getOperand(6));
7688     Inst = TmpInst;
7689     return true;
7690   }
7691
7692   case ARM::VLD2LNdWB_register_Asm_8:
7693   case ARM::VLD2LNdWB_register_Asm_16:
7694   case ARM::VLD2LNdWB_register_Asm_32:
7695   case ARM::VLD2LNqWB_register_Asm_16:
7696   case ARM::VLD2LNqWB_register_Asm_32: {
7697     MCInst TmpInst;
7698     // Shuffle the operands around so the lane index operand is in the
7699     // right place.
7700     unsigned Spacing;
7701     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7702     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7703     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7704                                             Spacing));
7705     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7706     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7707     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7708     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7709     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7710     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7711                                             Spacing));
7712     TmpInst.addOperand(Inst.getOperand(1)); // lane
7713     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7714     TmpInst.addOperand(Inst.getOperand(6));
7715     Inst = TmpInst;
7716     return true;
7717   }
7718
7719   case ARM::VLD3LNdWB_register_Asm_8:
7720   case ARM::VLD3LNdWB_register_Asm_16:
7721   case ARM::VLD3LNdWB_register_Asm_32:
7722   case ARM::VLD3LNqWB_register_Asm_16:
7723   case ARM::VLD3LNqWB_register_Asm_32: {
7724     MCInst TmpInst;
7725     // Shuffle the operands around so the lane index operand is in the
7726     // right place.
7727     unsigned Spacing;
7728     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7729     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7730     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7731                                             Spacing));
7732     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7733                                             Spacing * 2));
7734     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7735     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7736     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7737     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7738     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7739     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7740                                             Spacing));
7741     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7742                                             Spacing * 2));
7743     TmpInst.addOperand(Inst.getOperand(1)); // lane
7744     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7745     TmpInst.addOperand(Inst.getOperand(6));
7746     Inst = TmpInst;
7747     return true;
7748   }
7749
7750   case ARM::VLD4LNdWB_register_Asm_8:
7751   case ARM::VLD4LNdWB_register_Asm_16:
7752   case ARM::VLD4LNdWB_register_Asm_32:
7753   case ARM::VLD4LNqWB_register_Asm_16:
7754   case ARM::VLD4LNqWB_register_Asm_32: {
7755     MCInst TmpInst;
7756     // Shuffle the operands around so the lane index operand is in the
7757     // right place.
7758     unsigned Spacing;
7759     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7760     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7761     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7762                                             Spacing));
7763     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7764                                             Spacing * 2));
7765     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7766                                             Spacing * 3));
7767     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7768     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7769     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7770     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7771     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7772     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7773                                             Spacing));
7774     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7775                                             Spacing * 2));
7776     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7777                                             Spacing * 3));
7778     TmpInst.addOperand(Inst.getOperand(1)); // lane
7779     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7780     TmpInst.addOperand(Inst.getOperand(6));
7781     Inst = TmpInst;
7782     return true;
7783   }
7784
7785   case ARM::VLD1LNdWB_fixed_Asm_8:
7786   case ARM::VLD1LNdWB_fixed_Asm_16:
7787   case ARM::VLD1LNdWB_fixed_Asm_32: {
7788     MCInst TmpInst;
7789     // Shuffle the operands around so the lane index operand is in the
7790     // right place.
7791     unsigned Spacing;
7792     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7793     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7794     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7795     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7796     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7797     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7798     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7799     TmpInst.addOperand(Inst.getOperand(1)); // lane
7800     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7801     TmpInst.addOperand(Inst.getOperand(5));
7802     Inst = TmpInst;
7803     return true;
7804   }
7805
7806   case ARM::VLD2LNdWB_fixed_Asm_8:
7807   case ARM::VLD2LNdWB_fixed_Asm_16:
7808   case ARM::VLD2LNdWB_fixed_Asm_32:
7809   case ARM::VLD2LNqWB_fixed_Asm_16:
7810   case ARM::VLD2LNqWB_fixed_Asm_32: {
7811     MCInst TmpInst;
7812     // Shuffle the operands around so the lane index operand is in the
7813     // right place.
7814     unsigned Spacing;
7815     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7816     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7817     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7818                                             Spacing));
7819     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7820     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7821     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7822     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7823     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7824     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7825                                             Spacing));
7826     TmpInst.addOperand(Inst.getOperand(1)); // lane
7827     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7828     TmpInst.addOperand(Inst.getOperand(5));
7829     Inst = TmpInst;
7830     return true;
7831   }
7832
7833   case ARM::VLD3LNdWB_fixed_Asm_8:
7834   case ARM::VLD3LNdWB_fixed_Asm_16:
7835   case ARM::VLD3LNdWB_fixed_Asm_32:
7836   case ARM::VLD3LNqWB_fixed_Asm_16:
7837   case ARM::VLD3LNqWB_fixed_Asm_32: {
7838     MCInst TmpInst;
7839     // Shuffle the operands around so the lane index operand is in the
7840     // right place.
7841     unsigned Spacing;
7842     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7843     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7844     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7845                                             Spacing));
7846     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7847                                             Spacing * 2));
7848     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7849     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7850     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7851     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7852     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7853     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7854                                             Spacing));
7855     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7856                                             Spacing * 2));
7857     TmpInst.addOperand(Inst.getOperand(1)); // lane
7858     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7859     TmpInst.addOperand(Inst.getOperand(5));
7860     Inst = TmpInst;
7861     return true;
7862   }
7863
7864   case ARM::VLD4LNdWB_fixed_Asm_8:
7865   case ARM::VLD4LNdWB_fixed_Asm_16:
7866   case ARM::VLD4LNdWB_fixed_Asm_32:
7867   case ARM::VLD4LNqWB_fixed_Asm_16:
7868   case ARM::VLD4LNqWB_fixed_Asm_32: {
7869     MCInst TmpInst;
7870     // Shuffle the operands around so the lane index operand is in the
7871     // right place.
7872     unsigned Spacing;
7873     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7874     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7875     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7876                                             Spacing));
7877     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7878                                             Spacing * 2));
7879     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7880                                             Spacing * 3));
7881     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7882     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7883     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7884     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7885     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7886     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7887                                             Spacing));
7888     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7889                                             Spacing * 2));
7890     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7891                                             Spacing * 3));
7892     TmpInst.addOperand(Inst.getOperand(1)); // lane
7893     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7894     TmpInst.addOperand(Inst.getOperand(5));
7895     Inst = TmpInst;
7896     return true;
7897   }
7898
7899   case ARM::VLD1LNdAsm_8:
7900   case ARM::VLD1LNdAsm_16:
7901   case ARM::VLD1LNdAsm_32: {
7902     MCInst TmpInst;
7903     // Shuffle the operands around so the lane index operand is in the
7904     // right place.
7905     unsigned Spacing;
7906     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7907     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7908     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7909     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7910     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7911     TmpInst.addOperand(Inst.getOperand(1)); // lane
7912     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7913     TmpInst.addOperand(Inst.getOperand(5));
7914     Inst = TmpInst;
7915     return true;
7916   }
7917
7918   case ARM::VLD2LNdAsm_8:
7919   case ARM::VLD2LNdAsm_16:
7920   case ARM::VLD2LNdAsm_32:
7921   case ARM::VLD2LNqAsm_16:
7922   case ARM::VLD2LNqAsm_32: {
7923     MCInst TmpInst;
7924     // Shuffle the operands around so the lane index operand is in the
7925     // right place.
7926     unsigned Spacing;
7927     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7928     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7929     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7930                                             Spacing));
7931     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7932     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7933     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7934     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7935                                             Spacing));
7936     TmpInst.addOperand(Inst.getOperand(1)); // lane
7937     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7938     TmpInst.addOperand(Inst.getOperand(5));
7939     Inst = TmpInst;
7940     return true;
7941   }
7942
7943   case ARM::VLD3LNdAsm_8:
7944   case ARM::VLD3LNdAsm_16:
7945   case ARM::VLD3LNdAsm_32:
7946   case ARM::VLD3LNqAsm_16:
7947   case ARM::VLD3LNqAsm_32: {
7948     MCInst TmpInst;
7949     // Shuffle the operands around so the lane index operand is in the
7950     // right place.
7951     unsigned Spacing;
7952     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7953     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7954     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7955                                             Spacing));
7956     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7957                                             Spacing * 2));
7958     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7959     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7960     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7961     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7962                                             Spacing));
7963     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7964                                             Spacing * 2));
7965     TmpInst.addOperand(Inst.getOperand(1)); // lane
7966     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7967     TmpInst.addOperand(Inst.getOperand(5));
7968     Inst = TmpInst;
7969     return true;
7970   }
7971
7972   case ARM::VLD4LNdAsm_8:
7973   case ARM::VLD4LNdAsm_16:
7974   case ARM::VLD4LNdAsm_32:
7975   case ARM::VLD4LNqAsm_16:
7976   case ARM::VLD4LNqAsm_32: {
7977     MCInst TmpInst;
7978     // Shuffle the operands around so the lane index operand is in the
7979     // right place.
7980     unsigned Spacing;
7981     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7982     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7983     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7984                                             Spacing));
7985     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7986                                             Spacing * 2));
7987     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7988                                             Spacing * 3));
7989     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7990     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7991     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7992     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7993                                             Spacing));
7994     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7995                                             Spacing * 2));
7996     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7997                                             Spacing * 3));
7998     TmpInst.addOperand(Inst.getOperand(1)); // lane
7999     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8000     TmpInst.addOperand(Inst.getOperand(5));
8001     Inst = TmpInst;
8002     return true;
8003   }
8004
8005   // VLD3DUP single 3-element structure to all lanes instructions.
8006   case ARM::VLD3DUPdAsm_8:
8007   case ARM::VLD3DUPdAsm_16:
8008   case ARM::VLD3DUPdAsm_32:
8009   case ARM::VLD3DUPqAsm_8:
8010   case ARM::VLD3DUPqAsm_16:
8011   case ARM::VLD3DUPqAsm_32: {
8012     MCInst TmpInst;
8013     unsigned Spacing;
8014     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8015     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8016     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8017                                             Spacing));
8018     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8019                                             Spacing * 2));
8020     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8021     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8022     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8023     TmpInst.addOperand(Inst.getOperand(4));
8024     Inst = TmpInst;
8025     return true;
8026   }
8027
8028   case ARM::VLD3DUPdWB_fixed_Asm_8:
8029   case ARM::VLD3DUPdWB_fixed_Asm_16:
8030   case ARM::VLD3DUPdWB_fixed_Asm_32:
8031   case ARM::VLD3DUPqWB_fixed_Asm_8:
8032   case ARM::VLD3DUPqWB_fixed_Asm_16:
8033   case ARM::VLD3DUPqWB_fixed_Asm_32: {
8034     MCInst TmpInst;
8035     unsigned Spacing;
8036     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8037     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8038     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8039                                             Spacing));
8040     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8041                                             Spacing * 2));
8042     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8043     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8044     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8045     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8046     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8047     TmpInst.addOperand(Inst.getOperand(4));
8048     Inst = TmpInst;
8049     return true;
8050   }
8051
8052   case ARM::VLD3DUPdWB_register_Asm_8:
8053   case ARM::VLD3DUPdWB_register_Asm_16:
8054   case ARM::VLD3DUPdWB_register_Asm_32:
8055   case ARM::VLD3DUPqWB_register_Asm_8:
8056   case ARM::VLD3DUPqWB_register_Asm_16:
8057   case ARM::VLD3DUPqWB_register_Asm_32: {
8058     MCInst TmpInst;
8059     unsigned Spacing;
8060     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8061     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8062     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8063                                             Spacing));
8064     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8065                                             Spacing * 2));
8066     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8067     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8068     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8069     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8070     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8071     TmpInst.addOperand(Inst.getOperand(5));
8072     Inst = TmpInst;
8073     return true;
8074   }
8075
8076   // VLD3 multiple 3-element structure instructions.
8077   case ARM::VLD3dAsm_8:
8078   case ARM::VLD3dAsm_16:
8079   case ARM::VLD3dAsm_32:
8080   case ARM::VLD3qAsm_8:
8081   case ARM::VLD3qAsm_16:
8082   case ARM::VLD3qAsm_32: {
8083     MCInst TmpInst;
8084     unsigned Spacing;
8085     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8086     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8087     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8088                                             Spacing));
8089     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8090                                             Spacing * 2));
8091     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8092     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8093     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8094     TmpInst.addOperand(Inst.getOperand(4));
8095     Inst = TmpInst;
8096     return true;
8097   }
8098
8099   case ARM::VLD3dWB_fixed_Asm_8:
8100   case ARM::VLD3dWB_fixed_Asm_16:
8101   case ARM::VLD3dWB_fixed_Asm_32:
8102   case ARM::VLD3qWB_fixed_Asm_8:
8103   case ARM::VLD3qWB_fixed_Asm_16:
8104   case ARM::VLD3qWB_fixed_Asm_32: {
8105     MCInst TmpInst;
8106     unsigned Spacing;
8107     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8108     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8109     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8110                                             Spacing));
8111     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8112                                             Spacing * 2));
8113     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8114     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8115     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8116     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8117     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8118     TmpInst.addOperand(Inst.getOperand(4));
8119     Inst = TmpInst;
8120     return true;
8121   }
8122
8123   case ARM::VLD3dWB_register_Asm_8:
8124   case ARM::VLD3dWB_register_Asm_16:
8125   case ARM::VLD3dWB_register_Asm_32:
8126   case ARM::VLD3qWB_register_Asm_8:
8127   case ARM::VLD3qWB_register_Asm_16:
8128   case ARM::VLD3qWB_register_Asm_32: {
8129     MCInst TmpInst;
8130     unsigned Spacing;
8131     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8132     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8133     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8134                                             Spacing));
8135     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8136                                             Spacing * 2));
8137     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8138     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8139     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8140     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8141     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8142     TmpInst.addOperand(Inst.getOperand(5));
8143     Inst = TmpInst;
8144     return true;
8145   }
8146
8147   // VLD4DUP single 3-element structure to all lanes instructions.
8148   case ARM::VLD4DUPdAsm_8:
8149   case ARM::VLD4DUPdAsm_16:
8150   case ARM::VLD4DUPdAsm_32:
8151   case ARM::VLD4DUPqAsm_8:
8152   case ARM::VLD4DUPqAsm_16:
8153   case ARM::VLD4DUPqAsm_32: {
8154     MCInst TmpInst;
8155     unsigned Spacing;
8156     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8157     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8158     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8159                                             Spacing));
8160     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8161                                             Spacing * 2));
8162     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8163                                             Spacing * 3));
8164     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8165     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8166     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8167     TmpInst.addOperand(Inst.getOperand(4));
8168     Inst = TmpInst;
8169     return true;
8170   }
8171
8172   case ARM::VLD4DUPdWB_fixed_Asm_8:
8173   case ARM::VLD4DUPdWB_fixed_Asm_16:
8174   case ARM::VLD4DUPdWB_fixed_Asm_32:
8175   case ARM::VLD4DUPqWB_fixed_Asm_8:
8176   case ARM::VLD4DUPqWB_fixed_Asm_16:
8177   case ARM::VLD4DUPqWB_fixed_Asm_32: {
8178     MCInst TmpInst;
8179     unsigned Spacing;
8180     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8181     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8182     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8183                                             Spacing));
8184     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8185                                             Spacing * 2));
8186     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8187                                             Spacing * 3));
8188     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8189     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8190     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8191     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8192     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8193     TmpInst.addOperand(Inst.getOperand(4));
8194     Inst = TmpInst;
8195     return true;
8196   }
8197
8198   case ARM::VLD4DUPdWB_register_Asm_8:
8199   case ARM::VLD4DUPdWB_register_Asm_16:
8200   case ARM::VLD4DUPdWB_register_Asm_32:
8201   case ARM::VLD4DUPqWB_register_Asm_8:
8202   case ARM::VLD4DUPqWB_register_Asm_16:
8203   case ARM::VLD4DUPqWB_register_Asm_32: {
8204     MCInst TmpInst;
8205     unsigned Spacing;
8206     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8207     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8208     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8209                                             Spacing));
8210     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8211                                             Spacing * 2));
8212     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8213                                             Spacing * 3));
8214     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8215     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8216     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8217     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8218     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8219     TmpInst.addOperand(Inst.getOperand(5));
8220     Inst = TmpInst;
8221     return true;
8222   }
8223
8224   // VLD4 multiple 4-element structure instructions.
8225   case ARM::VLD4dAsm_8:
8226   case ARM::VLD4dAsm_16:
8227   case ARM::VLD4dAsm_32:
8228   case ARM::VLD4qAsm_8:
8229   case ARM::VLD4qAsm_16:
8230   case ARM::VLD4qAsm_32: {
8231     MCInst TmpInst;
8232     unsigned Spacing;
8233     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8234     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8235     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8236                                             Spacing));
8237     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8238                                             Spacing * 2));
8239     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8240                                             Spacing * 3));
8241     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8242     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8243     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8244     TmpInst.addOperand(Inst.getOperand(4));
8245     Inst = TmpInst;
8246     return true;
8247   }
8248
8249   case ARM::VLD4dWB_fixed_Asm_8:
8250   case ARM::VLD4dWB_fixed_Asm_16:
8251   case ARM::VLD4dWB_fixed_Asm_32:
8252   case ARM::VLD4qWB_fixed_Asm_8:
8253   case ARM::VLD4qWB_fixed_Asm_16:
8254   case ARM::VLD4qWB_fixed_Asm_32: {
8255     MCInst TmpInst;
8256     unsigned Spacing;
8257     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8258     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8259     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8260                                             Spacing));
8261     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8262                                             Spacing * 2));
8263     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8264                                             Spacing * 3));
8265     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8266     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8267     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8268     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8269     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8270     TmpInst.addOperand(Inst.getOperand(4));
8271     Inst = TmpInst;
8272     return true;
8273   }
8274
8275   case ARM::VLD4dWB_register_Asm_8:
8276   case ARM::VLD4dWB_register_Asm_16:
8277   case ARM::VLD4dWB_register_Asm_32:
8278   case ARM::VLD4qWB_register_Asm_8:
8279   case ARM::VLD4qWB_register_Asm_16:
8280   case ARM::VLD4qWB_register_Asm_32: {
8281     MCInst TmpInst;
8282     unsigned Spacing;
8283     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8284     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8285     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8286                                             Spacing));
8287     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8288                                             Spacing * 2));
8289     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8290                                             Spacing * 3));
8291     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8292     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8293     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8294     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8295     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8296     TmpInst.addOperand(Inst.getOperand(5));
8297     Inst = TmpInst;
8298     return true;
8299   }
8300
8301   // VST3 multiple 3-element structure instructions.
8302   case ARM::VST3dAsm_8:
8303   case ARM::VST3dAsm_16:
8304   case ARM::VST3dAsm_32:
8305   case ARM::VST3qAsm_8:
8306   case ARM::VST3qAsm_16:
8307   case ARM::VST3qAsm_32: {
8308     MCInst TmpInst;
8309     unsigned Spacing;
8310     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8311     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8312     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8313     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8314     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8315                                             Spacing));
8316     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8317                                             Spacing * 2));
8318     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8319     TmpInst.addOperand(Inst.getOperand(4));
8320     Inst = TmpInst;
8321     return true;
8322   }
8323
8324   case ARM::VST3dWB_fixed_Asm_8:
8325   case ARM::VST3dWB_fixed_Asm_16:
8326   case ARM::VST3dWB_fixed_Asm_32:
8327   case ARM::VST3qWB_fixed_Asm_8:
8328   case ARM::VST3qWB_fixed_Asm_16:
8329   case ARM::VST3qWB_fixed_Asm_32: {
8330     MCInst TmpInst;
8331     unsigned Spacing;
8332     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8333     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8334     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8335     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8336     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8337     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8338     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8339                                             Spacing));
8340     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8341                                             Spacing * 2));
8342     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8343     TmpInst.addOperand(Inst.getOperand(4));
8344     Inst = TmpInst;
8345     return true;
8346   }
8347
8348   case ARM::VST3dWB_register_Asm_8:
8349   case ARM::VST3dWB_register_Asm_16:
8350   case ARM::VST3dWB_register_Asm_32:
8351   case ARM::VST3qWB_register_Asm_8:
8352   case ARM::VST3qWB_register_Asm_16:
8353   case ARM::VST3qWB_register_Asm_32: {
8354     MCInst TmpInst;
8355     unsigned Spacing;
8356     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8357     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8358     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8359     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8360     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8361     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8362     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8363                                             Spacing));
8364     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8365                                             Spacing * 2));
8366     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8367     TmpInst.addOperand(Inst.getOperand(5));
8368     Inst = TmpInst;
8369     return true;
8370   }
8371
8372   // VST4 multiple 3-element structure instructions.
8373   case ARM::VST4dAsm_8:
8374   case ARM::VST4dAsm_16:
8375   case ARM::VST4dAsm_32:
8376   case ARM::VST4qAsm_8:
8377   case ARM::VST4qAsm_16:
8378   case ARM::VST4qAsm_32: {
8379     MCInst TmpInst;
8380     unsigned Spacing;
8381     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8382     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8383     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8384     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8385     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8386                                             Spacing));
8387     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8388                                             Spacing * 2));
8389     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8390                                             Spacing * 3));
8391     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8392     TmpInst.addOperand(Inst.getOperand(4));
8393     Inst = TmpInst;
8394     return true;
8395   }
8396
8397   case ARM::VST4dWB_fixed_Asm_8:
8398   case ARM::VST4dWB_fixed_Asm_16:
8399   case ARM::VST4dWB_fixed_Asm_32:
8400   case ARM::VST4qWB_fixed_Asm_8:
8401   case ARM::VST4qWB_fixed_Asm_16:
8402   case ARM::VST4qWB_fixed_Asm_32: {
8403     MCInst TmpInst;
8404     unsigned Spacing;
8405     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8406     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8407     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8408     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8409     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8410     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8411     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8412                                             Spacing));
8413     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8414                                             Spacing * 2));
8415     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8416                                             Spacing * 3));
8417     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8418     TmpInst.addOperand(Inst.getOperand(4));
8419     Inst = TmpInst;
8420     return true;
8421   }
8422
8423   case ARM::VST4dWB_register_Asm_8:
8424   case ARM::VST4dWB_register_Asm_16:
8425   case ARM::VST4dWB_register_Asm_32:
8426   case ARM::VST4qWB_register_Asm_8:
8427   case ARM::VST4qWB_register_Asm_16:
8428   case ARM::VST4qWB_register_Asm_32: {
8429     MCInst TmpInst;
8430     unsigned Spacing;
8431     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8432     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8433     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8434     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8435     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8436     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8437     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8438                                             Spacing));
8439     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8440                                             Spacing * 2));
8441     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8442                                             Spacing * 3));
8443     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8444     TmpInst.addOperand(Inst.getOperand(5));
8445     Inst = TmpInst;
8446     return true;
8447   }
8448
8449   // Handle encoding choice for the shift-immediate instructions.
8450   case ARM::t2LSLri:
8451   case ARM::t2LSRri:
8452   case ARM::t2ASRri:
8453     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8454         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8455         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8456         !HasWideQualifier) {
8457       unsigned NewOpc;
8458       switch (Inst.getOpcode()) {
8459       default: llvm_unreachable("unexpected opcode");
8460       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8461       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8462       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8463       }
8464       // The Thumb1 operands aren't in the same order. Awesome, eh?
8465       MCInst TmpInst;
8466       TmpInst.setOpcode(NewOpc);
8467       TmpInst.addOperand(Inst.getOperand(0));
8468       TmpInst.addOperand(Inst.getOperand(5));
8469       TmpInst.addOperand(Inst.getOperand(1));
8470       TmpInst.addOperand(Inst.getOperand(2));
8471       TmpInst.addOperand(Inst.getOperand(3));
8472       TmpInst.addOperand(Inst.getOperand(4));
8473       Inst = TmpInst;
8474       return true;
8475     }
8476     return false;
8477
8478   // Handle the Thumb2 mode MOV complex aliases.
8479   case ARM::t2MOVsr:
8480   case ARM::t2MOVSsr: {
8481     // Which instruction to expand to depends on the CCOut operand and
8482     // whether we're in an IT block if the register operands are low
8483     // registers.
8484     bool isNarrow = false;
8485     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8486         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8487         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8488         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8489         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8490         !HasWideQualifier)
8491       isNarrow = true;
8492     MCInst TmpInst;
8493     unsigned newOpc;
8494     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8495     default: llvm_unreachable("unexpected opcode!");
8496     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8497     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8498     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8499     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8500     }
8501     TmpInst.setOpcode(newOpc);
8502     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8503     if (isNarrow)
8504       TmpInst.addOperand(MCOperand::createReg(
8505           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8506     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8507     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8508     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8509     TmpInst.addOperand(Inst.getOperand(5));
8510     if (!isNarrow)
8511       TmpInst.addOperand(MCOperand::createReg(
8512           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8513     Inst = TmpInst;
8514     return true;
8515   }
8516   case ARM::t2MOVsi:
8517   case ARM::t2MOVSsi: {
8518     // Which instruction to expand to depends on the CCOut operand and
8519     // whether we're in an IT block if the register operands are low
8520     // registers.
8521     bool isNarrow = false;
8522     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8523         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8524         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8525         !HasWideQualifier)
8526       isNarrow = true;
8527     MCInst TmpInst;
8528     unsigned newOpc;
8529     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8530     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8531     bool isMov = false;
8532     // MOV rd, rm, LSL #0 is actually a MOV instruction
8533     if (Shift == ARM_AM::lsl && Amount == 0) {
8534       isMov = true;
8535       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8536       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8537       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8538       // instead.
8539       if (inITBlock()) {
8540         isNarrow = false;
8541       }
8542       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8543     } else {
8544       switch(Shift) {
8545       default: llvm_unreachable("unexpected opcode!");
8546       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8547       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8548       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8549       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8550       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8551       }
8552     }
8553     if (Amount == 32) Amount = 0;
8554     TmpInst.setOpcode(newOpc);
8555     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8556     if (isNarrow && !isMov)
8557       TmpInst.addOperand(MCOperand::createReg(
8558           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8559     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8560     if (newOpc != ARM::t2RRX && !isMov)
8561       TmpInst.addOperand(MCOperand::createImm(Amount));
8562     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8563     TmpInst.addOperand(Inst.getOperand(4));
8564     if (!isNarrow)
8565       TmpInst.addOperand(MCOperand::createReg(
8566           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8567     Inst = TmpInst;
8568     return true;
8569   }
8570   // Handle the ARM mode MOV complex aliases.
8571   case ARM::ASRr:
8572   case ARM::LSRr:
8573   case ARM::LSLr:
8574   case ARM::RORr: {
8575     ARM_AM::ShiftOpc ShiftTy;
8576     switch(Inst.getOpcode()) {
8577     default: llvm_unreachable("unexpected opcode!");
8578     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8579     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8580     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8581     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8582     }
8583     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8584     MCInst TmpInst;
8585     TmpInst.setOpcode(ARM::MOVsr);
8586     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8587     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8588     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8589     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8590     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8591     TmpInst.addOperand(Inst.getOperand(4));
8592     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8593     Inst = TmpInst;
8594     return true;
8595   }
8596   case ARM::ASRi:
8597   case ARM::LSRi:
8598   case ARM::LSLi:
8599   case ARM::RORi: {
8600     ARM_AM::ShiftOpc ShiftTy;
8601     switch(Inst.getOpcode()) {
8602     default: llvm_unreachable("unexpected opcode!");
8603     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8604     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8605     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8606     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8607     }
8608     // A shift by zero is a plain MOVr, not a MOVsi.
8609     unsigned Amt = Inst.getOperand(2).getImm();
8610     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8611     // A shift by 32 should be encoded as 0 when permitted
8612     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8613       Amt = 0;
8614     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8615     MCInst TmpInst;
8616     TmpInst.setOpcode(Opc);
8617     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8618     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8619     if (Opc == ARM::MOVsi)
8620       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8621     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8622     TmpInst.addOperand(Inst.getOperand(4));
8623     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8624     Inst = TmpInst;
8625     return true;
8626   }
8627   case ARM::RRXi: {
8628     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8629     MCInst TmpInst;
8630     TmpInst.setOpcode(ARM::MOVsi);
8631     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8632     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8633     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8634     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8635     TmpInst.addOperand(Inst.getOperand(3));
8636     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8637     Inst = TmpInst;
8638     return true;
8639   }
8640   case ARM::t2LDMIA_UPD: {
8641     // If this is a load of a single register, then we should use
8642     // a post-indexed LDR instruction instead, per the ARM ARM.
8643     if (Inst.getNumOperands() != 5)
8644       return false;
8645     MCInst TmpInst;
8646     TmpInst.setOpcode(ARM::t2LDR_POST);
8647     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8648     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8649     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8650     TmpInst.addOperand(MCOperand::createImm(4));
8651     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8652     TmpInst.addOperand(Inst.getOperand(3));
8653     Inst = TmpInst;
8654     return true;
8655   }
8656   case ARM::t2STMDB_UPD: {
8657     // If this is a store of a single register, then we should use
8658     // a pre-indexed STR instruction instead, per the ARM ARM.
8659     if (Inst.getNumOperands() != 5)
8660       return false;
8661     MCInst TmpInst;
8662     TmpInst.setOpcode(ARM::t2STR_PRE);
8663     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8664     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8665     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8666     TmpInst.addOperand(MCOperand::createImm(-4));
8667     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8668     TmpInst.addOperand(Inst.getOperand(3));
8669     Inst = TmpInst;
8670     return true;
8671   }
8672   case ARM::LDMIA_UPD:
8673     // If this is a load of a single register via a 'pop', then we should use
8674     // a post-indexed LDR instruction instead, per the ARM ARM.
8675     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8676         Inst.getNumOperands() == 5) {
8677       MCInst TmpInst;
8678       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8679       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8680       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8681       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8682       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8683       TmpInst.addOperand(MCOperand::createImm(4));
8684       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8685       TmpInst.addOperand(Inst.getOperand(3));
8686       Inst = TmpInst;
8687       return true;
8688     }
8689     break;
8690   case ARM::STMDB_UPD:
8691     // If this is a store of a single register via a 'push', then we should use
8692     // a pre-indexed STR instruction instead, per the ARM ARM.
8693     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8694         Inst.getNumOperands() == 5) {
8695       MCInst TmpInst;
8696       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8697       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8698       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8699       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8700       TmpInst.addOperand(MCOperand::createImm(-4));
8701       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8702       TmpInst.addOperand(Inst.getOperand(3));
8703       Inst = TmpInst;
8704     }
8705     break;
8706   case ARM::t2ADDri12:
8707     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8708     // mnemonic was used (not "addw"), encoding T3 is preferred.
8709     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8710         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8711       break;
8712     Inst.setOpcode(ARM::t2ADDri);
8713     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8714     break;
8715   case ARM::t2SUBri12:
8716     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8717     // mnemonic was used (not "subw"), encoding T3 is preferred.
8718     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8719         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8720       break;
8721     Inst.setOpcode(ARM::t2SUBri);
8722     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8723     break;
8724   case ARM::tADDi8:
8725     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8726     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8727     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8728     // to encoding T1 if <Rd> is omitted."
8729     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8730       Inst.setOpcode(ARM::tADDi3);
8731       return true;
8732     }
8733     break;
8734   case ARM::tSUBi8:
8735     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8736     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8737     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8738     // to encoding T1 if <Rd> is omitted."
8739     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8740       Inst.setOpcode(ARM::tSUBi3);
8741       return true;
8742     }
8743     break;
8744   case ARM::t2ADDri:
8745   case ARM::t2SUBri: {
8746     // If the destination and first source operand are the same, and
8747     // the flags are compatible with the current IT status, use encoding T2
8748     // instead of T3. For compatibility with the system 'as'. Make sure the
8749     // wide encoding wasn't explicit.
8750     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8751         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8752         (Inst.getOperand(2).isImm() &&
8753          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8754         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8755         HasWideQualifier)
8756       break;
8757     MCInst TmpInst;
8758     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8759                       ARM::tADDi8 : ARM::tSUBi8);
8760     TmpInst.addOperand(Inst.getOperand(0));
8761     TmpInst.addOperand(Inst.getOperand(5));
8762     TmpInst.addOperand(Inst.getOperand(0));
8763     TmpInst.addOperand(Inst.getOperand(2));
8764     TmpInst.addOperand(Inst.getOperand(3));
8765     TmpInst.addOperand(Inst.getOperand(4));
8766     Inst = TmpInst;
8767     return true;
8768   }
8769   case ARM::t2ADDrr: {
8770     // If the destination and first source operand are the same, and
8771     // there's no setting of the flags, use encoding T2 instead of T3.
8772     // Note that this is only for ADD, not SUB. This mirrors the system
8773     // 'as' behaviour.  Also take advantage of ADD being commutative.
8774     // Make sure the wide encoding wasn't explicit.
8775     bool Swap = false;
8776     auto DestReg = Inst.getOperand(0).getReg();
8777     bool Transform = DestReg == Inst.getOperand(1).getReg();
8778     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8779       Transform = true;
8780       Swap = true;
8781     }
8782     if (!Transform ||
8783         Inst.getOperand(5).getReg() != 0 ||
8784         HasWideQualifier)
8785       break;
8786     MCInst TmpInst;
8787     TmpInst.setOpcode(ARM::tADDhirr);
8788     TmpInst.addOperand(Inst.getOperand(0));
8789     TmpInst.addOperand(Inst.getOperand(0));
8790     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8791     TmpInst.addOperand(Inst.getOperand(3));
8792     TmpInst.addOperand(Inst.getOperand(4));
8793     Inst = TmpInst;
8794     return true;
8795   }
8796   case ARM::tADDrSP:
8797     // If the non-SP source operand and the destination operand are not the
8798     // same, we need to use the 32-bit encoding if it's available.
8799     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8800       Inst.setOpcode(ARM::t2ADDrr);
8801       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8802       return true;
8803     }
8804     break;
8805   case ARM::tB:
8806     // A Thumb conditional branch outside of an IT block is a tBcc.
8807     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8808       Inst.setOpcode(ARM::tBcc);
8809       return true;
8810     }
8811     break;
8812   case ARM::t2B:
8813     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8814     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8815       Inst.setOpcode(ARM::t2Bcc);
8816       return true;
8817     }
8818     break;
8819   case ARM::t2Bcc:
8820     // If the conditional is AL or we're in an IT block, we really want t2B.
8821     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8822       Inst.setOpcode(ARM::t2B);
8823       return true;
8824     }
8825     break;
8826   case ARM::tBcc:
8827     // If the conditional is AL, we really want tB.
8828     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8829       Inst.setOpcode(ARM::tB);
8830       return true;
8831     }
8832     break;
8833   case ARM::tLDMIA: {
8834     // If the register list contains any high registers, or if the writeback
8835     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8836     // instead if we're in Thumb2. Otherwise, this should have generated
8837     // an error in validateInstruction().
8838     unsigned Rn = Inst.getOperand(0).getReg();
8839     bool hasWritebackToken =
8840         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8841          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8842     bool listContainsBase;
8843     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8844         (!listContainsBase && !hasWritebackToken) ||
8845         (listContainsBase && hasWritebackToken)) {
8846       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8847       assert(isThumbTwo());
8848       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8849       // If we're switching to the updating version, we need to insert
8850       // the writeback tied operand.
8851       if (hasWritebackToken)
8852         Inst.insert(Inst.begin(),
8853                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8854       return true;
8855     }
8856     break;
8857   }
8858   case ARM::tSTMIA_UPD: {
8859     // If the register list contains any high registers, we need to use
8860     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8861     // should have generated an error in validateInstruction().
8862     unsigned Rn = Inst.getOperand(0).getReg();
8863     bool listContainsBase;
8864     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8865       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8866       assert(isThumbTwo());
8867       Inst.setOpcode(ARM::t2STMIA_UPD);
8868       return true;
8869     }
8870     break;
8871   }
8872   case ARM::tPOP: {
8873     bool listContainsBase;
8874     // If the register list contains any high registers, we need to use
8875     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8876     // should have generated an error in validateInstruction().
8877     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8878       return false;
8879     assert(isThumbTwo());
8880     Inst.setOpcode(ARM::t2LDMIA_UPD);
8881     // Add the base register and writeback operands.
8882     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8883     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8884     return true;
8885   }
8886   case ARM::tPUSH: {
8887     bool listContainsBase;
8888     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8889       return false;
8890     assert(isThumbTwo());
8891     Inst.setOpcode(ARM::t2STMDB_UPD);
8892     // Add the base register and writeback operands.
8893     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8894     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8895     return true;
8896   }
8897   case ARM::t2MOVi:
8898     // If we can use the 16-bit encoding and the user didn't explicitly
8899     // request the 32-bit variant, transform it here.
8900     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8901         (Inst.getOperand(1).isImm() &&
8902          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8903         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8904         !HasWideQualifier) {
8905       // The operands aren't in the same order for tMOVi8...
8906       MCInst TmpInst;
8907       TmpInst.setOpcode(ARM::tMOVi8);
8908       TmpInst.addOperand(Inst.getOperand(0));
8909       TmpInst.addOperand(Inst.getOperand(4));
8910       TmpInst.addOperand(Inst.getOperand(1));
8911       TmpInst.addOperand(Inst.getOperand(2));
8912       TmpInst.addOperand(Inst.getOperand(3));
8913       Inst = TmpInst;
8914       return true;
8915     }
8916     break;
8917
8918   case ARM::t2MOVr:
8919     // If we can use the 16-bit encoding and the user didn't explicitly
8920     // request the 32-bit variant, transform it here.
8921     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8922         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8923         Inst.getOperand(2).getImm() == ARMCC::AL &&
8924         Inst.getOperand(4).getReg() == ARM::CPSR &&
8925         !HasWideQualifier) {
8926       // The operands aren't the same for tMOV[S]r... (no cc_out)
8927       MCInst TmpInst;
8928       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8929       TmpInst.addOperand(Inst.getOperand(0));
8930       TmpInst.addOperand(Inst.getOperand(1));
8931       TmpInst.addOperand(Inst.getOperand(2));
8932       TmpInst.addOperand(Inst.getOperand(3));
8933       Inst = TmpInst;
8934       return true;
8935     }
8936     break;
8937
8938   case ARM::t2SXTH:
8939   case ARM::t2SXTB:
8940   case ARM::t2UXTH:
8941   case ARM::t2UXTB:
8942     // If we can use the 16-bit encoding and the user didn't explicitly
8943     // request the 32-bit variant, transform it here.
8944     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8945         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8946         Inst.getOperand(2).getImm() == 0 &&
8947         !HasWideQualifier) {
8948       unsigned NewOpc;
8949       switch (Inst.getOpcode()) {
8950       default: llvm_unreachable("Illegal opcode!");
8951       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8952       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8953       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8954       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8955       }
8956       // The operands aren't the same for thumb1 (no rotate operand).
8957       MCInst TmpInst;
8958       TmpInst.setOpcode(NewOpc);
8959       TmpInst.addOperand(Inst.getOperand(0));
8960       TmpInst.addOperand(Inst.getOperand(1));
8961       TmpInst.addOperand(Inst.getOperand(3));
8962       TmpInst.addOperand(Inst.getOperand(4));
8963       Inst = TmpInst;
8964       return true;
8965     }
8966     break;
8967
8968   case ARM::MOVsi: {
8969     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8970     // rrx shifts and asr/lsr of #32 is encoded as 0
8971     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8972       return false;
8973     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8974       // Shifting by zero is accepted as a vanilla 'MOVr'
8975       MCInst TmpInst;
8976       TmpInst.setOpcode(ARM::MOVr);
8977       TmpInst.addOperand(Inst.getOperand(0));
8978       TmpInst.addOperand(Inst.getOperand(1));
8979       TmpInst.addOperand(Inst.getOperand(3));
8980       TmpInst.addOperand(Inst.getOperand(4));
8981       TmpInst.addOperand(Inst.getOperand(5));
8982       Inst = TmpInst;
8983       return true;
8984     }
8985     return false;
8986   }
8987   case ARM::ANDrsi:
8988   case ARM::ORRrsi:
8989   case ARM::EORrsi:
8990   case ARM::BICrsi:
8991   case ARM::SUBrsi:
8992   case ARM::ADDrsi: {
8993     unsigned newOpc;
8994     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8995     if (SOpc == ARM_AM::rrx) return false;
8996     switch (Inst.getOpcode()) {
8997     default: llvm_unreachable("unexpected opcode!");
8998     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8999     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
9000     case ARM::EORrsi: newOpc = ARM::EORrr; break;
9001     case ARM::BICrsi: newOpc = ARM::BICrr; break;
9002     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
9003     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
9004     }
9005     // If the shift is by zero, use the non-shifted instruction definition.
9006     // The exception is for right shifts, where 0 == 32
9007     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
9008         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
9009       MCInst TmpInst;
9010       TmpInst.setOpcode(newOpc);
9011       TmpInst.addOperand(Inst.getOperand(0));
9012       TmpInst.addOperand(Inst.getOperand(1));
9013       TmpInst.addOperand(Inst.getOperand(2));
9014       TmpInst.addOperand(Inst.getOperand(4));
9015       TmpInst.addOperand(Inst.getOperand(5));
9016       TmpInst.addOperand(Inst.getOperand(6));
9017       Inst = TmpInst;
9018       return true;
9019     }
9020     return false;
9021   }
9022   case ARM::ITasm:
9023   case ARM::t2IT: {
9024     MCOperand &MO = Inst.getOperand(1);
9025     unsigned Mask = MO.getImm();
9026     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
9027
9028     // Set up the IT block state according to the IT instruction we just
9029     // matched.
9030     assert(!inITBlock() && "nested IT blocks?!");
9031     startExplicitITBlock(Cond, Mask);
9032     MO.setImm(getITMaskEncoding());
9033     break;
9034   }
9035   case ARM::t2LSLrr:
9036   case ARM::t2LSRrr:
9037   case ARM::t2ASRrr:
9038   case ARM::t2SBCrr:
9039   case ARM::t2RORrr:
9040   case ARM::t2BICrr:
9041     // Assemblers should use the narrow encodings of these instructions when permissible.
9042     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
9043          isARMLowRegister(Inst.getOperand(2).getReg())) &&
9044         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
9045         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9046         !HasWideQualifier) {
9047       unsigned NewOpc;
9048       switch (Inst.getOpcode()) {
9049         default: llvm_unreachable("unexpected opcode");
9050         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
9051         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
9052         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
9053         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
9054         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
9055         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
9056       }
9057       MCInst TmpInst;
9058       TmpInst.setOpcode(NewOpc);
9059       TmpInst.addOperand(Inst.getOperand(0));
9060       TmpInst.addOperand(Inst.getOperand(5));
9061       TmpInst.addOperand(Inst.getOperand(1));
9062       TmpInst.addOperand(Inst.getOperand(2));
9063       TmpInst.addOperand(Inst.getOperand(3));
9064       TmpInst.addOperand(Inst.getOperand(4));
9065       Inst = TmpInst;
9066       return true;
9067     }
9068     return false;
9069
9070   case ARM::t2ANDrr:
9071   case ARM::t2EORrr:
9072   case ARM::t2ADCrr:
9073   case ARM::t2ORRrr:
9074     // Assemblers should use the narrow encodings of these instructions when permissible.
9075     // These instructions are special in that they are commutable, so shorter encodings
9076     // are available more often.
9077     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
9078          isARMLowRegister(Inst.getOperand(2).getReg())) &&
9079         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
9080          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
9081         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9082         !HasWideQualifier) {
9083       unsigned NewOpc;
9084       switch (Inst.getOpcode()) {
9085         default: llvm_unreachable("unexpected opcode");
9086         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
9087         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
9088         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
9089         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
9090       }
9091       MCInst TmpInst;
9092       TmpInst.setOpcode(NewOpc);
9093       TmpInst.addOperand(Inst.getOperand(0));
9094       TmpInst.addOperand(Inst.getOperand(5));
9095       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
9096         TmpInst.addOperand(Inst.getOperand(1));
9097         TmpInst.addOperand(Inst.getOperand(2));
9098       } else {
9099         TmpInst.addOperand(Inst.getOperand(2));
9100         TmpInst.addOperand(Inst.getOperand(1));
9101       }
9102       TmpInst.addOperand(Inst.getOperand(3));
9103       TmpInst.addOperand(Inst.getOperand(4));
9104       Inst = TmpInst;
9105       return true;
9106     }
9107     return false;
9108   }
9109   return false;
9110 }
9111
9112 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
9113   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
9114   // suffix depending on whether they're in an IT block or not.
9115   unsigned Opc = Inst.getOpcode();
9116   const MCInstrDesc &MCID = MII.get(Opc);
9117   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
9118     assert(MCID.hasOptionalDef() &&
9119            "optionally flag setting instruction missing optional def operand");
9120     assert(MCID.NumOperands == Inst.getNumOperands() &&
9121            "operand count mismatch!");
9122     // Find the optional-def operand (cc_out).
9123     unsigned OpNo;
9124     for (OpNo = 0;
9125          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
9126          ++OpNo)
9127       ;
9128     // If we're parsing Thumb1, reject it completely.
9129     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
9130       return Match_RequiresFlagSetting;
9131     // If we're parsing Thumb2, which form is legal depends on whether we're
9132     // in an IT block.
9133     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
9134         !inITBlock())
9135       return Match_RequiresITBlock;
9136     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
9137         inITBlock())
9138       return Match_RequiresNotITBlock;
9139     // LSL with zero immediate is not allowed in an IT block
9140     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
9141       return Match_RequiresNotITBlock;
9142   } else if (isThumbOne()) {
9143     // Some high-register supporting Thumb1 encodings only allow both registers
9144     // to be from r0-r7 when in Thumb2.
9145     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
9146         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9147         isARMLowRegister(Inst.getOperand(2).getReg()))
9148       return Match_RequiresThumb2;
9149     // Others only require ARMv6 or later.
9150     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
9151              isARMLowRegister(Inst.getOperand(0).getReg()) &&
9152              isARMLowRegister(Inst.getOperand(1).getReg()))
9153       return Match_RequiresV6;
9154   }
9155
9156   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
9157   // than the loop below can handle, so it uses the GPRnopc register class and
9158   // we do SP handling here.
9159   if (Opc == ARM::t2MOVr && !hasV8Ops())
9160   {
9161     // SP as both source and destination is not allowed
9162     if (Inst.getOperand(0).getReg() == ARM::SP &&
9163         Inst.getOperand(1).getReg() == ARM::SP)
9164       return Match_RequiresV8;
9165     // When flags-setting SP as either source or destination is not allowed
9166     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
9167         (Inst.getOperand(0).getReg() == ARM::SP ||
9168          Inst.getOperand(1).getReg() == ARM::SP))
9169       return Match_RequiresV8;
9170   }
9171
9172   // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
9173   // ARMv8-A.
9174   if ((Inst.getOpcode() == ARM::VMRS || Inst.getOpcode() == ARM::VMSR) &&
9175       Inst.getOperand(0).getReg() == ARM::SP && (isThumb() && !hasV8Ops()))
9176     return Match_InvalidOperand;
9177
9178   for (unsigned I = 0; I < MCID.NumOperands; ++I)
9179     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
9180       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
9181       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
9182         return Match_RequiresV8;
9183       else if (Inst.getOperand(I).getReg() == ARM::PC)
9184         return Match_InvalidOperand;
9185     }
9186
9187   return Match_Success;
9188 }
9189
9190 namespace llvm {
9191
9192 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
9193   return true; // In an assembly source, no need to second-guess
9194 }
9195
9196 } // end namespace llvm
9197
9198 // Returns true if Inst is unpredictable if it is in and IT block, but is not
9199 // the last instruction in the block.
9200 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
9201   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9202
9203   // All branch & call instructions terminate IT blocks with the exception of
9204   // SVC.
9205   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
9206       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
9207     return true;
9208
9209   // Any arithmetic instruction which writes to the PC also terminates the IT
9210   // block.
9211   if (MCID.hasDefOfPhysReg(Inst, ARM::PC, *MRI))
9212     return true;
9213
9214   return false;
9215 }
9216
9217 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
9218                                           SmallVectorImpl<NearMissInfo> &NearMisses,
9219                                           bool MatchingInlineAsm,
9220                                           bool &EmitInITBlock,
9221                                           MCStreamer &Out) {
9222   // If we can't use an implicit IT block here, just match as normal.
9223   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
9224     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
9225
9226   // Try to match the instruction in an extension of the current IT block (if
9227   // there is one).
9228   if (inImplicitITBlock()) {
9229     extendImplicitITBlock(ITState.Cond);
9230     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
9231             Match_Success) {
9232       // The match succeded, but we still have to check that the instruction is
9233       // valid in this implicit IT block.
9234       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9235       if (MCID.isPredicable()) {
9236         ARMCC::CondCodes InstCond =
9237             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9238                 .getImm();
9239         ARMCC::CondCodes ITCond = currentITCond();
9240         if (InstCond == ITCond) {
9241           EmitInITBlock = true;
9242           return Match_Success;
9243         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
9244           invertCurrentITCondition();
9245           EmitInITBlock = true;
9246           return Match_Success;
9247         }
9248       }
9249     }
9250     rewindImplicitITPosition();
9251   }
9252
9253   // Finish the current IT block, and try to match outside any IT block.
9254   flushPendingInstructions(Out);
9255   unsigned PlainMatchResult =
9256       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
9257   if (PlainMatchResult == Match_Success) {
9258     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9259     if (MCID.isPredicable()) {
9260       ARMCC::CondCodes InstCond =
9261           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9262               .getImm();
9263       // Some forms of the branch instruction have their own condition code
9264       // fields, so can be conditionally executed without an IT block.
9265       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
9266         EmitInITBlock = false;
9267         return Match_Success;
9268       }
9269       if (InstCond == ARMCC::AL) {
9270         EmitInITBlock = false;
9271         return Match_Success;
9272       }
9273     } else {
9274       EmitInITBlock = false;
9275       return Match_Success;
9276     }
9277   }
9278
9279   // Try to match in a new IT block. The matcher doesn't check the actual
9280   // condition, so we create an IT block with a dummy condition, and fix it up
9281   // once we know the actual condition.
9282   startImplicitITBlock();
9283   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
9284       Match_Success) {
9285     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9286     if (MCID.isPredicable()) {
9287       ITState.Cond =
9288           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9289               .getImm();
9290       EmitInITBlock = true;
9291       return Match_Success;
9292     }
9293   }
9294   discardImplicitITBlock();
9295
9296   // If none of these succeed, return the error we got when trying to match
9297   // outside any IT blocks.
9298   EmitInITBlock = false;
9299   return PlainMatchResult;
9300 }
9301
9302 static std::string ARMMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
9303                                          unsigned VariantID = 0);
9304
9305 static const char *getSubtargetFeatureName(uint64_t Val);
9306 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
9307                                            OperandVector &Operands,
9308                                            MCStreamer &Out, uint64_t &ErrorInfo,
9309                                            bool MatchingInlineAsm) {
9310   MCInst Inst;
9311   unsigned MatchResult;
9312   bool PendConditionalInstruction = false;
9313
9314   SmallVector<NearMissInfo, 4> NearMisses;
9315   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
9316                                  PendConditionalInstruction, Out);
9317
9318   switch (MatchResult) {
9319   case Match_Success:
9320     LLVM_DEBUG(dbgs() << "Parsed as: ";
9321                Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
9322                dbgs() << "\n");
9323
9324     // Context sensitive operand constraints aren't handled by the matcher,
9325     // so check them here.
9326     if (validateInstruction(Inst, Operands)) {
9327       // Still progress the IT block, otherwise one wrong condition causes
9328       // nasty cascading errors.
9329       forwardITPosition();
9330       return true;
9331     }
9332
9333     { // processInstruction() updates inITBlock state, we need to save it away
9334       bool wasInITBlock = inITBlock();
9335
9336       // Some instructions need post-processing to, for example, tweak which
9337       // encoding is selected. Loop on it while changes happen so the
9338       // individual transformations can chain off each other. E.g.,
9339       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9340       while (processInstruction(Inst, Operands, Out))
9341         LLVM_DEBUG(dbgs() << "Changed to: ";
9342                    Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
9343                    dbgs() << "\n");
9344
9345       // Only after the instruction is fully processed, we can validate it
9346       if (wasInITBlock && hasV8Ops() && isThumb() &&
9347           !isV8EligibleForIT(&Inst)) {
9348         Warning(IDLoc, "deprecated instruction in IT block");
9349       }
9350     }
9351
9352     // Only move forward at the very end so that everything in validate
9353     // and process gets a consistent answer about whether we're in an IT
9354     // block.
9355     forwardITPosition();
9356
9357     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9358     // doesn't actually encode.
9359     if (Inst.getOpcode() == ARM::ITasm)
9360       return false;
9361
9362     Inst.setLoc(IDLoc);
9363     if (PendConditionalInstruction) {
9364       PendingConditionalInsts.push_back(Inst);
9365       if (isITBlockFull() || isITBlockTerminator(Inst))
9366         flushPendingInstructions(Out);
9367     } else {
9368       Out.EmitInstruction(Inst, getSTI());
9369     }
9370     return false;
9371   case Match_NearMisses:
9372     ReportNearMisses(NearMisses, IDLoc, Operands);
9373     return true;
9374   case Match_MnemonicFail: {
9375     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
9376     std::string Suggestion = ARMMnemonicSpellCheck(
9377       ((ARMOperand &)*Operands[0]).getToken(), FBS);
9378     return Error(IDLoc, "invalid instruction" + Suggestion,
9379                  ((ARMOperand &)*Operands[0]).getLocRange());
9380   }
9381   }
9382
9383   llvm_unreachable("Implement any new match types added!");
9384 }
9385
9386 /// parseDirective parses the arm specific directives
9387 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9388   const MCObjectFileInfo::Environment Format =
9389     getContext().getObjectFileInfo()->getObjectFileType();
9390   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9391   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9392
9393   StringRef IDVal = DirectiveID.getIdentifier();
9394   if (IDVal == ".word")
9395     parseLiteralValues(4, DirectiveID.getLoc());
9396   else if (IDVal == ".short" || IDVal == ".hword")
9397     parseLiteralValues(2, DirectiveID.getLoc());
9398   else if (IDVal == ".thumb")
9399     parseDirectiveThumb(DirectiveID.getLoc());
9400   else if (IDVal == ".arm")
9401     parseDirectiveARM(DirectiveID.getLoc());
9402   else if (IDVal == ".thumb_func")
9403     parseDirectiveThumbFunc(DirectiveID.getLoc());
9404   else if (IDVal == ".code")
9405     parseDirectiveCode(DirectiveID.getLoc());
9406   else if (IDVal == ".syntax")
9407     parseDirectiveSyntax(DirectiveID.getLoc());
9408   else if (IDVal == ".unreq")
9409     parseDirectiveUnreq(DirectiveID.getLoc());
9410   else if (IDVal == ".fnend")
9411     parseDirectiveFnEnd(DirectiveID.getLoc());
9412   else if (IDVal == ".cantunwind")
9413     parseDirectiveCantUnwind(DirectiveID.getLoc());
9414   else if (IDVal == ".personality")
9415     parseDirectivePersonality(DirectiveID.getLoc());
9416   else if (IDVal == ".handlerdata")
9417     parseDirectiveHandlerData(DirectiveID.getLoc());
9418   else if (IDVal == ".setfp")
9419     parseDirectiveSetFP(DirectiveID.getLoc());
9420   else if (IDVal == ".pad")
9421     parseDirectivePad(DirectiveID.getLoc());
9422   else if (IDVal == ".save")
9423     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9424   else if (IDVal == ".vsave")
9425     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9426   else if (IDVal == ".ltorg" || IDVal == ".pool")
9427     parseDirectiveLtorg(DirectiveID.getLoc());
9428   else if (IDVal == ".even")
9429     parseDirectiveEven(DirectiveID.getLoc());
9430   else if (IDVal == ".personalityindex")
9431     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9432   else if (IDVal == ".unwind_raw")
9433     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9434   else if (IDVal == ".movsp")
9435     parseDirectiveMovSP(DirectiveID.getLoc());
9436   else if (IDVal == ".arch_extension")
9437     parseDirectiveArchExtension(DirectiveID.getLoc());
9438   else if (IDVal == ".align")
9439     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9440   else if (IDVal == ".thumb_set")
9441     parseDirectiveThumbSet(DirectiveID.getLoc());
9442   else if (IDVal == ".inst")
9443     parseDirectiveInst(DirectiveID.getLoc());
9444   else if (IDVal == ".inst.n")
9445     parseDirectiveInst(DirectiveID.getLoc(), 'n');
9446   else if (IDVal == ".inst.w")
9447     parseDirectiveInst(DirectiveID.getLoc(), 'w');
9448   else if (!IsMachO && !IsCOFF) {
9449     if (IDVal == ".arch")
9450       parseDirectiveArch(DirectiveID.getLoc());
9451     else if (IDVal == ".cpu")
9452       parseDirectiveCPU(DirectiveID.getLoc());
9453     else if (IDVal == ".eabi_attribute")
9454       parseDirectiveEabiAttr(DirectiveID.getLoc());
9455     else if (IDVal == ".fpu")
9456       parseDirectiveFPU(DirectiveID.getLoc());
9457     else if (IDVal == ".fnstart")
9458       parseDirectiveFnStart(DirectiveID.getLoc());
9459     else if (IDVal == ".object_arch")
9460       parseDirectiveObjectArch(DirectiveID.getLoc());
9461     else if (IDVal == ".tlsdescseq")
9462       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9463     else
9464       return true;
9465   } else
9466     return true;
9467   return false;
9468 }
9469
9470 /// parseLiteralValues
9471 ///  ::= .hword expression [, expression]*
9472 ///  ::= .short expression [, expression]*
9473 ///  ::= .word expression [, expression]*
9474 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9475   auto parseOne = [&]() -> bool {
9476     const MCExpr *Value;
9477     if (getParser().parseExpression(Value))
9478       return true;
9479     getParser().getStreamer().EmitValue(Value, Size, L);
9480     return false;
9481   };
9482   return (parseMany(parseOne));
9483 }
9484
9485 /// parseDirectiveThumb
9486 ///  ::= .thumb
9487 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9488   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9489       check(!hasThumb(), L, "target does not support Thumb mode"))
9490     return true;
9491
9492   if (!isThumb())
9493     SwitchMode();
9494
9495   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9496   return false;
9497 }
9498
9499 /// parseDirectiveARM
9500 ///  ::= .arm
9501 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9502   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9503       check(!hasARM(), L, "target does not support ARM mode"))
9504     return true;
9505
9506   if (isThumb())
9507     SwitchMode();
9508   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9509   return false;
9510 }
9511
9512 void ARMAsmParser::doBeforeLabelEmit(MCSymbol *Symbol) {
9513   // We need to flush the current implicit IT block on a label, because it is
9514   // not legal to branch into an IT block.
9515   flushPendingInstructions(getStreamer());
9516 }
9517
9518 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9519   if (NextSymbolIsThumb) {
9520     getParser().getStreamer().EmitThumbFunc(Symbol);
9521     NextSymbolIsThumb = false;
9522   }
9523 }
9524
9525 /// parseDirectiveThumbFunc
9526 ///  ::= .thumbfunc symbol_name
9527 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9528   MCAsmParser &Parser = getParser();
9529   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9530   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9531
9532   // Darwin asm has (optionally) function name after .thumb_func direction
9533   // ELF doesn't
9534
9535   if (IsMachO) {
9536     if (Parser.getTok().is(AsmToken::Identifier) ||
9537         Parser.getTok().is(AsmToken::String)) {
9538       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9539           Parser.getTok().getIdentifier());
9540       getParser().getStreamer().EmitThumbFunc(Func);
9541       Parser.Lex();
9542       if (parseToken(AsmToken::EndOfStatement,
9543                      "unexpected token in '.thumb_func' directive"))
9544         return true;
9545       return false;
9546     }
9547   }
9548
9549   if (parseToken(AsmToken::EndOfStatement,
9550                  "unexpected token in '.thumb_func' directive"))
9551     return true;
9552
9553   NextSymbolIsThumb = true;
9554   return false;
9555 }
9556
9557 /// parseDirectiveSyntax
9558 ///  ::= .syntax unified | divided
9559 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9560   MCAsmParser &Parser = getParser();
9561   const AsmToken &Tok = Parser.getTok();
9562   if (Tok.isNot(AsmToken::Identifier)) {
9563     Error(L, "unexpected token in .syntax directive");
9564     return false;
9565   }
9566
9567   StringRef Mode = Tok.getString();
9568   Parser.Lex();
9569   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9570             "'.syntax divided' arm assembly not supported") ||
9571       check(Mode != "unified" && Mode != "UNIFIED", L,
9572             "unrecognized syntax mode in .syntax directive") ||
9573       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9574     return true;
9575
9576   // TODO tell the MC streamer the mode
9577   // getParser().getStreamer().Emit???();
9578   return false;
9579 }
9580
9581 /// parseDirectiveCode
9582 ///  ::= .code 16 | 32
9583 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9584   MCAsmParser &Parser = getParser();
9585   const AsmToken &Tok = Parser.getTok();
9586   if (Tok.isNot(AsmToken::Integer))
9587     return Error(L, "unexpected token in .code directive");
9588   int64_t Val = Parser.getTok().getIntVal();
9589   if (Val != 16 && Val != 32) {
9590     Error(L, "invalid operand to .code directive");
9591     return false;
9592   }
9593   Parser.Lex();
9594
9595   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9596     return true;
9597
9598   if (Val == 16) {
9599     if (!hasThumb())
9600       return Error(L, "target does not support Thumb mode");
9601
9602     if (!isThumb())
9603       SwitchMode();
9604     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9605   } else {
9606     if (!hasARM())
9607       return Error(L, "target does not support ARM mode");
9608
9609     if (isThumb())
9610       SwitchMode();
9611     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9612   }
9613
9614   return false;
9615 }
9616
9617 /// parseDirectiveReq
9618 ///  ::= name .req registername
9619 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9620   MCAsmParser &Parser = getParser();
9621   Parser.Lex(); // Eat the '.req' token.
9622   unsigned Reg;
9623   SMLoc SRegLoc, ERegLoc;
9624   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9625             "register name expected") ||
9626       parseToken(AsmToken::EndOfStatement,
9627                  "unexpected input in .req directive."))
9628     return true;
9629
9630   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9631     return Error(SRegLoc,
9632                  "redefinition of '" + Name + "' does not match original.");
9633
9634   return false;
9635 }
9636
9637 /// parseDirectiveUneq
9638 ///  ::= .unreq registername
9639 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9640   MCAsmParser &Parser = getParser();
9641   if (Parser.getTok().isNot(AsmToken::Identifier))
9642     return Error(L, "unexpected input in .unreq directive.");
9643   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9644   Parser.Lex(); // Eat the identifier.
9645   if (parseToken(AsmToken::EndOfStatement,
9646                  "unexpected input in '.unreq' directive"))
9647     return true;
9648   return false;
9649 }
9650
9651 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9652 // before, if supported by the new target, or emit mapping symbols for the mode
9653 // switch.
9654 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9655   if (WasThumb != isThumb()) {
9656     if (WasThumb && hasThumb()) {
9657       // Stay in Thumb mode
9658       SwitchMode();
9659     } else if (!WasThumb && hasARM()) {
9660       // Stay in ARM mode
9661       SwitchMode();
9662     } else {
9663       // Mode switch forced, because the new arch doesn't support the old mode.
9664       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9665                                                             : MCAF_Code32);
9666       // Warn about the implcit mode switch. GAS does not switch modes here,
9667       // but instead stays in the old mode, reporting an error on any following
9668       // instructions as the mode does not exist on the target.
9669       Warning(Loc, Twine("new target does not support ") +
9670                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9671                        (!WasThumb ? "thumb" : "arm") + " mode");
9672     }
9673   }
9674 }
9675
9676 /// parseDirectiveArch
9677 ///  ::= .arch token
9678 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9679   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9680   ARM::ArchKind ID = ARM::parseArch(Arch);
9681
9682   if (ID == ARM::ArchKind::INVALID)
9683     return Error(L, "Unknown arch name");
9684
9685   bool WasThumb = isThumb();
9686   Triple T;
9687   MCSubtargetInfo &STI = copySTI();
9688   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9689   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9690   FixModeAfterArchChange(WasThumb, L);
9691
9692   getTargetStreamer().emitArch(ID);
9693   return false;
9694 }
9695
9696 /// parseDirectiveEabiAttr
9697 ///  ::= .eabi_attribute int, int [, "str"]
9698 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9699 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9700   MCAsmParser &Parser = getParser();
9701   int64_t Tag;
9702   SMLoc TagLoc;
9703   TagLoc = Parser.getTok().getLoc();
9704   if (Parser.getTok().is(AsmToken::Identifier)) {
9705     StringRef Name = Parser.getTok().getIdentifier();
9706     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9707     if (Tag == -1) {
9708       Error(TagLoc, "attribute name not recognised: " + Name);
9709       return false;
9710     }
9711     Parser.Lex();
9712   } else {
9713     const MCExpr *AttrExpr;
9714
9715     TagLoc = Parser.getTok().getLoc();
9716     if (Parser.parseExpression(AttrExpr))
9717       return true;
9718
9719     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9720     if (check(!CE, TagLoc, "expected numeric constant"))
9721       return true;
9722
9723     Tag = CE->getValue();
9724   }
9725
9726   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9727     return true;
9728
9729   StringRef StringValue = "";
9730   bool IsStringValue = false;
9731
9732   int64_t IntegerValue = 0;
9733   bool IsIntegerValue = false;
9734
9735   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9736     IsStringValue = true;
9737   else if (Tag == ARMBuildAttrs::compatibility) {
9738     IsStringValue = true;
9739     IsIntegerValue = true;
9740   } else if (Tag < 32 || Tag % 2 == 0)
9741     IsIntegerValue = true;
9742   else if (Tag % 2 == 1)
9743     IsStringValue = true;
9744   else
9745     llvm_unreachable("invalid tag type");
9746
9747   if (IsIntegerValue) {
9748     const MCExpr *ValueExpr;
9749     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9750     if (Parser.parseExpression(ValueExpr))
9751       return true;
9752
9753     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9754     if (!CE)
9755       return Error(ValueExprLoc, "expected numeric constant");
9756     IntegerValue = CE->getValue();
9757   }
9758
9759   if (Tag == ARMBuildAttrs::compatibility) {
9760     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9761       return true;
9762   }
9763
9764   if (IsStringValue) {
9765     if (Parser.getTok().isNot(AsmToken::String))
9766       return Error(Parser.getTok().getLoc(), "bad string constant");
9767
9768     StringValue = Parser.getTok().getStringContents();
9769     Parser.Lex();
9770   }
9771
9772   if (Parser.parseToken(AsmToken::EndOfStatement,
9773                         "unexpected token in '.eabi_attribute' directive"))
9774     return true;
9775
9776   if (IsIntegerValue && IsStringValue) {
9777     assert(Tag == ARMBuildAttrs::compatibility);
9778     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9779   } else if (IsIntegerValue)
9780     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9781   else if (IsStringValue)
9782     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9783   return false;
9784 }
9785
9786 /// parseDirectiveCPU
9787 ///  ::= .cpu str
9788 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9789   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9790   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9791
9792   // FIXME: This is using table-gen data, but should be moved to
9793   // ARMTargetParser once that is table-gen'd.
9794   if (!getSTI().isCPUStringValid(CPU))
9795     return Error(L, "Unknown CPU name");
9796
9797   bool WasThumb = isThumb();
9798   MCSubtargetInfo &STI = copySTI();
9799   STI.setDefaultFeatures(CPU, "");
9800   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9801   FixModeAfterArchChange(WasThumb, L);
9802
9803   return false;
9804 }
9805
9806 /// parseDirectiveFPU
9807 ///  ::= .fpu str
9808 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9809   SMLoc FPUNameLoc = getTok().getLoc();
9810   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9811
9812   unsigned ID = ARM::parseFPU(FPU);
9813   std::vector<StringRef> Features;
9814   if (!ARM::getFPUFeatures(ID, Features))
9815     return Error(FPUNameLoc, "Unknown FPU name");
9816
9817   MCSubtargetInfo &STI = copySTI();
9818   for (auto Feature : Features)
9819     STI.ApplyFeatureFlag(Feature);
9820   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9821
9822   getTargetStreamer().emitFPU(ID);
9823   return false;
9824 }
9825
9826 /// parseDirectiveFnStart
9827 ///  ::= .fnstart
9828 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9829   if (parseToken(AsmToken::EndOfStatement,
9830                  "unexpected token in '.fnstart' directive"))
9831     return true;
9832
9833   if (UC.hasFnStart()) {
9834     Error(L, ".fnstart starts before the end of previous one");
9835     UC.emitFnStartLocNotes();
9836     return true;
9837   }
9838
9839   // Reset the unwind directives parser state
9840   UC.reset();
9841
9842   getTargetStreamer().emitFnStart();
9843
9844   UC.recordFnStart(L);
9845   return false;
9846 }
9847
9848 /// parseDirectiveFnEnd
9849 ///  ::= .fnend
9850 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9851   if (parseToken(AsmToken::EndOfStatement,
9852                  "unexpected token in '.fnend' directive"))
9853     return true;
9854   // Check the ordering of unwind directives
9855   if (!UC.hasFnStart())
9856     return Error(L, ".fnstart must precede .fnend directive");
9857
9858   // Reset the unwind directives parser state
9859   getTargetStreamer().emitFnEnd();
9860
9861   UC.reset();
9862   return false;
9863 }
9864
9865 /// parseDirectiveCantUnwind
9866 ///  ::= .cantunwind
9867 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9868   if (parseToken(AsmToken::EndOfStatement,
9869                  "unexpected token in '.cantunwind' directive"))
9870     return true;
9871
9872   UC.recordCantUnwind(L);
9873   // Check the ordering of unwind directives
9874   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9875     return true;
9876
9877   if (UC.hasHandlerData()) {
9878     Error(L, ".cantunwind can't be used with .handlerdata directive");
9879     UC.emitHandlerDataLocNotes();
9880     return true;
9881   }
9882   if (UC.hasPersonality()) {
9883     Error(L, ".cantunwind can't be used with .personality directive");
9884     UC.emitPersonalityLocNotes();
9885     return true;
9886   }
9887
9888   getTargetStreamer().emitCantUnwind();
9889   return false;
9890 }
9891
9892 /// parseDirectivePersonality
9893 ///  ::= .personality name
9894 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9895   MCAsmParser &Parser = getParser();
9896   bool HasExistingPersonality = UC.hasPersonality();
9897
9898   // Parse the name of the personality routine
9899   if (Parser.getTok().isNot(AsmToken::Identifier))
9900     return Error(L, "unexpected input in .personality directive.");
9901   StringRef Name(Parser.getTok().getIdentifier());
9902   Parser.Lex();
9903
9904   if (parseToken(AsmToken::EndOfStatement,
9905                  "unexpected token in '.personality' directive"))
9906     return true;
9907
9908   UC.recordPersonality(L);
9909
9910   // Check the ordering of unwind directives
9911   if (!UC.hasFnStart())
9912     return Error(L, ".fnstart must precede .personality directive");
9913   if (UC.cantUnwind()) {
9914     Error(L, ".personality can't be used with .cantunwind directive");
9915     UC.emitCantUnwindLocNotes();
9916     return true;
9917   }
9918   if (UC.hasHandlerData()) {
9919     Error(L, ".personality must precede .handlerdata directive");
9920     UC.emitHandlerDataLocNotes();
9921     return true;
9922   }
9923   if (HasExistingPersonality) {
9924     Error(L, "multiple personality directives");
9925     UC.emitPersonalityLocNotes();
9926     return true;
9927   }
9928
9929   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9930   getTargetStreamer().emitPersonality(PR);
9931   return false;
9932 }
9933
9934 /// parseDirectiveHandlerData
9935 ///  ::= .handlerdata
9936 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9937   if (parseToken(AsmToken::EndOfStatement,
9938                  "unexpected token in '.handlerdata' directive"))
9939     return true;
9940
9941   UC.recordHandlerData(L);
9942   // Check the ordering of unwind directives
9943   if (!UC.hasFnStart())
9944     return Error(L, ".fnstart must precede .personality directive");
9945   if (UC.cantUnwind()) {
9946     Error(L, ".handlerdata can't be used with .cantunwind directive");
9947     UC.emitCantUnwindLocNotes();
9948     return true;
9949   }
9950
9951   getTargetStreamer().emitHandlerData();
9952   return false;
9953 }
9954
9955 /// parseDirectiveSetFP
9956 ///  ::= .setfp fpreg, spreg [, offset]
9957 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9958   MCAsmParser &Parser = getParser();
9959   // Check the ordering of unwind directives
9960   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9961       check(UC.hasHandlerData(), L,
9962             ".setfp must precede .handlerdata directive"))
9963     return true;
9964
9965   // Parse fpreg
9966   SMLoc FPRegLoc = Parser.getTok().getLoc();
9967   int FPReg = tryParseRegister();
9968
9969   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9970       Parser.parseToken(AsmToken::Comma, "comma expected"))
9971     return true;
9972
9973   // Parse spreg
9974   SMLoc SPRegLoc = Parser.getTok().getLoc();
9975   int SPReg = tryParseRegister();
9976   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9977       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9978             "register should be either $sp or the latest fp register"))
9979     return true;
9980
9981   // Update the frame pointer register
9982   UC.saveFPReg(FPReg);
9983
9984   // Parse offset
9985   int64_t Offset = 0;
9986   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9987     if (Parser.getTok().isNot(AsmToken::Hash) &&
9988         Parser.getTok().isNot(AsmToken::Dollar))
9989       return Error(Parser.getTok().getLoc(), "'#' expected");
9990     Parser.Lex(); // skip hash token.
9991
9992     const MCExpr *OffsetExpr;
9993     SMLoc ExLoc = Parser.getTok().getLoc();
9994     SMLoc EndLoc;
9995     if (getParser().parseExpression(OffsetExpr, EndLoc))
9996       return Error(ExLoc, "malformed setfp offset");
9997     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9998     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9999       return true;
10000     Offset = CE->getValue();
10001   }
10002
10003   if (Parser.parseToken(AsmToken::EndOfStatement))
10004     return true;
10005
10006   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
10007                                 static_cast<unsigned>(SPReg), Offset);
10008   return false;
10009 }
10010
10011 /// parseDirective
10012 ///  ::= .pad offset
10013 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
10014   MCAsmParser &Parser = getParser();
10015   // Check the ordering of unwind directives
10016   if (!UC.hasFnStart())
10017     return Error(L, ".fnstart must precede .pad directive");
10018   if (UC.hasHandlerData())
10019     return Error(L, ".pad must precede .handlerdata directive");
10020
10021   // Parse the offset
10022   if (Parser.getTok().isNot(AsmToken::Hash) &&
10023       Parser.getTok().isNot(AsmToken::Dollar))
10024     return Error(Parser.getTok().getLoc(), "'#' expected");
10025   Parser.Lex(); // skip hash token.
10026
10027   const MCExpr *OffsetExpr;
10028   SMLoc ExLoc = Parser.getTok().getLoc();
10029   SMLoc EndLoc;
10030   if (getParser().parseExpression(OffsetExpr, EndLoc))
10031     return Error(ExLoc, "malformed pad offset");
10032   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10033   if (!CE)
10034     return Error(ExLoc, "pad offset must be an immediate");
10035
10036   if (parseToken(AsmToken::EndOfStatement,
10037                  "unexpected token in '.pad' directive"))
10038     return true;
10039
10040   getTargetStreamer().emitPad(CE->getValue());
10041   return false;
10042 }
10043
10044 /// parseDirectiveRegSave
10045 ///  ::= .save  { registers }
10046 ///  ::= .vsave { registers }
10047 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
10048   // Check the ordering of unwind directives
10049   if (!UC.hasFnStart())
10050     return Error(L, ".fnstart must precede .save or .vsave directives");
10051   if (UC.hasHandlerData())
10052     return Error(L, ".save or .vsave must precede .handlerdata directive");
10053
10054   // RAII object to make sure parsed operands are deleted.
10055   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
10056
10057   // Parse the register list
10058   if (parseRegisterList(Operands) ||
10059       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10060     return true;
10061   ARMOperand &Op = (ARMOperand &)*Operands[0];
10062   if (!IsVector && !Op.isRegList())
10063     return Error(L, ".save expects GPR registers");
10064   if (IsVector && !Op.isDPRRegList())
10065     return Error(L, ".vsave expects DPR registers");
10066
10067   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
10068   return false;
10069 }
10070
10071 /// parseDirectiveInst
10072 ///  ::= .inst opcode [, ...]
10073 ///  ::= .inst.n opcode [, ...]
10074 ///  ::= .inst.w opcode [, ...]
10075 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
10076   int Width = 4;
10077
10078   if (isThumb()) {
10079     switch (Suffix) {
10080     case 'n':
10081       Width = 2;
10082       break;
10083     case 'w':
10084       break;
10085     default:
10086       Width = 0;
10087       break;
10088     }
10089   } else {
10090     if (Suffix)
10091       return Error(Loc, "width suffixes are invalid in ARM mode");
10092   }
10093
10094   auto parseOne = [&]() -> bool {
10095     const MCExpr *Expr;
10096     if (getParser().parseExpression(Expr))
10097       return true;
10098     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
10099     if (!Value) {
10100       return Error(Loc, "expected constant expression");
10101     }
10102
10103     char CurSuffix = Suffix;
10104     switch (Width) {
10105     case 2:
10106       if (Value->getValue() > 0xffff)
10107         return Error(Loc, "inst.n operand is too big, use inst.w instead");
10108       break;
10109     case 4:
10110       if (Value->getValue() > 0xffffffff)
10111         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
10112                               " operand is too big");
10113       break;
10114     case 0:
10115       // Thumb mode, no width indicated. Guess from the opcode, if possible.
10116       if (Value->getValue() < 0xe800)
10117         CurSuffix = 'n';
10118       else if (Value->getValue() >= 0xe8000000)
10119         CurSuffix = 'w';
10120       else
10121         return Error(Loc, "cannot determine Thumb instruction size, "
10122                           "use inst.n/inst.w instead");
10123       break;
10124     default:
10125       llvm_unreachable("only supported widths are 2 and 4");
10126     }
10127
10128     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
10129     return false;
10130   };
10131
10132   if (parseOptionalToken(AsmToken::EndOfStatement))
10133     return Error(Loc, "expected expression following directive");
10134   if (parseMany(parseOne))
10135     return true;
10136   return false;
10137 }
10138
10139 /// parseDirectiveLtorg
10140 ///  ::= .ltorg | .pool
10141 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
10142   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10143     return true;
10144   getTargetStreamer().emitCurrentConstantPool();
10145   return false;
10146 }
10147
10148 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
10149   const MCSection *Section = getStreamer().getCurrentSectionOnly();
10150
10151   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10152     return true;
10153
10154   if (!Section) {
10155     getStreamer().InitSections(false);
10156     Section = getStreamer().getCurrentSectionOnly();
10157   }
10158
10159   assert(Section && "must have section to emit alignment");
10160   if (Section->UseCodeAlign())
10161     getStreamer().EmitCodeAlignment(2);
10162   else
10163     getStreamer().EmitValueToAlignment(2);
10164
10165   return false;
10166 }
10167
10168 /// parseDirectivePersonalityIndex
10169 ///   ::= .personalityindex index
10170 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
10171   MCAsmParser &Parser = getParser();
10172   bool HasExistingPersonality = UC.hasPersonality();
10173
10174   const MCExpr *IndexExpression;
10175   SMLoc IndexLoc = Parser.getTok().getLoc();
10176   if (Parser.parseExpression(IndexExpression) ||
10177       parseToken(AsmToken::EndOfStatement,
10178                  "unexpected token in '.personalityindex' directive")) {
10179     return true;
10180   }
10181
10182   UC.recordPersonalityIndex(L);
10183
10184   if (!UC.hasFnStart()) {
10185     return Error(L, ".fnstart must precede .personalityindex directive");
10186   }
10187   if (UC.cantUnwind()) {
10188     Error(L, ".personalityindex cannot be used with .cantunwind");
10189     UC.emitCantUnwindLocNotes();
10190     return true;
10191   }
10192   if (UC.hasHandlerData()) {
10193     Error(L, ".personalityindex must precede .handlerdata directive");
10194     UC.emitHandlerDataLocNotes();
10195     return true;
10196   }
10197   if (HasExistingPersonality) {
10198     Error(L, "multiple personality directives");
10199     UC.emitPersonalityLocNotes();
10200     return true;
10201   }
10202
10203   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
10204   if (!CE)
10205     return Error(IndexLoc, "index must be a constant number");
10206   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
10207     return Error(IndexLoc,
10208                  "personality routine index should be in range [0-3]");
10209
10210   getTargetStreamer().emitPersonalityIndex(CE->getValue());
10211   return false;
10212 }
10213
10214 /// parseDirectiveUnwindRaw
10215 ///   ::= .unwind_raw offset, opcode [, opcode...]
10216 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
10217   MCAsmParser &Parser = getParser();
10218   int64_t StackOffset;
10219   const MCExpr *OffsetExpr;
10220   SMLoc OffsetLoc = getLexer().getLoc();
10221
10222   if (!UC.hasFnStart())
10223     return Error(L, ".fnstart must precede .unwind_raw directives");
10224   if (getParser().parseExpression(OffsetExpr))
10225     return Error(OffsetLoc, "expected expression");
10226
10227   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10228   if (!CE)
10229     return Error(OffsetLoc, "offset must be a constant");
10230
10231   StackOffset = CE->getValue();
10232
10233   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
10234     return true;
10235
10236   SmallVector<uint8_t, 16> Opcodes;
10237
10238   auto parseOne = [&]() -> bool {
10239     const MCExpr *OE;
10240     SMLoc OpcodeLoc = getLexer().getLoc();
10241     if (check(getLexer().is(AsmToken::EndOfStatement) ||
10242                   Parser.parseExpression(OE),
10243               OpcodeLoc, "expected opcode expression"))
10244       return true;
10245     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
10246     if (!OC)
10247       return Error(OpcodeLoc, "opcode value must be a constant");
10248     const int64_t Opcode = OC->getValue();
10249     if (Opcode & ~0xff)
10250       return Error(OpcodeLoc, "invalid opcode");
10251     Opcodes.push_back(uint8_t(Opcode));
10252     return false;
10253   };
10254
10255   // Must have at least 1 element
10256   SMLoc OpcodeLoc = getLexer().getLoc();
10257   if (parseOptionalToken(AsmToken::EndOfStatement))
10258     return Error(OpcodeLoc, "expected opcode expression");
10259   if (parseMany(parseOne))
10260     return true;
10261
10262   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
10263   return false;
10264 }
10265
10266 /// parseDirectiveTLSDescSeq
10267 ///   ::= .tlsdescseq tls-variable
10268 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
10269   MCAsmParser &Parser = getParser();
10270
10271   if (getLexer().isNot(AsmToken::Identifier))
10272     return TokError("expected variable after '.tlsdescseq' directive");
10273
10274   const MCSymbolRefExpr *SRE =
10275     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
10276                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
10277   Lex();
10278
10279   if (parseToken(AsmToken::EndOfStatement,
10280                  "unexpected token in '.tlsdescseq' directive"))
10281     return true;
10282
10283   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10284   return false;
10285 }
10286
10287 /// parseDirectiveMovSP
10288 ///  ::= .movsp reg [, #offset]
10289 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10290   MCAsmParser &Parser = getParser();
10291   if (!UC.hasFnStart())
10292     return Error(L, ".fnstart must precede .movsp directives");
10293   if (UC.getFPReg() != ARM::SP)
10294     return Error(L, "unexpected .movsp directive");
10295
10296   SMLoc SPRegLoc = Parser.getTok().getLoc();
10297   int SPReg = tryParseRegister();
10298   if (SPReg == -1)
10299     return Error(SPRegLoc, "register expected");
10300   if (SPReg == ARM::SP || SPReg == ARM::PC)
10301     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10302
10303   int64_t Offset = 0;
10304   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10305     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10306       return true;
10307
10308     const MCExpr *OffsetExpr;
10309     SMLoc OffsetLoc = Parser.getTok().getLoc();
10310
10311     if (Parser.parseExpression(OffsetExpr))
10312       return Error(OffsetLoc, "malformed offset expression");
10313
10314     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10315     if (!CE)
10316       return Error(OffsetLoc, "offset must be an immediate constant");
10317
10318     Offset = CE->getValue();
10319   }
10320
10321   if (parseToken(AsmToken::EndOfStatement,
10322                  "unexpected token in '.movsp' directive"))
10323     return true;
10324
10325   getTargetStreamer().emitMovSP(SPReg, Offset);
10326   UC.saveFPReg(SPReg);
10327
10328   return false;
10329 }
10330
10331 /// parseDirectiveObjectArch
10332 ///   ::= .object_arch name
10333 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10334   MCAsmParser &Parser = getParser();
10335   if (getLexer().isNot(AsmToken::Identifier))
10336     return Error(getLexer().getLoc(), "unexpected token");
10337
10338   StringRef Arch = Parser.getTok().getString();
10339   SMLoc ArchLoc = Parser.getTok().getLoc();
10340   Lex();
10341
10342   ARM::ArchKind ID = ARM::parseArch(Arch);
10343
10344   if (ID == ARM::ArchKind::INVALID)
10345     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10346   if (parseToken(AsmToken::EndOfStatement))
10347     return true;
10348
10349   getTargetStreamer().emitObjectArch(ID);
10350   return false;
10351 }
10352
10353 /// parseDirectiveAlign
10354 ///   ::= .align
10355 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10356   // NOTE: if this is not the end of the statement, fall back to the target
10357   // agnostic handling for this directive which will correctly handle this.
10358   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10359     // '.align' is target specifically handled to mean 2**2 byte alignment.
10360     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10361     assert(Section && "must have section to emit alignment");
10362     if (Section->UseCodeAlign())
10363       getStreamer().EmitCodeAlignment(4, 0);
10364     else
10365       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10366     return false;
10367   }
10368   return true;
10369 }
10370
10371 /// parseDirectiveThumbSet
10372 ///  ::= .thumb_set name, value
10373 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10374   MCAsmParser &Parser = getParser();
10375
10376   StringRef Name;
10377   if (check(Parser.parseIdentifier(Name),
10378             "expected identifier after '.thumb_set'") ||
10379       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10380     return true;
10381
10382   MCSymbol *Sym;
10383   const MCExpr *Value;
10384   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10385                                                Parser, Sym, Value))
10386     return true;
10387
10388   getTargetStreamer().emitThumbSet(Sym, Value);
10389   return false;
10390 }
10391
10392 /// Force static initialization.
10393 extern "C" void LLVMInitializeARMAsmParser() {
10394   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10395   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10396   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10397   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10398 }
10399
10400 #define GET_REGISTER_MATCHER
10401 #define GET_SUBTARGET_FEATURE_NAME
10402 #define GET_MATCHER_IMPLEMENTATION
10403 #define GET_MNEMONIC_SPELL_CHECKER
10404 #include "ARMGenAsmMatcher.inc"
10405
10406 // Some diagnostics need to vary with subtarget features, so they are handled
10407 // here. For example, the DPR class has either 16 or 32 registers, depending
10408 // on the FPU available.
10409 const char *
10410 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
10411   switch (MatchError) {
10412   // rGPR contains sp starting with ARMv8.
10413   case Match_rGPR:
10414     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
10415                       : "operand must be a register in range [r0, r12] or r14";
10416   // DPR contains 16 registers for some FPUs, and 32 for others.
10417   case Match_DPR:
10418     return hasD32() ? "operand must be a register in range [d0, d31]"
10419                     : "operand must be a register in range [d0, d15]";
10420   case Match_DPR_RegList:
10421     return hasD32() ? "operand must be a list of registers in range [d0, d31]"
10422                     : "operand must be a list of registers in range [d0, d15]";
10423
10424   // For all other diags, use the static string from tablegen.
10425   default:
10426     return getMatchKindDiag(MatchError);
10427   }
10428 }
10429
10430 // Process the list of near-misses, throwing away ones we don't want to report
10431 // to the user, and converting the rest to a source location and string that
10432 // should be reported.
10433 void
10434 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
10435                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
10436                                SMLoc IDLoc, OperandVector &Operands) {
10437   // TODO: If operand didn't match, sub in a dummy one and run target
10438   // predicate, so that we can avoid reporting near-misses that are invalid?
10439   // TODO: Many operand types dont have SuperClasses set, so we report
10440   // redundant ones.
10441   // TODO: Some operands are superclasses of registers (e.g.
10442   // MCK_RegShiftedImm), we don't have any way to represent that currently.
10443   // TODO: This is not all ARM-specific, can some of it be factored out?
10444
10445   // Record some information about near-misses that we have already seen, so
10446   // that we can avoid reporting redundant ones. For example, if there are
10447   // variants of an instruction that take 8- and 16-bit immediates, we want
10448   // to only report the widest one.
10449   std::multimap<unsigned, unsigned> OperandMissesSeen;
10450   SmallSet<FeatureBitset, 4> FeatureMissesSeen;
10451   bool ReportedTooFewOperands = false;
10452
10453   // Process the near-misses in reverse order, so that we see more general ones
10454   // first, and so can avoid emitting more specific ones.
10455   for (NearMissInfo &I : reverse(NearMissesIn)) {
10456     switch (I.getKind()) {
10457     case NearMissInfo::NearMissOperand: {
10458       SMLoc OperandLoc =
10459           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
10460       const char *OperandDiag =
10461           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
10462
10463       // If we have already emitted a message for a superclass, don't also report
10464       // the sub-class. We consider all operand classes that we don't have a
10465       // specialised diagnostic for to be equal for the propose of this check,
10466       // so that we don't report the generic error multiple times on the same
10467       // operand.
10468       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
10469       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
10470       if (std::any_of(PrevReports.first, PrevReports.second,
10471                       [DupCheckMatchClass](
10472                           const std::pair<unsigned, unsigned> Pair) {
10473             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
10474               return Pair.second == DupCheckMatchClass;
10475             else
10476               return isSubclass((MatchClassKind)DupCheckMatchClass,
10477                                 (MatchClassKind)Pair.second);
10478           }))
10479         break;
10480       OperandMissesSeen.insert(
10481           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
10482
10483       NearMissMessage Message;
10484       Message.Loc = OperandLoc;
10485       if (OperandDiag) {
10486         Message.Message = OperandDiag;
10487       } else if (I.getOperandClass() == InvalidMatchClass) {
10488         Message.Message = "too many operands for instruction";
10489       } else {
10490         Message.Message = "invalid operand for instruction";
10491         LLVM_DEBUG(
10492             dbgs() << "Missing diagnostic string for operand class "
10493                    << getMatchClassName((MatchClassKind)I.getOperandClass())
10494                    << I.getOperandClass() << ", error " << I.getOperandError()
10495                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
10496       }
10497       NearMissesOut.emplace_back(Message);
10498       break;
10499     }
10500     case NearMissInfo::NearMissFeature: {
10501       const FeatureBitset &MissingFeatures = I.getFeatures();
10502       // Don't report the same set of features twice.
10503       if (FeatureMissesSeen.count(MissingFeatures))
10504         break;
10505       FeatureMissesSeen.insert(MissingFeatures);
10506
10507       // Special case: don't report a feature set which includes arm-mode for
10508       // targets that don't have ARM mode.
10509       if (MissingFeatures.test(Feature_IsARMBit) && !hasARM())
10510         break;
10511       // Don't report any near-misses that both require switching instruction
10512       // set, and adding other subtarget features.
10513       if (isThumb() && MissingFeatures.test(Feature_IsARMBit) &&
10514           MissingFeatures.count() > 1)
10515         break;
10516       if (!isThumb() && MissingFeatures.test(Feature_IsThumbBit) &&
10517           MissingFeatures.count() > 1)
10518         break;
10519       if (!isThumb() && MissingFeatures.test(Feature_IsThumb2Bit) &&
10520           (MissingFeatures & ~FeatureBitset({Feature_IsThumb2Bit,
10521                                              Feature_IsThumbBit})).any())
10522         break;
10523       if (isMClass() && MissingFeatures.test(Feature_HasNEONBit))
10524         break;
10525
10526       NearMissMessage Message;
10527       Message.Loc = IDLoc;
10528       raw_svector_ostream OS(Message.Message);
10529
10530       OS << "instruction requires:";
10531       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
10532         if (MissingFeatures.test(i))
10533           OS << ' ' << getSubtargetFeatureName(i);
10534
10535       NearMissesOut.emplace_back(Message);
10536
10537       break;
10538     }
10539     case NearMissInfo::NearMissPredicate: {
10540       NearMissMessage Message;
10541       Message.Loc = IDLoc;
10542       switch (I.getPredicateError()) {
10543       case Match_RequiresNotITBlock:
10544         Message.Message = "flag setting instruction only valid outside IT block";
10545         break;
10546       case Match_RequiresITBlock:
10547         Message.Message = "instruction only valid inside IT block";
10548         break;
10549       case Match_RequiresV6:
10550         Message.Message = "instruction variant requires ARMv6 or later";
10551         break;
10552       case Match_RequiresThumb2:
10553         Message.Message = "instruction variant requires Thumb2";
10554         break;
10555       case Match_RequiresV8:
10556         Message.Message = "instruction variant requires ARMv8 or later";
10557         break;
10558       case Match_RequiresFlagSetting:
10559         Message.Message = "no flag-preserving variant of this instruction available";
10560         break;
10561       case Match_InvalidOperand:
10562         Message.Message = "invalid operand for instruction";
10563         break;
10564       default:
10565         llvm_unreachable("Unhandled target predicate error");
10566         break;
10567       }
10568       NearMissesOut.emplace_back(Message);
10569       break;
10570     }
10571     case NearMissInfo::NearMissTooFewOperands: {
10572       if (!ReportedTooFewOperands) {
10573         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
10574         NearMissesOut.emplace_back(NearMissMessage{
10575             EndLoc, StringRef("too few operands for instruction")});
10576         ReportedTooFewOperands = true;
10577       }
10578       break;
10579     }
10580     case NearMissInfo::NoNearMiss:
10581       // This should never leave the matcher.
10582       llvm_unreachable("not a near-miss");
10583       break;
10584     }
10585   }
10586 }
10587
10588 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
10589                                     SMLoc IDLoc, OperandVector &Operands) {
10590   SmallVector<NearMissMessage, 4> Messages;
10591   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
10592
10593   if (Messages.size() == 0) {
10594     // No near-misses were found, so the best we can do is "invalid
10595     // instruction".
10596     Error(IDLoc, "invalid instruction");
10597   } else if (Messages.size() == 1) {
10598     // One near miss was found, report it as the sole error.
10599     Error(Messages[0].Loc, Messages[0].Message);
10600   } else {
10601     // More than one near miss, so report a generic "invalid instruction"
10602     // error, followed by notes for each of the near-misses.
10603     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
10604     for (auto &M : Messages) {
10605       Note(M.Loc, M.Message);
10606     }
10607   }
10608 }
10609
10610 /// parseDirectiveArchExtension
10611 ///   ::= .arch_extension [no]feature
10612 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10613   // FIXME: This structure should be moved inside ARMTargetParser
10614   // when we start to table-generate them, and we can use the ARM
10615   // flags below, that were generated by table-gen.
10616   static const struct {
10617     const unsigned Kind;
10618     const FeatureBitset ArchCheck;
10619     const FeatureBitset Features;
10620   } Extensions[] = {
10621     { ARM::AEK_CRC, {Feature_HasV8Bit}, {ARM::FeatureCRC} },
10622     { ARM::AEK_CRYPTO,  {Feature_HasV8Bit},
10623       {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10624     { ARM::AEK_FP, {Feature_HasV8Bit},
10625       {ARM::FeatureVFP2_D16_SP, ARM::FeatureFPARMv8} },
10626     { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM),
10627       {Feature_HasV7Bit, Feature_IsNotMClassBit},
10628       {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10629     { ARM::AEK_MP, {Feature_HasV7Bit, Feature_IsNotMClassBit},
10630       {ARM::FeatureMP} },
10631     { ARM::AEK_SIMD, {Feature_HasV8Bit},
10632       {ARM::FeatureNEON, ARM::FeatureVFP2_D16_SP, ARM::FeatureFPARMv8} },
10633     { ARM::AEK_SEC, {Feature_HasV6KBit}, {ARM::FeatureTrustZone} },
10634     // FIXME: Only available in A-class, isel not predicated
10635     { ARM::AEK_VIRT, {Feature_HasV7Bit}, {ARM::FeatureVirtualization} },
10636     { ARM::AEK_FP16, {Feature_HasV8_2aBit},
10637       {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10638     { ARM::AEK_RAS, {Feature_HasV8Bit}, {ARM::FeatureRAS} },
10639     // FIXME: Unsupported extensions.
10640     { ARM::AEK_OS, {}, {} },
10641     { ARM::AEK_IWMMXT, {}, {} },
10642     { ARM::AEK_IWMMXT2, {}, {} },
10643     { ARM::AEK_MAVERICK, {}, {} },
10644     { ARM::AEK_XSCALE, {}, {} },
10645   };
10646
10647   MCAsmParser &Parser = getParser();
10648
10649   if (getLexer().isNot(AsmToken::Identifier))
10650     return Error(getLexer().getLoc(), "expected architecture extension name");
10651
10652   StringRef Name = Parser.getTok().getString();
10653   SMLoc ExtLoc = Parser.getTok().getLoc();
10654   Lex();
10655
10656   if (parseToken(AsmToken::EndOfStatement,
10657                  "unexpected token in '.arch_extension' directive"))
10658     return true;
10659
10660   bool EnableFeature = true;
10661   if (Name.startswith_lower("no")) {
10662     EnableFeature = false;
10663     Name = Name.substr(2);
10664   }
10665   unsigned FeatureKind = ARM::parseArchExt(Name);
10666   if (FeatureKind == ARM::AEK_INVALID)
10667     return Error(ExtLoc, "unknown architectural extension: " + Name);
10668
10669   for (const auto &Extension : Extensions) {
10670     if (Extension.Kind != FeatureKind)
10671       continue;
10672
10673     if (Extension.Features.none())
10674       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10675
10676     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10677       return Error(ExtLoc, "architectural extension '" + Name +
10678                                "' is not "
10679                                "allowed for the current base architecture");
10680
10681     MCSubtargetInfo &STI = copySTI();
10682     if (EnableFeature) {
10683       STI.SetFeatureBitsTransitively(Extension.Features);
10684     } else {
10685       STI.ClearFeatureBitsTransitively(Extension.Features);
10686     }
10687     FeatureBitset Features = ComputeAvailableFeatures(STI.getFeatureBits());
10688     setAvailableFeatures(Features);
10689     return false;
10690   }
10691
10692   return Error(ExtLoc, "unknown architectural extension: " + Name);
10693 }
10694
10695 // Define this matcher function after the auto-generated include so we
10696 // have the match class enum definitions.
10697 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10698                                                   unsigned Kind) {
10699   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10700   // If the kind is a token for a literal immediate, check if our asm
10701   // operand matches. This is for InstAliases which have a fixed-value
10702   // immediate in the syntax.
10703   switch (Kind) {
10704   default: break;
10705   case MCK__35_0:
10706     if (Op.isImm())
10707       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10708         if (CE->getValue() == 0)
10709           return Match_Success;
10710     break;
10711   case MCK_ModImm:
10712     if (Op.isImm()) {
10713       const MCExpr *SOExpr = Op.getImm();
10714       int64_t Value;
10715       if (!SOExpr->evaluateAsAbsolute(Value))
10716         return Match_Success;
10717       assert((Value >= std::numeric_limits<int32_t>::min() &&
10718               Value <= std::numeric_limits<uint32_t>::max()) &&
10719              "expression value must be representable in 32 bits");
10720     }
10721     break;
10722   case MCK_rGPR:
10723     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10724       return Match_Success;
10725     return Match_rGPR;
10726   case MCK_GPRPair:
10727     if (Op.isReg() &&
10728         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10729       return Match_Success;
10730     break;
10731   }
10732   return Match_InvalidOperand;
10733 }