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