1 //===-- HexagonAsmParser.cpp - Parse Hexagon asm 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 #define DEBUG_TYPE "mcasmparser"
10 
11 #include "HexagonTargetStreamer.h"
12 #include "MCTargetDesc/HexagonMCChecker.h"
13 #include "MCTargetDesc/HexagonMCELFStreamer.h"
14 #include "MCTargetDesc/HexagonMCExpr.h"
15 #include "MCTargetDesc/HexagonMCInstrInfo.h"
16 #include "MCTargetDesc/HexagonMCTargetDesc.h"
17 #include "MCTargetDesc/HexagonShuffler.h"
18 #include "TargetInfo/HexagonTargetInfo.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/BinaryFormat/ELF.h"
25 #include "llvm/MC/MCAssembler.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDirectives.h"
28 #include "llvm/MC/MCELFStreamer.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCParser/MCAsmLexer.h"
32 #include "llvm/MC/MCParser/MCAsmParser.h"
33 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
34 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
35 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
36 #include "llvm/MC/MCRegisterInfo.h"
37 #include "llvm/MC/MCSectionELF.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSubtargetInfo.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/MC/MCValue.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/SMLoc.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include <algorithm>
53 #include <cassert>
54 #include <cctype>
55 #include <cstddef>
56 #include <cstdint>
57 #include <memory>
58 #include <string>
59 #include <utility>
60 
61 using namespace llvm;
62 
63 static cl::opt<bool> WarnMissingParenthesis(
64     "mwarn-missing-parenthesis",
65     cl::desc("Warn for missing parenthesis around predicate registers"),
66     cl::init(true));
67 static cl::opt<bool> ErrorMissingParenthesis(
68     "merror-missing-parenthesis",
69     cl::desc("Error for missing parenthesis around predicate registers"),
70     cl::init(false));
71 static cl::opt<bool> WarnSignedMismatch(
72     "mwarn-sign-mismatch",
73     cl::desc("Warn for mismatching a signed and unsigned value"),
74     cl::init(true));
75 static cl::opt<bool> WarnNoncontigiousRegister(
76     "mwarn-noncontigious-register",
77     cl::desc("Warn for register names that arent contigious"), cl::init(true));
78 static cl::opt<bool> ErrorNoncontigiousRegister(
79     "merror-noncontigious-register",
80     cl::desc("Error for register names that aren't contigious"),
81     cl::init(false));
82 
83 namespace {
84 
85 struct HexagonOperand;
86 
87 class HexagonAsmParser : public MCTargetAsmParser {
88 
89   HexagonTargetStreamer &getTargetStreamer() {
90     MCTargetStreamer &TS = *Parser.getStreamer().getTargetStreamer();
91     return static_cast<HexagonTargetStreamer &>(TS);
92   }
93 
94   MCAsmParser &Parser;
95   MCInst MCB;
96   bool InBrackets;
97 
98   MCAsmParser &getParser() const { return Parser; }
99   MCAssembler *getAssembler() const {
100     MCAssembler *Assembler = nullptr;
101     // FIXME: need better way to detect AsmStreamer (upstream removed getKind())
102     if (!Parser.getStreamer().hasRawTextSupport()) {
103       MCELFStreamer *MES = static_cast<MCELFStreamer *>(&Parser.getStreamer());
104       Assembler = &MES->getAssembler();
105     }
106     return Assembler;
107   }
108 
109   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
110 
111   bool equalIsAsmAssignment() override { return false; }
112   bool isLabel(AsmToken &Token) override;
113 
114   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
115   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
116   bool ParseDirectiveFalign(unsigned Size, SMLoc L);
117 
118   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
119   bool ParseDirectiveSubsection(SMLoc L);
120   bool ParseDirectiveComm(bool IsLocal, SMLoc L);
121   bool RegisterMatchesArch(unsigned MatchNum) const;
122 
123   bool matchBundleOptions();
124   bool handleNoncontigiousRegister(bool Contigious, SMLoc &Loc);
125   bool finishBundle(SMLoc IDLoc, MCStreamer &Out);
126   void canonicalizeImmediates(MCInst &MCI);
127   bool matchOneInstruction(MCInst &MCB, SMLoc IDLoc,
128                            OperandVector &InstOperands, uint64_t &ErrorInfo,
129                            bool MatchingInlineAsm);
130   void eatToEndOfPacket();
131   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
132                                OperandVector &Operands, MCStreamer &Out,
133                                uint64_t &ErrorInfo,
134                                bool MatchingInlineAsm) override;
135 
136   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
137                                       unsigned Kind) override;
138   bool OutOfRange(SMLoc IDLoc, long long Val, long long Max);
139   int processInstruction(MCInst &Inst, OperandVector const &Operands,
140                          SMLoc IDLoc);
141 
142   // Check if we have an assembler and, if so, set the ELF e_header flags.
143   void chksetELFHeaderEFlags(unsigned flags) {
144     if (getAssembler())
145       getAssembler()->setELFHeaderEFlags(flags);
146   }
147 
148   unsigned matchRegister(StringRef Name);
149 
150 /// @name Auto-generated Match Functions
151 /// {
152 
153 #define GET_ASSEMBLER_HEADER
154 #include "HexagonGenAsmMatcher.inc"
155 
156   /// }
157 
158 public:
159   HexagonAsmParser(const MCSubtargetInfo &_STI, MCAsmParser &_Parser,
160                    const MCInstrInfo &MII, const MCTargetOptions &Options)
161     : MCTargetAsmParser(Options, _STI, MII), Parser(_Parser),
162       InBrackets(false) {
163     MCB.setOpcode(Hexagon::BUNDLE);
164     setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
165 
166     Parser.addAliasForDirective(".half", ".2byte");
167     Parser.addAliasForDirective(".hword", ".2byte");
168     Parser.addAliasForDirective(".word", ".4byte");
169 
170     MCAsmParserExtension::Initialize(_Parser);
171   }
172 
173   bool splitIdentifier(OperandVector &Operands);
174   bool parseOperand(OperandVector &Operands);
175   bool parseInstruction(OperandVector &Operands);
176   bool implicitExpressionLocation(OperandVector &Operands);
177   bool parseExpressionOrOperand(OperandVector &Operands);
178   bool parseExpression(MCExpr const *&Expr);
179 
180   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
181                         SMLoc NameLoc, OperandVector &Operands) override {
182     llvm_unreachable("Unimplemented");
183   }
184 
185   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name, AsmToken ID,
186                         OperandVector &Operands) override;
187 
188   bool ParseDirective(AsmToken DirectiveID) override;
189 };
190 
191 /// HexagonOperand - Instances of this class represent a parsed Hexagon machine
192 /// instruction.
193 struct HexagonOperand : public MCParsedAsmOperand {
194   enum KindTy { Token, Immediate, Register } Kind;
195   MCContext &Context;
196 
197   SMLoc StartLoc, EndLoc;
198 
199   struct TokTy {
200     const char *Data;
201     unsigned Length;
202   };
203 
204   struct RegTy {
205     unsigned RegNum;
206   };
207 
208   struct ImmTy {
209     const MCExpr *Val;
210   };
211 
212   struct InstTy {
213     OperandVector *SubInsts;
214   };
215 
216   union {
217     struct TokTy Tok;
218     struct RegTy Reg;
219     struct ImmTy Imm;
220   };
221 
222   HexagonOperand(KindTy K, MCContext &Context)
223       : MCParsedAsmOperand(), Kind(K), Context(Context) {}
224 
225 public:
226   HexagonOperand(const HexagonOperand &o)
227       : MCParsedAsmOperand(), Context(o.Context) {
228     Kind = o.Kind;
229     StartLoc = o.StartLoc;
230     EndLoc = o.EndLoc;
231     switch (Kind) {
232     case Register:
233       Reg = o.Reg;
234       break;
235     case Immediate:
236       Imm = o.Imm;
237       break;
238     case Token:
239       Tok = o.Tok;
240       break;
241     }
242   }
243 
244   /// getStartLoc - Get the location of the first token of this operand.
245   SMLoc getStartLoc() const override { return StartLoc; }
246 
247   /// getEndLoc - Get the location of the last token of this operand.
248   SMLoc getEndLoc() const override { return EndLoc; }
249 
250   unsigned getReg() const override {
251     assert(Kind == Register && "Invalid access!");
252     return Reg.RegNum;
253   }
254 
255   const MCExpr *getImm() const {
256     assert(Kind == Immediate && "Invalid access!");
257     return Imm.Val;
258   }
259 
260   bool isToken() const override { return Kind == Token; }
261   bool isImm() const override { return Kind == Immediate; }
262   bool isMem() const override { llvm_unreachable("No isMem"); }
263   bool isReg() const override { return Kind == Register; }
264 
265   bool CheckImmRange(int immBits, int zeroBits, bool isSigned,
266                      bool isRelocatable, bool Extendable) const {
267     if (Kind == Immediate) {
268       const MCExpr *myMCExpr = &HexagonMCInstrInfo::getExpr(*getImm());
269       if (HexagonMCInstrInfo::mustExtend(*Imm.Val) && !Extendable)
270         return false;
271       int64_t Res;
272       if (myMCExpr->evaluateAsAbsolute(Res)) {
273         int bits = immBits + zeroBits;
274         // Field bit range is zerobits + bits
275         // zeroBits must be 0
276         if (Res & ((1 << zeroBits) - 1))
277           return false;
278         if (isSigned) {
279           if (Res < (1LL << (bits - 1)) && Res >= -(1LL << (bits - 1)))
280             return true;
281         } else {
282           if (bits == 64)
283             return true;
284           if (Res >= 0)
285             return ((uint64_t)Res < (uint64_t)(1ULL << bits));
286           else {
287             const int64_t high_bit_set = 1ULL << 63;
288             const uint64_t mask = (high_bit_set >> (63 - bits));
289             return (((uint64_t)Res & mask) == mask);
290           }
291         }
292       } else if (myMCExpr->getKind() == MCExpr::SymbolRef && isRelocatable)
293         return true;
294       else if (myMCExpr->getKind() == MCExpr::Binary ||
295                myMCExpr->getKind() == MCExpr::Unary)
296         return true;
297     }
298     return false;
299   }
300 
301   bool isa30_2Imm() const { return CheckImmRange(30, 2, true, true, true); }
302   bool isb30_2Imm() const { return CheckImmRange(30, 2, true, true, true); }
303   bool isb15_2Imm() const { return CheckImmRange(15, 2, true, true, false); }
304   bool isb13_2Imm() const { return CheckImmRange(13, 2, true, true, false); }
305 
306   bool ism32_0Imm() const { return true; }
307 
308   bool isf32Imm() const { return false; }
309   bool isf64Imm() const { return false; }
310   bool iss32_0Imm() const { return true; }
311   bool iss31_1Imm() const { return true; }
312   bool iss30_2Imm() const { return true; }
313   bool iss29_3Imm() const { return true; }
314   bool iss27_2Imm() const { return CheckImmRange(27, 2, true, true, false); }
315   bool iss10_0Imm() const { return CheckImmRange(10, 0, true, false, false); }
316   bool iss10_6Imm() const { return CheckImmRange(10, 6, true, false, false); }
317   bool iss9_0Imm() const { return CheckImmRange(9, 0, true, false, false); }
318   bool iss8_0Imm() const { return CheckImmRange(8, 0, true, false, false); }
319   bool iss8_0Imm64() const { return CheckImmRange(8, 0, true, true, false); }
320   bool iss7_0Imm() const { return CheckImmRange(7, 0, true, false, false); }
321   bool iss6_0Imm() const { return CheckImmRange(6, 0, true, false, false); }
322   bool iss6_3Imm() const { return CheckImmRange(6, 3, true, false, false); }
323   bool iss4_0Imm() const { return CheckImmRange(4, 0, true, false, false); }
324   bool iss4_1Imm() const { return CheckImmRange(4, 1, true, false, false); }
325   bool iss4_2Imm() const { return CheckImmRange(4, 2, true, false, false); }
326   bool iss4_3Imm() const { return CheckImmRange(4, 3, true, false, false); }
327   bool iss3_0Imm() const { return CheckImmRange(3, 0, true, false, false); }
328 
329   bool isu64_0Imm() const { return CheckImmRange(64, 0, false, true, true); }
330   bool isu32_0Imm() const { return true; }
331   bool isu31_1Imm() const { return true; }
332   bool isu30_2Imm() const { return true; }
333   bool isu29_3Imm() const { return true; }
334   bool isu26_6Imm() const { return CheckImmRange(26, 6, false, true, false); }
335   bool isu16_0Imm() const { return CheckImmRange(16, 0, false, true, false); }
336   bool isu16_1Imm() const { return CheckImmRange(16, 1, false, true, false); }
337   bool isu16_2Imm() const { return CheckImmRange(16, 2, false, true, false); }
338   bool isu16_3Imm() const { return CheckImmRange(16, 3, false, true, false); }
339   bool isu11_3Imm() const { return CheckImmRange(11, 3, false, false, false); }
340   bool isu10_0Imm() const { return CheckImmRange(10, 0, false, false, false); }
341   bool isu9_0Imm() const { return CheckImmRange(9, 0, false, false, false); }
342   bool isu8_0Imm() const { return CheckImmRange(8, 0, false, false, false); }
343   bool isu7_0Imm() const { return CheckImmRange(7, 0, false, false, false); }
344   bool isu6_0Imm() const { return CheckImmRange(6, 0, false, false, false); }
345   bool isu6_1Imm() const { return CheckImmRange(6, 1, false, false, false); }
346   bool isu6_2Imm() const { return CheckImmRange(6, 2, false, false, false); }
347   bool isu6_3Imm() const { return CheckImmRange(6, 3, false, false, false); }
348   bool isu5_0Imm() const { return CheckImmRange(5, 0, false, false, false); }
349   bool isu5_2Imm() const { return CheckImmRange(5, 2, false, false, false); }
350   bool isu5_3Imm() const { return CheckImmRange(5, 3, false, false, false); }
351   bool isu4_0Imm() const { return CheckImmRange(4, 0, false, false, false); }
352   bool isu4_2Imm() const { return CheckImmRange(4, 2, false, false, false); }
353   bool isu3_0Imm() const { return CheckImmRange(3, 0, false, false, false); }
354   bool isu3_1Imm() const { return CheckImmRange(3, 1, false, false, false); }
355   bool isu2_0Imm() const { return CheckImmRange(2, 0, false, false, false); }
356   bool isu1_0Imm() const { return CheckImmRange(1, 0, false, false, false); }
357 
358   bool isn1Const() const {
359     if (!isImm())
360       return false;
361     int64_t Value;
362     if (!getImm()->evaluateAsAbsolute(Value))
363       return false;
364     return Value == -1;
365   }
366   bool iss11_0Imm() const {
367     return CheckImmRange(11 + 26, 0, true, true, true);
368   }
369   bool iss11_1Imm() const {
370     return CheckImmRange(11 + 26, 1, true, true, true);
371   }
372   bool iss11_2Imm() const {
373     return CheckImmRange(11 + 26, 2, true, true, true);
374   }
375   bool iss11_3Imm() const {
376     return CheckImmRange(11 + 26, 3, true, true, true);
377   }
378   bool isu32_0MustExt() const { return isImm(); }
379 
380   void addRegOperands(MCInst &Inst, unsigned N) const {
381     assert(N == 1 && "Invalid number of operands!");
382     Inst.addOperand(MCOperand::createReg(getReg()));
383   }
384 
385   void addImmOperands(MCInst &Inst, unsigned N) const {
386     assert(N == 1 && "Invalid number of operands!");
387     Inst.addOperand(MCOperand::createExpr(getImm()));
388   }
389 
390   void addSignedImmOperands(MCInst &Inst, unsigned N) const {
391     assert(N == 1 && "Invalid number of operands!");
392     HexagonMCExpr *Expr =
393         const_cast<HexagonMCExpr *>(cast<HexagonMCExpr>(getImm()));
394     int64_t Value;
395     if (!Expr->evaluateAsAbsolute(Value)) {
396       Inst.addOperand(MCOperand::createExpr(Expr));
397       return;
398     }
399     int64_t Extended = SignExtend64(Value, 32);
400     HexagonMCExpr *NewExpr = HexagonMCExpr::create(
401         MCConstantExpr::create(Extended, Context), Context);
402     if ((Extended < 0) != (Value < 0))
403       NewExpr->setSignMismatch();
404     NewExpr->setMustExtend(Expr->mustExtend());
405     NewExpr->setMustNotExtend(Expr->mustNotExtend());
406     Inst.addOperand(MCOperand::createExpr(NewExpr));
407   }
408 
409   void addn1ConstOperands(MCInst &Inst, unsigned N) const {
410     addImmOperands(Inst, N);
411   }
412 
413   StringRef getToken() const {
414     assert(Kind == Token && "Invalid access!");
415     return StringRef(Tok.Data, Tok.Length);
416   }
417 
418   void print(raw_ostream &OS) const override;
419 
420   static std::unique_ptr<HexagonOperand> CreateToken(MCContext &Context,
421                                                      StringRef Str, SMLoc S) {
422     HexagonOperand *Op = new HexagonOperand(Token, Context);
423     Op->Tok.Data = Str.data();
424     Op->Tok.Length = Str.size();
425     Op->StartLoc = S;
426     Op->EndLoc = S;
427     return std::unique_ptr<HexagonOperand>(Op);
428   }
429 
430   static std::unique_ptr<HexagonOperand>
431   CreateReg(MCContext &Context, unsigned RegNum, SMLoc S, SMLoc E) {
432     HexagonOperand *Op = new HexagonOperand(Register, Context);
433     Op->Reg.RegNum = RegNum;
434     Op->StartLoc = S;
435     Op->EndLoc = E;
436     return std::unique_ptr<HexagonOperand>(Op);
437   }
438 
439   static std::unique_ptr<HexagonOperand>
440   CreateImm(MCContext &Context, const MCExpr *Val, SMLoc S, SMLoc E) {
441     HexagonOperand *Op = new HexagonOperand(Immediate, Context);
442     Op->Imm.Val = Val;
443     Op->StartLoc = S;
444     Op->EndLoc = E;
445     return std::unique_ptr<HexagonOperand>(Op);
446   }
447 };
448 
449 } // end anonymous namespace
450 
451 void HexagonOperand::print(raw_ostream &OS) const {
452   switch (Kind) {
453   case Immediate:
454     getImm()->print(OS, nullptr);
455     break;
456   case Register:
457     OS << "<register R";
458     OS << getReg() << ">";
459     break;
460   case Token:
461     OS << "'" << getToken() << "'";
462     break;
463   }
464 }
465 
466 bool HexagonAsmParser::finishBundle(SMLoc IDLoc, MCStreamer &Out) {
467   LLVM_DEBUG(dbgs() << "Bundle:");
468   LLVM_DEBUG(MCB.dump_pretty(dbgs()));
469   LLVM_DEBUG(dbgs() << "--\n");
470 
471   MCB.setLoc(IDLoc);
472 
473   // Check the bundle for errors.
474   const MCRegisterInfo *RI = getContext().getRegisterInfo();
475   MCSubtargetInfo const &STI = getSTI();
476 
477   MCInst OrigBundle = MCB;
478   HexagonMCChecker Check(getContext(), MII, STI, MCB, *RI, true);
479 
480   bool CheckOk = HexagonMCInstrInfo::canonicalizePacket(
481       MII, STI, getContext(), MCB, &Check, true);
482 
483   if (CheckOk) {
484     if (HexagonMCInstrInfo::bundleSize(MCB) == 0) {
485       assert(!HexagonMCInstrInfo::isInnerLoop(MCB));
486       assert(!HexagonMCInstrInfo::isOuterLoop(MCB));
487       // Empty packets are valid yet aren't emitted
488       return false;
489     }
490 
491     assert(HexagonMCInstrInfo::isBundle(MCB));
492 
493     Out.EmitInstruction(MCB, STI);
494   } else
495     return true; // Error
496 
497   return false; // No error
498 }
499 
500 bool HexagonAsmParser::matchBundleOptions() {
501   MCAsmParser &Parser = getParser();
502   while (true) {
503     if (!Parser.getTok().is(AsmToken::Colon))
504       return false;
505     Lex();
506     char const *MemNoShuffMsg =
507         "invalid instruction packet: mem_noshuf specifier not "
508         "supported with this architecture";
509     StringRef Option = Parser.getTok().getString();
510     auto IDLoc = Parser.getTok().getLoc();
511     if (Option.compare_lower("endloop01") == 0) {
512       HexagonMCInstrInfo::setInnerLoop(MCB);
513       HexagonMCInstrInfo::setOuterLoop(MCB);
514     } else if (Option.compare_lower("endloop0") == 0) {
515       HexagonMCInstrInfo::setInnerLoop(MCB);
516     } else if (Option.compare_lower("endloop1") == 0) {
517       HexagonMCInstrInfo::setOuterLoop(MCB);
518     } else if (Option.compare_lower("mem_noshuf") == 0) {
519       if (getSTI().getFeatureBits()[Hexagon::FeatureMemNoShuf])
520         HexagonMCInstrInfo::setMemReorderDisabled(MCB);
521       else
522         return getParser().Error(IDLoc, MemNoShuffMsg);
523     } else if (Option.compare_lower("mem_no_order") == 0) {
524       // Nothing.
525     } else
526       return getParser().Error(IDLoc, llvm::Twine("'") + Option +
527                                           "' is not a valid bundle option");
528     Lex();
529   }
530 }
531 
532 // For instruction aliases, immediates are generated rather than
533 // MCConstantExpr.  Convert them for uniform MCExpr.
534 // Also check for signed/unsigned mismatches and warn
535 void HexagonAsmParser::canonicalizeImmediates(MCInst &MCI) {
536   MCInst NewInst;
537   NewInst.setOpcode(MCI.getOpcode());
538   for (MCOperand &I : MCI)
539     if (I.isImm()) {
540       int64_t Value(I.getImm());
541       NewInst.addOperand(MCOperand::createExpr(HexagonMCExpr::create(
542           MCConstantExpr::create(Value, getContext()), getContext())));
543     } else {
544       if (I.isExpr() && cast<HexagonMCExpr>(I.getExpr())->signMismatch() &&
545           WarnSignedMismatch)
546         Warning(MCI.getLoc(), "Signed/Unsigned mismatch");
547       NewInst.addOperand(I);
548     }
549   MCI = NewInst;
550 }
551 
552 bool HexagonAsmParser::matchOneInstruction(MCInst &MCI, SMLoc IDLoc,
553                                            OperandVector &InstOperands,
554                                            uint64_t &ErrorInfo,
555                                            bool MatchingInlineAsm) {
556   // Perform matching with tablegen asmmatcher generated function
557   int result =
558       MatchInstructionImpl(InstOperands, MCI, ErrorInfo, MatchingInlineAsm);
559   if (result == Match_Success) {
560     MCI.setLoc(IDLoc);
561     canonicalizeImmediates(MCI);
562     result = processInstruction(MCI, InstOperands, IDLoc);
563 
564     LLVM_DEBUG(dbgs() << "Insn:");
565     LLVM_DEBUG(MCI.dump_pretty(dbgs()));
566     LLVM_DEBUG(dbgs() << "\n\n");
567 
568     MCI.setLoc(IDLoc);
569   }
570 
571   // Create instruction operand for bundle instruction
572   //   Break this into a separate function Code here is less readable
573   //   Think about how to get an instruction error to report correctly.
574   //   SMLoc will return the "{"
575   switch (result) {
576   default:
577     break;
578   case Match_Success:
579     return false;
580   case Match_MissingFeature:
581     return Error(IDLoc, "invalid instruction");
582   case Match_MnemonicFail:
583     return Error(IDLoc, "unrecognized instruction");
584   case Match_InvalidOperand:
585     LLVM_FALLTHROUGH;
586   case Match_InvalidTiedOperand:
587     SMLoc ErrorLoc = IDLoc;
588     if (ErrorInfo != ~0U) {
589       if (ErrorInfo >= InstOperands.size())
590         return Error(IDLoc, "too few operands for instruction");
591 
592       ErrorLoc = (static_cast<HexagonOperand *>(InstOperands[ErrorInfo].get()))
593                      ->getStartLoc();
594       if (ErrorLoc == SMLoc())
595         ErrorLoc = IDLoc;
596     }
597     return Error(ErrorLoc, "invalid operand for instruction");
598   }
599   llvm_unreachable("Implement any new match types added!");
600 }
601 
602 void HexagonAsmParser::eatToEndOfPacket() {
603   assert(InBrackets);
604   MCAsmLexer &Lexer = getLexer();
605   while (!Lexer.is(AsmToken::RCurly))
606     Lexer.Lex();
607   Lexer.Lex();
608   InBrackets = false;
609 }
610 
611 bool HexagonAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
612                                                OperandVector &Operands,
613                                                MCStreamer &Out,
614                                                uint64_t &ErrorInfo,
615                                                bool MatchingInlineAsm) {
616   if (!InBrackets) {
617     MCB.clear();
618     MCB.addOperand(MCOperand::createImm(0));
619   }
620   HexagonOperand &FirstOperand = static_cast<HexagonOperand &>(*Operands[0]);
621   if (FirstOperand.isToken() && FirstOperand.getToken() == "{") {
622     assert(Operands.size() == 1 && "Brackets should be by themselves");
623     if (InBrackets) {
624       getParser().Error(IDLoc, "Already in a packet");
625       InBrackets = false;
626       return true;
627     }
628     InBrackets = true;
629     return false;
630   }
631   if (FirstOperand.isToken() && FirstOperand.getToken() == "}") {
632     assert(Operands.size() == 1 && "Brackets should be by themselves");
633     if (!InBrackets) {
634       getParser().Error(IDLoc, "Not in a packet");
635       return true;
636     }
637     InBrackets = false;
638     if (matchBundleOptions())
639       return true;
640     return finishBundle(IDLoc, Out);
641   }
642   MCInst *SubInst = new (getParser().getContext()) MCInst;
643   if (matchOneInstruction(*SubInst, IDLoc, Operands, ErrorInfo,
644                           MatchingInlineAsm)) {
645     if (InBrackets)
646       eatToEndOfPacket();
647     return true;
648   }
649   HexagonMCInstrInfo::extendIfNeeded(
650       getParser().getContext(), MII, MCB, *SubInst);
651   MCB.addOperand(MCOperand::createInst(SubInst));
652   if (!InBrackets)
653     return finishBundle(IDLoc, Out);
654   return false;
655 }
656 
657 /// ParseDirective parses the Hexagon specific directives
658 bool HexagonAsmParser::ParseDirective(AsmToken DirectiveID) {
659   StringRef IDVal = DirectiveID.getIdentifier();
660   if (IDVal.lower() == ".falign")
661     return ParseDirectiveFalign(256, DirectiveID.getLoc());
662   if ((IDVal.lower() == ".lcomm") || (IDVal.lower() == ".lcommon"))
663     return ParseDirectiveComm(true, DirectiveID.getLoc());
664   if ((IDVal.lower() == ".comm") || (IDVal.lower() == ".common"))
665     return ParseDirectiveComm(false, DirectiveID.getLoc());
666   if (IDVal.lower() == ".subsection")
667     return ParseDirectiveSubsection(DirectiveID.getLoc());
668 
669   return true;
670 }
671 bool HexagonAsmParser::ParseDirectiveSubsection(SMLoc L) {
672   const MCExpr *Subsection = nullptr;
673   int64_t Res;
674 
675   assert((getLexer().isNot(AsmToken::EndOfStatement)) &&
676          "Invalid subsection directive");
677   getParser().parseExpression(Subsection);
678 
679   if (!Subsection->evaluateAsAbsolute(Res))
680     return Error(L, "Cannot evaluate subsection number");
681 
682   if (getLexer().isNot(AsmToken::EndOfStatement))
683     return TokError("unexpected token in directive");
684 
685   // 0-8192 is the hard-coded range in MCObjectStreamper.cpp, this keeps the
686   // negative subsections together and in the same order but at the opposite
687   // end of the section.  Only legacy hexagon-gcc created assembly code
688   // used negative subsections.
689   if ((Res < 0) && (Res > -8193))
690     Subsection = HexagonMCExpr::create(
691         MCConstantExpr::create(8192 + Res, getContext()), getContext());
692 
693   getStreamer().SubSection(Subsection);
694   return false;
695 }
696 
697 ///  ::= .falign [expression]
698 bool HexagonAsmParser::ParseDirectiveFalign(unsigned Size, SMLoc L) {
699 
700   int64_t MaxBytesToFill = 15;
701 
702   // if there is an argument
703   if (getLexer().isNot(AsmToken::EndOfStatement)) {
704     const MCExpr *Value;
705     SMLoc ExprLoc = L;
706 
707     // Make sure we have a number (false is returned if expression is a number)
708     if (!getParser().parseExpression(Value)) {
709       // Make sure this is a number that is in range
710       auto *MCE = cast<MCConstantExpr>(Value);
711       uint64_t IntValue = MCE->getValue();
712       if (!isUIntN(Size, IntValue) && !isIntN(Size, IntValue))
713         return Error(ExprLoc, "literal value out of range (256) for falign");
714       MaxBytesToFill = IntValue;
715       Lex();
716     } else {
717       return Error(ExprLoc, "not a valid expression for falign directive");
718     }
719   }
720 
721   getTargetStreamer().emitFAlign(16, MaxBytesToFill);
722   Lex();
723 
724   return false;
725 }
726 
727 // This is largely a copy of AsmParser's ParseDirectiveComm extended to
728 // accept a 3rd argument, AccessAlignment which indicates the smallest
729 // memory access made to the symbol, expressed in bytes.  If no
730 // AccessAlignment is specified it defaults to the Alignment Value.
731 // Hexagon's .lcomm:
732 //   .lcomm Symbol, Length, Alignment, AccessAlignment
733 bool HexagonAsmParser::ParseDirectiveComm(bool IsLocal, SMLoc Loc) {
734   // FIXME: need better way to detect if AsmStreamer (upstream removed
735   // getKind())
736   if (getStreamer().hasRawTextSupport())
737     return true; // Only object file output requires special treatment.
738 
739   StringRef Name;
740   if (getParser().parseIdentifier(Name))
741     return TokError("expected identifier in directive");
742   // Handle the identifier as the key symbol.
743   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
744 
745   if (getLexer().isNot(AsmToken::Comma))
746     return TokError("unexpected token in directive");
747   Lex();
748 
749   int64_t Size;
750   SMLoc SizeLoc = getLexer().getLoc();
751   if (getParser().parseAbsoluteExpression(Size))
752     return true;
753 
754   int64_t ByteAlignment = 1;
755   SMLoc ByteAlignmentLoc;
756   if (getLexer().is(AsmToken::Comma)) {
757     Lex();
758     ByteAlignmentLoc = getLexer().getLoc();
759     if (getParser().parseAbsoluteExpression(ByteAlignment))
760       return true;
761     if (!isPowerOf2_64(ByteAlignment))
762       return Error(ByteAlignmentLoc, "alignment must be a power of 2");
763   }
764 
765   int64_t AccessAlignment = 0;
766   if (getLexer().is(AsmToken::Comma)) {
767     // The optional access argument specifies the size of the smallest memory
768     //   access to be made to the symbol, expressed in bytes.
769     SMLoc AccessAlignmentLoc;
770     Lex();
771     AccessAlignmentLoc = getLexer().getLoc();
772     if (getParser().parseAbsoluteExpression(AccessAlignment))
773       return true;
774 
775     if (!isPowerOf2_64(AccessAlignment))
776       return Error(AccessAlignmentLoc, "access alignment must be a power of 2");
777   }
778 
779   if (getLexer().isNot(AsmToken::EndOfStatement))
780     return TokError("unexpected token in '.comm' or '.lcomm' directive");
781 
782   Lex();
783 
784   // NOTE: a size of zero for a .comm should create a undefined symbol
785   // but a size of .lcomm creates a bss symbol of size zero.
786   if (Size < 0)
787     return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
788                           "be less than zero");
789 
790   // NOTE: The alignment in the directive is a power of 2 value, the assembler
791   // may internally end up wanting an alignment in bytes.
792   // FIXME: Diagnose overflow.
793   if (ByteAlignment < 0)
794     return Error(ByteAlignmentLoc, "invalid '.comm' or '.lcomm' directive "
795                                    "alignment, can't be less than zero");
796 
797   if (!Sym->isUndefined())
798     return Error(Loc, "invalid symbol redefinition");
799 
800   HexagonMCELFStreamer &HexagonELFStreamer =
801       static_cast<HexagonMCELFStreamer &>(getStreamer());
802   if (IsLocal) {
803     HexagonELFStreamer.HexagonMCEmitLocalCommonSymbol(Sym, Size, ByteAlignment,
804                                                       AccessAlignment);
805     return false;
806   }
807 
808   HexagonELFStreamer.HexagonMCEmitCommonSymbol(Sym, Size, ByteAlignment,
809                                                AccessAlignment);
810   return false;
811 }
812 
813 // validate register against architecture
814 bool HexagonAsmParser::RegisterMatchesArch(unsigned MatchNum) const {
815   if (HexagonMCRegisterClasses[Hexagon::V62RegsRegClassID].contains(MatchNum))
816     if (!getSTI().getFeatureBits()[Hexagon::ArchV62])
817       return false;
818   return true;
819 }
820 
821 // extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeHexagonAsmLexer();
822 
823 /// Force static initialization.
824 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeHexagonAsmParser() {
825   RegisterMCAsmParser<HexagonAsmParser> X(getTheHexagonTarget());
826 }
827 
828 #define GET_MATCHER_IMPLEMENTATION
829 #define GET_REGISTER_MATCHER
830 #include "HexagonGenAsmMatcher.inc"
831 
832 static bool previousEqual(OperandVector &Operands, size_t Index,
833                           StringRef String) {
834   if (Index >= Operands.size())
835     return false;
836   MCParsedAsmOperand &Operand = *Operands[Operands.size() - Index - 1];
837   if (!Operand.isToken())
838     return false;
839   return static_cast<HexagonOperand &>(Operand).getToken().equals_lower(String);
840 }
841 
842 static bool previousIsLoop(OperandVector &Operands, size_t Index) {
843   return previousEqual(Operands, Index, "loop0") ||
844          previousEqual(Operands, Index, "loop1") ||
845          previousEqual(Operands, Index, "sp1loop0") ||
846          previousEqual(Operands, Index, "sp2loop0") ||
847          previousEqual(Operands, Index, "sp3loop0");
848 }
849 
850 bool HexagonAsmParser::splitIdentifier(OperandVector &Operands) {
851   AsmToken const &Token = getParser().getTok();
852   StringRef String = Token.getString();
853   SMLoc Loc = Token.getLoc();
854   Lex();
855   do {
856     std::pair<StringRef, StringRef> HeadTail = String.split('.');
857     if (!HeadTail.first.empty())
858       Operands.push_back(
859           HexagonOperand::CreateToken(getContext(), HeadTail.first, Loc));
860     if (!HeadTail.second.empty())
861       Operands.push_back(HexagonOperand::CreateToken(
862           getContext(), String.substr(HeadTail.first.size(), 1), Loc));
863     String = HeadTail.second;
864   } while (!String.empty());
865   return false;
866 }
867 
868 bool HexagonAsmParser::parseOperand(OperandVector &Operands) {
869   unsigned Register;
870   SMLoc Begin;
871   SMLoc End;
872   MCAsmLexer &Lexer = getLexer();
873   if (!ParseRegister(Register, Begin, End)) {
874     if (!ErrorMissingParenthesis)
875       switch (Register) {
876       default:
877         break;
878       case Hexagon::P0:
879       case Hexagon::P1:
880       case Hexagon::P2:
881       case Hexagon::P3:
882         if (previousEqual(Operands, 0, "if")) {
883           if (WarnMissingParenthesis)
884             Warning(Begin, "Missing parenthesis around predicate register");
885           static char const *LParen = "(";
886           static char const *RParen = ")";
887           Operands.push_back(
888               HexagonOperand::CreateToken(getContext(), LParen, Begin));
889           Operands.push_back(
890               HexagonOperand::CreateReg(getContext(), Register, Begin, End));
891           const AsmToken &MaybeDotNew = Lexer.getTok();
892           if (MaybeDotNew.is(AsmToken::TokenKind::Identifier) &&
893               MaybeDotNew.getString().equals_lower(".new"))
894             splitIdentifier(Operands);
895           Operands.push_back(
896               HexagonOperand::CreateToken(getContext(), RParen, Begin));
897           return false;
898         }
899         if (previousEqual(Operands, 0, "!") &&
900             previousEqual(Operands, 1, "if")) {
901           if (WarnMissingParenthesis)
902             Warning(Begin, "Missing parenthesis around predicate register");
903           static char const *LParen = "(";
904           static char const *RParen = ")";
905           Operands.insert(Operands.end() - 1, HexagonOperand::CreateToken(
906                                                   getContext(), LParen, Begin));
907           Operands.push_back(
908               HexagonOperand::CreateReg(getContext(), Register, Begin, End));
909           const AsmToken &MaybeDotNew = Lexer.getTok();
910           if (MaybeDotNew.is(AsmToken::TokenKind::Identifier) &&
911               MaybeDotNew.getString().equals_lower(".new"))
912             splitIdentifier(Operands);
913           Operands.push_back(
914               HexagonOperand::CreateToken(getContext(), RParen, Begin));
915           return false;
916         }
917         break;
918       }
919     Operands.push_back(
920         HexagonOperand::CreateReg(getContext(), Register, Begin, End));
921     return false;
922   }
923   return splitIdentifier(Operands);
924 }
925 
926 bool HexagonAsmParser::isLabel(AsmToken &Token) {
927   MCAsmLexer &Lexer = getLexer();
928   AsmToken const &Second = Lexer.getTok();
929   AsmToken Third = Lexer.peekTok();
930   StringRef String = Token.getString();
931   if (Token.is(AsmToken::TokenKind::LCurly) ||
932       Token.is(AsmToken::TokenKind::RCurly))
933     return false;
934   // special case for parsing vwhist256:sat
935   if (String.lower() == "vwhist256" && Second.is(AsmToken::Colon) &&
936       Third.getString().lower() == "sat")
937     return false;
938   if (!Token.is(AsmToken::TokenKind::Identifier))
939     return true;
940   if (!matchRegister(String.lower()))
941     return true;
942   assert(Second.is(AsmToken::Colon));
943   StringRef Raw(String.data(), Third.getString().data() - String.data() +
944                                    Third.getString().size());
945   std::string Collapsed = std::string(Raw);
946   Collapsed.erase(llvm::remove_if(Collapsed, isspace), Collapsed.end());
947   StringRef Whole = Collapsed;
948   std::pair<StringRef, StringRef> DotSplit = Whole.split('.');
949   if (!matchRegister(DotSplit.first.lower()))
950     return true;
951   return false;
952 }
953 
954 bool HexagonAsmParser::handleNoncontigiousRegister(bool Contigious,
955                                                    SMLoc &Loc) {
956   if (!Contigious && ErrorNoncontigiousRegister) {
957     Error(Loc, "Register name is not contigious");
958     return true;
959   }
960   if (!Contigious && WarnNoncontigiousRegister)
961     Warning(Loc, "Register name is not contigious");
962   return false;
963 }
964 
965 bool HexagonAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
966                                      SMLoc &EndLoc) {
967   MCAsmLexer &Lexer = getLexer();
968   StartLoc = getLexer().getLoc();
969   SmallVector<AsmToken, 5> Lookahead;
970   StringRef RawString(Lexer.getTok().getString().data(), 0);
971   bool Again = Lexer.is(AsmToken::Identifier);
972   bool NeededWorkaround = false;
973   while (Again) {
974     AsmToken const &Token = Lexer.getTok();
975     RawString = StringRef(RawString.data(), Token.getString().data() -
976                                                 RawString.data() +
977                                                 Token.getString().size());
978     Lookahead.push_back(Token);
979     Lexer.Lex();
980     bool Contigious = Lexer.getTok().getString().data() ==
981                       Lookahead.back().getString().data() +
982                           Lookahead.back().getString().size();
983     bool Type = Lexer.is(AsmToken::Identifier) || Lexer.is(AsmToken::Dot) ||
984                 Lexer.is(AsmToken::Integer) || Lexer.is(AsmToken::Real) ||
985                 Lexer.is(AsmToken::Colon);
986     bool Workaround =
987         Lexer.is(AsmToken::Colon) || Lookahead.back().is(AsmToken::Colon);
988     Again = (Contigious && Type) || (Workaround && Type);
989     NeededWorkaround = NeededWorkaround || (Again && !(Contigious && Type));
990   }
991   std::string Collapsed = std::string(RawString);
992   Collapsed.erase(llvm::remove_if(Collapsed, isspace), Collapsed.end());
993   StringRef FullString = Collapsed;
994   std::pair<StringRef, StringRef> DotSplit = FullString.split('.');
995   unsigned DotReg = matchRegister(DotSplit.first.lower());
996   if (DotReg != Hexagon::NoRegister && RegisterMatchesArch(DotReg)) {
997     if (DotSplit.second.empty()) {
998       RegNo = DotReg;
999       EndLoc = Lexer.getLoc();
1000       if (handleNoncontigiousRegister(!NeededWorkaround, StartLoc))
1001         return true;
1002       return false;
1003     } else {
1004       RegNo = DotReg;
1005       size_t First = RawString.find('.');
1006       StringRef DotString (RawString.data() + First, RawString.size() - First);
1007       Lexer.UnLex(AsmToken(AsmToken::Identifier, DotString));
1008       EndLoc = Lexer.getLoc();
1009       if (handleNoncontigiousRegister(!NeededWorkaround, StartLoc))
1010         return true;
1011       return false;
1012     }
1013   }
1014   std::pair<StringRef, StringRef> ColonSplit = StringRef(FullString).split(':');
1015   unsigned ColonReg = matchRegister(ColonSplit.first.lower());
1016   if (ColonReg != Hexagon::NoRegister && RegisterMatchesArch(DotReg)) {
1017     do {
1018       Lexer.UnLex(Lookahead.back());
1019       Lookahead.pop_back();
1020     } while (!Lookahead.empty () && !Lexer.is(AsmToken::Colon));
1021     RegNo = ColonReg;
1022     EndLoc = Lexer.getLoc();
1023     if (handleNoncontigiousRegister(!NeededWorkaround, StartLoc))
1024       return true;
1025     return false;
1026   }
1027   while (!Lookahead.empty()) {
1028     Lexer.UnLex(Lookahead.back());
1029     Lookahead.pop_back();
1030   }
1031   return true;
1032 }
1033 
1034 bool HexagonAsmParser::implicitExpressionLocation(OperandVector &Operands) {
1035   if (previousEqual(Operands, 0, "call"))
1036     return true;
1037   if (previousEqual(Operands, 0, "jump"))
1038     if (!getLexer().getTok().is(AsmToken::Colon))
1039       return true;
1040   if (previousEqual(Operands, 0, "(") && previousIsLoop(Operands, 1))
1041     return true;
1042   if (previousEqual(Operands, 1, ":") && previousEqual(Operands, 2, "jump") &&
1043       (previousEqual(Operands, 0, "nt") || previousEqual(Operands, 0, "t")))
1044     return true;
1045   return false;
1046 }
1047 
1048 bool HexagonAsmParser::parseExpression(MCExpr const *&Expr) {
1049   SmallVector<AsmToken, 4> Tokens;
1050   MCAsmLexer &Lexer = getLexer();
1051   bool Done = false;
1052   static char const *Comma = ",";
1053   do {
1054     Tokens.emplace_back(Lexer.getTok());
1055     Lex();
1056     switch (Tokens.back().getKind()) {
1057     case AsmToken::TokenKind::Hash:
1058       if (Tokens.size() > 1)
1059         if ((Tokens.end() - 2)->getKind() == AsmToken::TokenKind::Plus) {
1060           Tokens.insert(Tokens.end() - 2,
1061                         AsmToken(AsmToken::TokenKind::Comma, Comma));
1062           Done = true;
1063         }
1064       break;
1065     case AsmToken::TokenKind::RCurly:
1066     case AsmToken::TokenKind::EndOfStatement:
1067     case AsmToken::TokenKind::Eof:
1068       Done = true;
1069       break;
1070     default:
1071       break;
1072     }
1073   } while (!Done);
1074   while (!Tokens.empty()) {
1075     Lexer.UnLex(Tokens.back());
1076     Tokens.pop_back();
1077   }
1078   SMLoc Loc = Lexer.getLoc();
1079   return getParser().parseExpression(Expr, Loc);
1080 }
1081 
1082 bool HexagonAsmParser::parseExpressionOrOperand(OperandVector &Operands) {
1083   if (implicitExpressionLocation(Operands)) {
1084     MCAsmParser &Parser = getParser();
1085     SMLoc Loc = Parser.getLexer().getLoc();
1086     MCExpr const *Expr = nullptr;
1087     bool Error = parseExpression(Expr);
1088     Expr = HexagonMCExpr::create(Expr, getContext());
1089     if (!Error)
1090       Operands.push_back(
1091           HexagonOperand::CreateImm(getContext(), Expr, Loc, Loc));
1092     return Error;
1093   }
1094   return parseOperand(Operands);
1095 }
1096 
1097 /// Parse an instruction.
1098 bool HexagonAsmParser::parseInstruction(OperandVector &Operands) {
1099   MCAsmParser &Parser = getParser();
1100   MCAsmLexer &Lexer = getLexer();
1101   while (true) {
1102     AsmToken const &Token = Parser.getTok();
1103     switch (Token.getKind()) {
1104     case AsmToken::Eof:
1105     case AsmToken::EndOfStatement: {
1106       Lex();
1107       return false;
1108     }
1109     case AsmToken::LCurly: {
1110       if (!Operands.empty())
1111         return true;
1112       Operands.push_back(HexagonOperand::CreateToken(
1113           getContext(), Token.getString(), Token.getLoc()));
1114       Lex();
1115       return false;
1116     }
1117     case AsmToken::RCurly: {
1118       if (Operands.empty()) {
1119         Operands.push_back(HexagonOperand::CreateToken(
1120             getContext(), Token.getString(), Token.getLoc()));
1121         Lex();
1122       }
1123       return false;
1124     }
1125     case AsmToken::Comma: {
1126       Lex();
1127       continue;
1128     }
1129     case AsmToken::EqualEqual:
1130     case AsmToken::ExclaimEqual:
1131     case AsmToken::GreaterEqual:
1132     case AsmToken::GreaterGreater:
1133     case AsmToken::LessEqual:
1134     case AsmToken::LessLess: {
1135       Operands.push_back(HexagonOperand::CreateToken(
1136           getContext(), Token.getString().substr(0, 1), Token.getLoc()));
1137       Operands.push_back(HexagonOperand::CreateToken(
1138           getContext(), Token.getString().substr(1, 1), Token.getLoc()));
1139       Lex();
1140       continue;
1141     }
1142     case AsmToken::Hash: {
1143       bool MustNotExtend = false;
1144       bool ImplicitExpression = implicitExpressionLocation(Operands);
1145       SMLoc ExprLoc = Lexer.getLoc();
1146       if (!ImplicitExpression)
1147         Operands.push_back(HexagonOperand::CreateToken(
1148             getContext(), Token.getString(), Token.getLoc()));
1149       Lex();
1150       bool MustExtend = false;
1151       bool HiOnly = false;
1152       bool LoOnly = false;
1153       if (Lexer.is(AsmToken::Hash)) {
1154         Lex();
1155         MustExtend = true;
1156       } else if (ImplicitExpression)
1157         MustNotExtend = true;
1158       AsmToken const &Token = Parser.getTok();
1159       if (Token.is(AsmToken::Identifier)) {
1160         StringRef String = Token.getString();
1161         if (String.lower() == "hi") {
1162           HiOnly = true;
1163         } else if (String.lower() == "lo") {
1164           LoOnly = true;
1165         }
1166         if (HiOnly || LoOnly) {
1167           AsmToken LParen = Lexer.peekTok();
1168           if (!LParen.is(AsmToken::LParen)) {
1169             HiOnly = false;
1170             LoOnly = false;
1171           } else {
1172             Lex();
1173           }
1174         }
1175       }
1176       MCExpr const *Expr = nullptr;
1177       if (parseExpression(Expr))
1178         return true;
1179       int64_t Value;
1180       MCContext &Context = Parser.getContext();
1181       assert(Expr != nullptr);
1182       if (Expr->evaluateAsAbsolute(Value)) {
1183         if (HiOnly)
1184           Expr = MCBinaryExpr::createLShr(
1185               Expr, MCConstantExpr::create(16, Context), Context);
1186         if (HiOnly || LoOnly)
1187           Expr = MCBinaryExpr::createAnd(
1188               Expr, MCConstantExpr::create(0xffff, Context), Context);
1189       } else {
1190         MCValue Value;
1191         if (Expr->evaluateAsRelocatable(Value, nullptr, nullptr)) {
1192           if (!Value.isAbsolute()) {
1193             switch (Value.getAccessVariant()) {
1194             case MCSymbolRefExpr::VariantKind::VK_TPREL:
1195             case MCSymbolRefExpr::VariantKind::VK_DTPREL:
1196               // Don't lazy extend these expression variants
1197               MustNotExtend = !MustExtend;
1198               break;
1199             default:
1200               break;
1201             }
1202           }
1203         }
1204       }
1205       Expr = HexagonMCExpr::create(Expr, Context);
1206       HexagonMCInstrInfo::setMustNotExtend(*Expr, MustNotExtend);
1207       HexagonMCInstrInfo::setMustExtend(*Expr, MustExtend);
1208       std::unique_ptr<HexagonOperand> Operand =
1209           HexagonOperand::CreateImm(getContext(), Expr, ExprLoc, ExprLoc);
1210       Operands.push_back(std::move(Operand));
1211       continue;
1212     }
1213     default:
1214       break;
1215     }
1216     if (parseExpressionOrOperand(Operands))
1217       return true;
1218   }
1219 }
1220 
1221 bool HexagonAsmParser::ParseInstruction(ParseInstructionInfo &Info,
1222                                         StringRef Name, AsmToken ID,
1223                                         OperandVector &Operands) {
1224   getLexer().UnLex(ID);
1225   return parseInstruction(Operands);
1226 }
1227 
1228 static MCInst makeCombineInst(int opCode, MCOperand &Rdd, MCOperand &MO1,
1229                               MCOperand &MO2) {
1230   MCInst TmpInst;
1231   TmpInst.setOpcode(opCode);
1232   TmpInst.addOperand(Rdd);
1233   TmpInst.addOperand(MO1);
1234   TmpInst.addOperand(MO2);
1235 
1236   return TmpInst;
1237 }
1238 
1239 // Define this matcher function after the auto-generated include so we
1240 // have the match class enum definitions.
1241 unsigned HexagonAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
1242                                                       unsigned Kind) {
1243   HexagonOperand *Op = static_cast<HexagonOperand *>(&AsmOp);
1244 
1245   switch (Kind) {
1246   case MCK_0: {
1247     int64_t Value;
1248     return Op->isImm() && Op->Imm.Val->evaluateAsAbsolute(Value) && Value == 0
1249                ? Match_Success
1250                : Match_InvalidOperand;
1251   }
1252   case MCK_1: {
1253     int64_t Value;
1254     return Op->isImm() && Op->Imm.Val->evaluateAsAbsolute(Value) && Value == 1
1255                ? Match_Success
1256                : Match_InvalidOperand;
1257   }
1258   }
1259   if (Op->Kind == HexagonOperand::Token && Kind != InvalidMatchClass) {
1260     StringRef myStringRef = StringRef(Op->Tok.Data, Op->Tok.Length);
1261     if (matchTokenString(myStringRef.lower()) == (MatchClassKind)Kind)
1262       return Match_Success;
1263     if (matchTokenString(myStringRef.upper()) == (MatchClassKind)Kind)
1264       return Match_Success;
1265   }
1266 
1267   LLVM_DEBUG(dbgs() << "Unmatched Operand:");
1268   LLVM_DEBUG(Op->dump());
1269   LLVM_DEBUG(dbgs() << "\n");
1270 
1271   return Match_InvalidOperand;
1272 }
1273 
1274 // FIXME: Calls to OutOfRange shoudl propagate failure up to parseStatement.
1275 bool HexagonAsmParser::OutOfRange(SMLoc IDLoc, long long Val, long long Max) {
1276   std::string errStr;
1277   raw_string_ostream ES(errStr);
1278   ES << "value " << Val << "(" << format_hex(Val, 0) << ") out of range: ";
1279   if (Max >= 0)
1280     ES << "0-" << Max;
1281   else
1282     ES << Max << "-" << (-Max - 1);
1283   return Parser.printError(IDLoc, ES.str());
1284 }
1285 
1286 int HexagonAsmParser::processInstruction(MCInst &Inst,
1287                                          OperandVector const &Operands,
1288                                          SMLoc IDLoc) {
1289   MCContext &Context = getParser().getContext();
1290   const MCRegisterInfo *RI = getContext().getRegisterInfo();
1291   std::string r = "r";
1292   std::string v = "v";
1293   std::string Colon = ":";
1294 
1295   bool is32bit = false; // used to distinguish between CONST32 and CONST64
1296   switch (Inst.getOpcode()) {
1297   default:
1298     if (HexagonMCInstrInfo::getDesc(MII, Inst).isPseudo()) {
1299       SMDiagnostic Diag = getSourceManager().GetMessage(
1300           IDLoc, SourceMgr::DK_Error,
1301           "Found pseudo instruction with no expansion");
1302       Diag.print("", errs());
1303       report_fatal_error("Invalid pseudo instruction");
1304     }
1305     break;
1306 
1307   case Hexagon::J2_trap1:
1308     if (!getSTI().getFeatureBits()[Hexagon::ArchV65]) {
1309       MCOperand &Rx = Inst.getOperand(0);
1310       MCOperand &Ry = Inst.getOperand(1);
1311       if (Rx.getReg() != Hexagon::R0 || Ry.getReg() != Hexagon::R0) {
1312         Error(IDLoc, "trap1 can only have register r0 as operand");
1313         return Match_InvalidOperand;
1314       }
1315     }
1316     break;
1317 
1318   case Hexagon::A2_iconst: {
1319     Inst.setOpcode(Hexagon::A2_addi);
1320     MCOperand Reg = Inst.getOperand(0);
1321     MCOperand S27 = Inst.getOperand(1);
1322     HexagonMCInstrInfo::setMustNotExtend(*S27.getExpr());
1323     HexagonMCInstrInfo::setS27_2_reloc(*S27.getExpr());
1324     Inst.clear();
1325     Inst.addOperand(Reg);
1326     Inst.addOperand(MCOperand::createReg(Hexagon::R0));
1327     Inst.addOperand(S27);
1328     break;
1329   }
1330   case Hexagon::M4_mpyrr_addr:
1331   case Hexagon::S4_addi_asl_ri:
1332   case Hexagon::S4_addi_lsr_ri:
1333   case Hexagon::S4_andi_asl_ri:
1334   case Hexagon::S4_andi_lsr_ri:
1335   case Hexagon::S4_ori_asl_ri:
1336   case Hexagon::S4_ori_lsr_ri:
1337   case Hexagon::S4_or_andix:
1338   case Hexagon::S4_subi_asl_ri:
1339   case Hexagon::S4_subi_lsr_ri: {
1340     MCOperand &Ry = Inst.getOperand(0);
1341     MCOperand &src = Inst.getOperand(2);
1342     if (RI->getEncodingValue(Ry.getReg()) != RI->getEncodingValue(src.getReg()))
1343       return Match_InvalidOperand;
1344     break;
1345   }
1346 
1347   case Hexagon::C2_cmpgei: {
1348     MCOperand &MO = Inst.getOperand(2);
1349     MO.setExpr(HexagonMCExpr::create(
1350         MCBinaryExpr::createSub(MO.getExpr(),
1351                                 MCConstantExpr::create(1, Context), Context),
1352         Context));
1353     Inst.setOpcode(Hexagon::C2_cmpgti);
1354     break;
1355   }
1356 
1357   case Hexagon::C2_cmpgeui: {
1358     MCOperand &MO = Inst.getOperand(2);
1359     int64_t Value;
1360     bool Success = MO.getExpr()->evaluateAsAbsolute(Value);
1361     (void)Success;
1362     assert(Success && "Assured by matcher");
1363     if (Value == 0) {
1364       MCInst TmpInst;
1365       MCOperand &Pd = Inst.getOperand(0);
1366       MCOperand &Rt = Inst.getOperand(1);
1367       TmpInst.setOpcode(Hexagon::C2_cmpeq);
1368       TmpInst.addOperand(Pd);
1369       TmpInst.addOperand(Rt);
1370       TmpInst.addOperand(Rt);
1371       Inst = TmpInst;
1372     } else {
1373       MO.setExpr(HexagonMCExpr::create(
1374           MCBinaryExpr::createSub(MO.getExpr(),
1375                                   MCConstantExpr::create(1, Context), Context),
1376           Context));
1377       Inst.setOpcode(Hexagon::C2_cmpgtui);
1378     }
1379     break;
1380   }
1381 
1382   // Translate a "$Rdd = $Rss" to "$Rdd = combine($Rs, $Rt)"
1383   case Hexagon::A2_tfrp: {
1384     MCOperand &MO = Inst.getOperand(1);
1385     unsigned int RegPairNum = RI->getEncodingValue(MO.getReg());
1386     std::string R1 = r + utostr(RegPairNum + 1);
1387     StringRef Reg1(R1);
1388     MO.setReg(matchRegister(Reg1));
1389     // Add a new operand for the second register in the pair.
1390     std::string R2 = r + utostr(RegPairNum);
1391     StringRef Reg2(R2);
1392     Inst.addOperand(MCOperand::createReg(matchRegister(Reg2)));
1393     Inst.setOpcode(Hexagon::A2_combinew);
1394     break;
1395   }
1396 
1397   case Hexagon::A2_tfrpt:
1398   case Hexagon::A2_tfrpf: {
1399     MCOperand &MO = Inst.getOperand(2);
1400     unsigned int RegPairNum = RI->getEncodingValue(MO.getReg());
1401     std::string R1 = r + utostr(RegPairNum + 1);
1402     StringRef Reg1(R1);
1403     MO.setReg(matchRegister(Reg1));
1404     // Add a new operand for the second register in the pair.
1405     std::string R2 = r + utostr(RegPairNum);
1406     StringRef Reg2(R2);
1407     Inst.addOperand(MCOperand::createReg(matchRegister(Reg2)));
1408     Inst.setOpcode((Inst.getOpcode() == Hexagon::A2_tfrpt)
1409                        ? Hexagon::C2_ccombinewt
1410                        : Hexagon::C2_ccombinewf);
1411     break;
1412   }
1413   case Hexagon::A2_tfrptnew:
1414   case Hexagon::A2_tfrpfnew: {
1415     MCOperand &MO = Inst.getOperand(2);
1416     unsigned int RegPairNum = RI->getEncodingValue(MO.getReg());
1417     std::string R1 = r + utostr(RegPairNum + 1);
1418     StringRef Reg1(R1);
1419     MO.setReg(matchRegister(Reg1));
1420     // Add a new operand for the second register in the pair.
1421     std::string R2 = r + utostr(RegPairNum);
1422     StringRef Reg2(R2);
1423     Inst.addOperand(MCOperand::createReg(matchRegister(Reg2)));
1424     Inst.setOpcode((Inst.getOpcode() == Hexagon::A2_tfrptnew)
1425                        ? Hexagon::C2_ccombinewnewt
1426                        : Hexagon::C2_ccombinewnewf);
1427     break;
1428   }
1429 
1430   // Translate a "$Vdd = $Vss" to "$Vdd = vcombine($Vs, $Vt)"
1431   case Hexagon::V6_vassignp: {
1432     MCOperand &MO = Inst.getOperand(1);
1433     unsigned int RegPairNum = RI->getEncodingValue(MO.getReg());
1434     std::string R1 = v + utostr(RegPairNum + 1);
1435     MO.setReg(MatchRegisterName(R1));
1436     // Add a new operand for the second register in the pair.
1437     std::string R2 = v + utostr(RegPairNum);
1438     Inst.addOperand(MCOperand::createReg(MatchRegisterName(R2)));
1439     Inst.setOpcode(Hexagon::V6_vcombine);
1440     break;
1441   }
1442 
1443   // Translate a "$Rx =  CONST32(#imm)" to "$Rx = memw(gp+#LABEL) "
1444   case Hexagon::CONST32:
1445     is32bit = true;
1446     LLVM_FALLTHROUGH;
1447   // Translate a "$Rx:y =  CONST64(#imm)" to "$Rx:y = memd(gp+#LABEL) "
1448   case Hexagon::CONST64:
1449     // FIXME: need better way to detect AsmStreamer (upstream removed getKind())
1450     if (!Parser.getStreamer().hasRawTextSupport()) {
1451       MCELFStreamer *MES = static_cast<MCELFStreamer *>(&Parser.getStreamer());
1452       MCOperand &MO_1 = Inst.getOperand(1);
1453       MCOperand &MO_0 = Inst.getOperand(0);
1454 
1455       // push section onto section stack
1456       MES->PushSection();
1457 
1458       std::string myCharStr;
1459       MCSectionELF *mySection;
1460 
1461       // check if this as an immediate or a symbol
1462       int64_t Value;
1463       bool Absolute = MO_1.getExpr()->evaluateAsAbsolute(Value);
1464       if (Absolute) {
1465         // Create a new section - one for each constant
1466         // Some or all of the zeros are replaced with the given immediate.
1467         if (is32bit) {
1468           std::string myImmStr = utohexstr(static_cast<uint32_t>(Value));
1469           myCharStr = StringRef(".gnu.linkonce.l4.CONST_00000000")
1470                           .drop_back(myImmStr.size())
1471                           .str() +
1472                       myImmStr;
1473         } else {
1474           std::string myImmStr = utohexstr(Value);
1475           myCharStr = StringRef(".gnu.linkonce.l8.CONST_0000000000000000")
1476                           .drop_back(myImmStr.size())
1477                           .str() +
1478                       myImmStr;
1479         }
1480 
1481         mySection = getContext().getELFSection(myCharStr, ELF::SHT_PROGBITS,
1482                                                ELF::SHF_ALLOC | ELF::SHF_WRITE);
1483       } else if (MO_1.isExpr()) {
1484         // .lita - for expressions
1485         myCharStr = ".lita";
1486         mySection = getContext().getELFSection(myCharStr, ELF::SHT_PROGBITS,
1487                                                ELF::SHF_ALLOC | ELF::SHF_WRITE);
1488       } else
1489         llvm_unreachable("unexpected type of machine operand!");
1490 
1491       MES->SwitchSection(mySection);
1492       unsigned byteSize = is32bit ? 4 : 8;
1493       getStreamer().EmitCodeAlignment(byteSize, byteSize);
1494 
1495       MCSymbol *Sym;
1496 
1497       // for symbols, get rid of prepended ".gnu.linkonce.lx."
1498 
1499       // emit symbol if needed
1500       if (Absolute) {
1501         Sym = getContext().getOrCreateSymbol(StringRef(myCharStr.c_str() + 16));
1502         if (Sym->isUndefined()) {
1503           getStreamer().EmitLabel(Sym);
1504           getStreamer().EmitSymbolAttribute(Sym, MCSA_Global);
1505           getStreamer().EmitIntValue(Value, byteSize);
1506         }
1507       } else if (MO_1.isExpr()) {
1508         const char *StringStart = nullptr;
1509         const char *StringEnd = nullptr;
1510         if (*Operands[4]->getStartLoc().getPointer() == '#') {
1511           StringStart = Operands[5]->getStartLoc().getPointer();
1512           StringEnd = Operands[6]->getStartLoc().getPointer();
1513         } else { // no pound
1514           StringStart = Operands[4]->getStartLoc().getPointer();
1515           StringEnd = Operands[5]->getStartLoc().getPointer();
1516         }
1517 
1518         unsigned size = StringEnd - StringStart;
1519         std::string DotConst = ".CONST_";
1520         Sym = getContext().getOrCreateSymbol(DotConst +
1521                                              StringRef(StringStart, size));
1522 
1523         if (Sym->isUndefined()) {
1524           // case where symbol is not yet defined: emit symbol
1525           getStreamer().EmitLabel(Sym);
1526           getStreamer().EmitSymbolAttribute(Sym, MCSA_Local);
1527           getStreamer().EmitValue(MO_1.getExpr(), 4);
1528         }
1529       } else
1530         llvm_unreachable("unexpected type of machine operand!");
1531 
1532       MES->PopSection();
1533 
1534       if (Sym) {
1535         MCInst TmpInst;
1536         if (is32bit) // 32 bit
1537           TmpInst.setOpcode(Hexagon::L2_loadrigp);
1538         else // 64 bit
1539           TmpInst.setOpcode(Hexagon::L2_loadrdgp);
1540 
1541         TmpInst.addOperand(MO_0);
1542         TmpInst.addOperand(MCOperand::createExpr(HexagonMCExpr::create(
1543             MCSymbolRefExpr::create(Sym, getContext()), getContext())));
1544         Inst = TmpInst;
1545       }
1546     }
1547     break;
1548 
1549   // Translate a "$Rdd = #-imm" to "$Rdd = combine(#[-1,0], #-imm)"
1550   case Hexagon::A2_tfrpi: {
1551     MCOperand &Rdd = Inst.getOperand(0);
1552     MCOperand &MO = Inst.getOperand(1);
1553     int64_t Value;
1554     int sVal = (MO.getExpr()->evaluateAsAbsolute(Value) && Value < 0) ? -1 : 0;
1555     MCOperand imm(MCOperand::createExpr(
1556         HexagonMCExpr::create(MCConstantExpr::create(sVal, Context), Context)));
1557     Inst = makeCombineInst(Hexagon::A2_combineii, Rdd, imm, MO);
1558     break;
1559   }
1560 
1561   // Translate a "$Rdd = [#]#imm" to "$Rdd = combine(#, [#]#imm)"
1562   case Hexagon::TFRI64_V4: {
1563     MCOperand &Rdd = Inst.getOperand(0);
1564     MCOperand &MO = Inst.getOperand(1);
1565     int64_t Value;
1566     if (MO.getExpr()->evaluateAsAbsolute(Value)) {
1567       int s8 = Hi_32(Value);
1568       if (!isInt<8>(s8))
1569         OutOfRange(IDLoc, s8, -128);
1570       MCOperand imm(MCOperand::createExpr(HexagonMCExpr::create(
1571           MCConstantExpr::create(s8, Context), Context))); // upper 32
1572       auto Expr = HexagonMCExpr::create(
1573           MCConstantExpr::create(Lo_32(Value), Context), Context);
1574       HexagonMCInstrInfo::setMustExtend(
1575           *Expr, HexagonMCInstrInfo::mustExtend(*MO.getExpr()));
1576       MCOperand imm2(MCOperand::createExpr(Expr)); // lower 32
1577       Inst = makeCombineInst(Hexagon::A4_combineii, Rdd, imm, imm2);
1578     } else {
1579       MCOperand imm(MCOperand::createExpr(HexagonMCExpr::create(
1580           MCConstantExpr::create(0, Context), Context))); // upper 32
1581       Inst = makeCombineInst(Hexagon::A4_combineii, Rdd, imm, MO);
1582     }
1583     break;
1584   }
1585 
1586   // Handle $Rdd = combine(##imm, #imm)"
1587   case Hexagon::TFRI64_V2_ext: {
1588     MCOperand &Rdd = Inst.getOperand(0);
1589     MCOperand &MO1 = Inst.getOperand(1);
1590     MCOperand &MO2 = Inst.getOperand(2);
1591     int64_t Value;
1592     if (MO2.getExpr()->evaluateAsAbsolute(Value)) {
1593       int s8 = Value;
1594       if (s8 < -128 || s8 > 127)
1595         OutOfRange(IDLoc, s8, -128);
1596     }
1597     Inst = makeCombineInst(Hexagon::A2_combineii, Rdd, MO1, MO2);
1598     break;
1599   }
1600 
1601   // Handle $Rdd = combine(#imm, ##imm)"
1602   case Hexagon::A4_combineii: {
1603     MCOperand &Rdd = Inst.getOperand(0);
1604     MCOperand &MO1 = Inst.getOperand(1);
1605     int64_t Value;
1606     if (MO1.getExpr()->evaluateAsAbsolute(Value)) {
1607       int s8 = Value;
1608       if (s8 < -128 || s8 > 127)
1609         OutOfRange(IDLoc, s8, -128);
1610     }
1611     MCOperand &MO2 = Inst.getOperand(2);
1612     Inst = makeCombineInst(Hexagon::A4_combineii, Rdd, MO1, MO2);
1613     break;
1614   }
1615 
1616   case Hexagon::S2_tableidxb_goodsyntax:
1617     Inst.setOpcode(Hexagon::S2_tableidxb);
1618     break;
1619 
1620   case Hexagon::S2_tableidxh_goodsyntax: {
1621     MCInst TmpInst;
1622     MCOperand &Rx = Inst.getOperand(0);
1623     MCOperand &Rs = Inst.getOperand(2);
1624     MCOperand &Imm4 = Inst.getOperand(3);
1625     MCOperand &Imm6 = Inst.getOperand(4);
1626     Imm6.setExpr(HexagonMCExpr::create(
1627         MCBinaryExpr::createSub(Imm6.getExpr(),
1628                                 MCConstantExpr::create(1, Context), Context),
1629         Context));
1630     TmpInst.setOpcode(Hexagon::S2_tableidxh);
1631     TmpInst.addOperand(Rx);
1632     TmpInst.addOperand(Rx);
1633     TmpInst.addOperand(Rs);
1634     TmpInst.addOperand(Imm4);
1635     TmpInst.addOperand(Imm6);
1636     Inst = TmpInst;
1637     break;
1638   }
1639 
1640   case Hexagon::S2_tableidxw_goodsyntax: {
1641     MCInst TmpInst;
1642     MCOperand &Rx = Inst.getOperand(0);
1643     MCOperand &Rs = Inst.getOperand(2);
1644     MCOperand &Imm4 = Inst.getOperand(3);
1645     MCOperand &Imm6 = Inst.getOperand(4);
1646     Imm6.setExpr(HexagonMCExpr::create(
1647         MCBinaryExpr::createSub(Imm6.getExpr(),
1648                                 MCConstantExpr::create(2, Context), Context),
1649         Context));
1650     TmpInst.setOpcode(Hexagon::S2_tableidxw);
1651     TmpInst.addOperand(Rx);
1652     TmpInst.addOperand(Rx);
1653     TmpInst.addOperand(Rs);
1654     TmpInst.addOperand(Imm4);
1655     TmpInst.addOperand(Imm6);
1656     Inst = TmpInst;
1657     break;
1658   }
1659 
1660   case Hexagon::S2_tableidxd_goodsyntax: {
1661     MCInst TmpInst;
1662     MCOperand &Rx = Inst.getOperand(0);
1663     MCOperand &Rs = Inst.getOperand(2);
1664     MCOperand &Imm4 = Inst.getOperand(3);
1665     MCOperand &Imm6 = Inst.getOperand(4);
1666     Imm6.setExpr(HexagonMCExpr::create(
1667         MCBinaryExpr::createSub(Imm6.getExpr(),
1668                                 MCConstantExpr::create(3, Context), Context),
1669         Context));
1670     TmpInst.setOpcode(Hexagon::S2_tableidxd);
1671     TmpInst.addOperand(Rx);
1672     TmpInst.addOperand(Rx);
1673     TmpInst.addOperand(Rs);
1674     TmpInst.addOperand(Imm4);
1675     TmpInst.addOperand(Imm6);
1676     Inst = TmpInst;
1677     break;
1678   }
1679 
1680   case Hexagon::M2_mpyui:
1681     Inst.setOpcode(Hexagon::M2_mpyi);
1682     break;
1683   case Hexagon::M2_mpysmi: {
1684     MCInst TmpInst;
1685     MCOperand &Rd = Inst.getOperand(0);
1686     MCOperand &Rs = Inst.getOperand(1);
1687     MCOperand &Imm = Inst.getOperand(2);
1688     int64_t Value;
1689     MCExpr const &Expr = *Imm.getExpr();
1690     bool Absolute = Expr.evaluateAsAbsolute(Value);
1691     if (!Absolute)
1692       return Match_InvalidOperand;
1693     if (!HexagonMCInstrInfo::mustExtend(Expr) &&
1694         ((Value <= -256) || Value >= 256))
1695       return Match_InvalidOperand;
1696     if (Value < 0 && Value > -256) {
1697       Imm.setExpr(HexagonMCExpr::create(
1698           MCConstantExpr::create(Value * -1, Context), Context));
1699       TmpInst.setOpcode(Hexagon::M2_mpysin);
1700     } else
1701       TmpInst.setOpcode(Hexagon::M2_mpysip);
1702     TmpInst.addOperand(Rd);
1703     TmpInst.addOperand(Rs);
1704     TmpInst.addOperand(Imm);
1705     Inst = TmpInst;
1706     break;
1707   }
1708 
1709   case Hexagon::S2_asr_i_r_rnd_goodsyntax: {
1710     MCOperand &Imm = Inst.getOperand(2);
1711     MCInst TmpInst;
1712     int64_t Value;
1713     bool Absolute = Imm.getExpr()->evaluateAsAbsolute(Value);
1714     if (!Absolute)
1715       return Match_InvalidOperand;
1716     if (Value == 0) { // convert to $Rd = $Rs
1717       TmpInst.setOpcode(Hexagon::A2_tfr);
1718       MCOperand &Rd = Inst.getOperand(0);
1719       MCOperand &Rs = Inst.getOperand(1);
1720       TmpInst.addOperand(Rd);
1721       TmpInst.addOperand(Rs);
1722     } else {
1723       Imm.setExpr(HexagonMCExpr::create(
1724           MCBinaryExpr::createSub(Imm.getExpr(),
1725                                   MCConstantExpr::create(1, Context), Context),
1726           Context));
1727       TmpInst.setOpcode(Hexagon::S2_asr_i_r_rnd);
1728       MCOperand &Rd = Inst.getOperand(0);
1729       MCOperand &Rs = Inst.getOperand(1);
1730       TmpInst.addOperand(Rd);
1731       TmpInst.addOperand(Rs);
1732       TmpInst.addOperand(Imm);
1733     }
1734     Inst = TmpInst;
1735     break;
1736   }
1737 
1738   case Hexagon::S2_asr_i_p_rnd_goodsyntax: {
1739     MCOperand &Rdd = Inst.getOperand(0);
1740     MCOperand &Rss = Inst.getOperand(1);
1741     MCOperand &Imm = Inst.getOperand(2);
1742     int64_t Value;
1743     bool Absolute = Imm.getExpr()->evaluateAsAbsolute(Value);
1744     if (!Absolute)
1745       return Match_InvalidOperand;
1746     if (Value == 0) { // convert to $Rdd = combine ($Rs[0], $Rs[1])
1747       MCInst TmpInst;
1748       unsigned int RegPairNum = RI->getEncodingValue(Rss.getReg());
1749       std::string R1 = r + utostr(RegPairNum + 1);
1750       StringRef Reg1(R1);
1751       Rss.setReg(matchRegister(Reg1));
1752       // Add a new operand for the second register in the pair.
1753       std::string R2 = r + utostr(RegPairNum);
1754       StringRef Reg2(R2);
1755       TmpInst.setOpcode(Hexagon::A2_combinew);
1756       TmpInst.addOperand(Rdd);
1757       TmpInst.addOperand(Rss);
1758       TmpInst.addOperand(MCOperand::createReg(matchRegister(Reg2)));
1759       Inst = TmpInst;
1760     } else {
1761       Imm.setExpr(HexagonMCExpr::create(
1762           MCBinaryExpr::createSub(Imm.getExpr(),
1763                                   MCConstantExpr::create(1, Context), Context),
1764           Context));
1765       Inst.setOpcode(Hexagon::S2_asr_i_p_rnd);
1766     }
1767     break;
1768   }
1769 
1770   case Hexagon::A4_boundscheck: {
1771     MCOperand &Rs = Inst.getOperand(1);
1772     unsigned int RegNum = RI->getEncodingValue(Rs.getReg());
1773     if (RegNum & 1) { // Odd mapped to raw:hi, regpair is rodd:odd-1, like r3:2
1774       Inst.setOpcode(Hexagon::A4_boundscheck_hi);
1775       std::string Name = r + utostr(RegNum) + Colon + utostr(RegNum - 1);
1776       StringRef RegPair = Name;
1777       Rs.setReg(matchRegister(RegPair));
1778     } else { // raw:lo
1779       Inst.setOpcode(Hexagon::A4_boundscheck_lo);
1780       std::string Name = r + utostr(RegNum + 1) + Colon + utostr(RegNum);
1781       StringRef RegPair = Name;
1782       Rs.setReg(matchRegister(RegPair));
1783     }
1784     break;
1785   }
1786 
1787   case Hexagon::A2_addsp: {
1788     MCOperand &Rs = Inst.getOperand(1);
1789     unsigned int RegNum = RI->getEncodingValue(Rs.getReg());
1790     if (RegNum & 1) { // Odd mapped to raw:hi
1791       Inst.setOpcode(Hexagon::A2_addsph);
1792       std::string Name = r + utostr(RegNum) + Colon + utostr(RegNum - 1);
1793       StringRef RegPair = Name;
1794       Rs.setReg(matchRegister(RegPair));
1795     } else { // Even mapped raw:lo
1796       Inst.setOpcode(Hexagon::A2_addspl);
1797       std::string Name = r + utostr(RegNum + 1) + Colon + utostr(RegNum);
1798       StringRef RegPair = Name;
1799       Rs.setReg(matchRegister(RegPair));
1800     }
1801     break;
1802   }
1803 
1804   case Hexagon::M2_vrcmpys_s1: {
1805     MCOperand &Rt = Inst.getOperand(2);
1806     unsigned int RegNum = RI->getEncodingValue(Rt.getReg());
1807     if (RegNum & 1) { // Odd mapped to sat:raw:hi
1808       Inst.setOpcode(Hexagon::M2_vrcmpys_s1_h);
1809       std::string Name = r + utostr(RegNum) + Colon + utostr(RegNum - 1);
1810       StringRef RegPair = Name;
1811       Rt.setReg(matchRegister(RegPair));
1812     } else { // Even mapped sat:raw:lo
1813       Inst.setOpcode(Hexagon::M2_vrcmpys_s1_l);
1814       std::string Name = r + utostr(RegNum + 1) + Colon + utostr(RegNum);
1815       StringRef RegPair = Name;
1816       Rt.setReg(matchRegister(RegPair));
1817     }
1818     break;
1819   }
1820 
1821   case Hexagon::M2_vrcmpys_acc_s1: {
1822     MCInst TmpInst;
1823     MCOperand &Rxx = Inst.getOperand(0);
1824     MCOperand &Rss = Inst.getOperand(2);
1825     MCOperand &Rt = Inst.getOperand(3);
1826     unsigned int RegNum = RI->getEncodingValue(Rt.getReg());
1827     if (RegNum & 1) { // Odd mapped to sat:raw:hi
1828       TmpInst.setOpcode(Hexagon::M2_vrcmpys_acc_s1_h);
1829       std::string Name = r + utostr(RegNum) + Colon + utostr(RegNum - 1);
1830       StringRef RegPair = Name;
1831       Rt.setReg(matchRegister(RegPair));
1832     } else { // Even mapped sat:raw:lo
1833       TmpInst.setOpcode(Hexagon::M2_vrcmpys_acc_s1_l);
1834       std::string Name = r + utostr(RegNum + 1) + Colon + utostr(RegNum);
1835       StringRef RegPair = Name;
1836       Rt.setReg(matchRegister(RegPair));
1837     }
1838     // Registers are in different positions
1839     TmpInst.addOperand(Rxx);
1840     TmpInst.addOperand(Rxx);
1841     TmpInst.addOperand(Rss);
1842     TmpInst.addOperand(Rt);
1843     Inst = TmpInst;
1844     break;
1845   }
1846 
1847   case Hexagon::M2_vrcmpys_s1rp: {
1848     MCOperand &Rt = Inst.getOperand(2);
1849     unsigned int RegNum = RI->getEncodingValue(Rt.getReg());
1850     if (RegNum & 1) { // Odd mapped to rnd:sat:raw:hi
1851       Inst.setOpcode(Hexagon::M2_vrcmpys_s1rp_h);
1852       std::string Name = r + utostr(RegNum) + Colon + utostr(RegNum - 1);
1853       StringRef RegPair = Name;
1854       Rt.setReg(matchRegister(RegPair));
1855     } else { // Even mapped rnd:sat:raw:lo
1856       Inst.setOpcode(Hexagon::M2_vrcmpys_s1rp_l);
1857       std::string Name = r + utostr(RegNum + 1) + Colon + utostr(RegNum);
1858       StringRef RegPair = Name;
1859       Rt.setReg(matchRegister(RegPair));
1860     }
1861     break;
1862   }
1863 
1864   case Hexagon::S5_asrhub_rnd_sat_goodsyntax: {
1865     MCOperand &Imm = Inst.getOperand(2);
1866     int64_t Value;
1867     bool Absolute = Imm.getExpr()->evaluateAsAbsolute(Value);
1868     if (!Absolute)
1869       return Match_InvalidOperand;
1870     if (Value == 0)
1871       Inst.setOpcode(Hexagon::S2_vsathub);
1872     else {
1873       Imm.setExpr(HexagonMCExpr::create(
1874           MCBinaryExpr::createSub(Imm.getExpr(),
1875                                   MCConstantExpr::create(1, Context), Context),
1876           Context));
1877       Inst.setOpcode(Hexagon::S5_asrhub_rnd_sat);
1878     }
1879     break;
1880   }
1881 
1882   case Hexagon::S5_vasrhrnd_goodsyntax: {
1883     MCOperand &Rdd = Inst.getOperand(0);
1884     MCOperand &Rss = Inst.getOperand(1);
1885     MCOperand &Imm = Inst.getOperand(2);
1886     int64_t Value;
1887     bool Absolute = Imm.getExpr()->evaluateAsAbsolute(Value);
1888     if (!Absolute)
1889       return Match_InvalidOperand;
1890     if (Value == 0) {
1891       MCInst TmpInst;
1892       unsigned int RegPairNum = RI->getEncodingValue(Rss.getReg());
1893       std::string R1 = r + utostr(RegPairNum + 1);
1894       StringRef Reg1(R1);
1895       Rss.setReg(matchRegister(Reg1));
1896       // Add a new operand for the second register in the pair.
1897       std::string R2 = r + utostr(RegPairNum);
1898       StringRef Reg2(R2);
1899       TmpInst.setOpcode(Hexagon::A2_combinew);
1900       TmpInst.addOperand(Rdd);
1901       TmpInst.addOperand(Rss);
1902       TmpInst.addOperand(MCOperand::createReg(matchRegister(Reg2)));
1903       Inst = TmpInst;
1904     } else {
1905       Imm.setExpr(HexagonMCExpr::create(
1906           MCBinaryExpr::createSub(Imm.getExpr(),
1907                                   MCConstantExpr::create(1, Context), Context),
1908           Context));
1909       Inst.setOpcode(Hexagon::S5_vasrhrnd);
1910     }
1911     break;
1912   }
1913 
1914   case Hexagon::A2_not: {
1915     MCInst TmpInst;
1916     MCOperand &Rd = Inst.getOperand(0);
1917     MCOperand &Rs = Inst.getOperand(1);
1918     TmpInst.setOpcode(Hexagon::A2_subri);
1919     TmpInst.addOperand(Rd);
1920     TmpInst.addOperand(MCOperand::createExpr(
1921         HexagonMCExpr::create(MCConstantExpr::create(-1, Context), Context)));
1922     TmpInst.addOperand(Rs);
1923     Inst = TmpInst;
1924     break;
1925   }
1926   case Hexagon::PS_loadrubabs:
1927     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(1).getExpr()))
1928       Inst.setOpcode(Hexagon::L2_loadrubgp);
1929     break;
1930   case Hexagon::PS_loadrbabs:
1931     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(1).getExpr()))
1932       Inst.setOpcode(Hexagon::L2_loadrbgp);
1933     break;
1934   case Hexagon::PS_loadruhabs:
1935     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(1).getExpr()))
1936       Inst.setOpcode(Hexagon::L2_loadruhgp);
1937     break;
1938   case Hexagon::PS_loadrhabs:
1939     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(1).getExpr()))
1940       Inst.setOpcode(Hexagon::L2_loadrhgp);
1941     break;
1942   case Hexagon::PS_loadriabs:
1943     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(1).getExpr()))
1944       Inst.setOpcode(Hexagon::L2_loadrigp);
1945     break;
1946   case Hexagon::PS_loadrdabs:
1947     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(1).getExpr()))
1948       Inst.setOpcode(Hexagon::L2_loadrdgp);
1949     break;
1950   case Hexagon::PS_storerbabs:
1951     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(0).getExpr()))
1952       Inst.setOpcode(Hexagon::S2_storerbgp);
1953     break;
1954   case Hexagon::PS_storerhabs:
1955     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(0).getExpr()))
1956       Inst.setOpcode(Hexagon::S2_storerhgp);
1957     break;
1958   case Hexagon::PS_storerfabs:
1959     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(0).getExpr()))
1960       Inst.setOpcode(Hexagon::S2_storerfgp);
1961     break;
1962   case Hexagon::PS_storeriabs:
1963     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(0).getExpr()))
1964       Inst.setOpcode(Hexagon::S2_storerigp);
1965     break;
1966   case Hexagon::PS_storerdabs:
1967     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(0).getExpr()))
1968       Inst.setOpcode(Hexagon::S2_storerdgp);
1969     break;
1970   case Hexagon::PS_storerbnewabs:
1971     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(0).getExpr()))
1972       Inst.setOpcode(Hexagon::S2_storerbnewgp);
1973     break;
1974   case Hexagon::PS_storerhnewabs:
1975     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(0).getExpr()))
1976       Inst.setOpcode(Hexagon::S2_storerhnewgp);
1977     break;
1978   case Hexagon::PS_storerinewabs:
1979     if (!HexagonMCInstrInfo::mustExtend(*Inst.getOperand(0).getExpr()))
1980       Inst.setOpcode(Hexagon::S2_storerinewgp);
1981     break;
1982   case Hexagon::A2_zxtb: {
1983     Inst.setOpcode(Hexagon::A2_andir);
1984     Inst.addOperand(
1985         MCOperand::createExpr(MCConstantExpr::create(255, Context)));
1986     break;
1987   }
1988   } // switch
1989 
1990   return Match_Success;
1991 }
1992 
1993 unsigned HexagonAsmParser::matchRegister(StringRef Name) {
1994   if (unsigned Reg = MatchRegisterName(Name))
1995     return Reg;
1996   return MatchRegisterAltName(Name);
1997 }
1998