1 //===- RISCVVEmitter.cpp - Generate riscv_vector.h for use with clang -----===//
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 // This tablegen backend is responsible for emitting riscv_vector.h which
10 // includes a declaration and definition of each intrinsic functions specified
11 // in https://github.com/riscv/rvv-intrinsic-doc.
12 //
13 // See also the documentation in include/clang/Basic/riscv_vector.td.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
25 #include <numeric>
26 
27 using namespace llvm;
28 using BasicType = char;
29 using VScaleVal = Optional<unsigned>;
30 
31 namespace {
32 
33 // Exponential LMUL
34 struct LMULType {
35   int Log2LMUL;
36   LMULType(int Log2LMUL);
37   // Return the C/C++ string representation of LMUL
38   std::string str() const;
39   Optional<unsigned> getScale(unsigned ElementBitwidth) const;
40   void MulLog2LMUL(int Log2LMUL);
41   LMULType &operator*=(uint32_t RHS);
42 };
43 
44 // This class is compact representation of a valid and invalid RVVType.
45 class RVVType {
46   enum ScalarTypeKind : uint32_t {
47     Void,
48     Size_t,
49     Ptrdiff_t,
50     UnsignedLong,
51     SignedLong,
52     Boolean,
53     SignedInteger,
54     UnsignedInteger,
55     Float,
56     Invalid,
57   };
58   BasicType BT;
59   ScalarTypeKind ScalarType = Invalid;
60   LMULType LMUL;
61   bool IsPointer = false;
62   // IsConstant indices are "int", but have the constant expression.
63   bool IsImmediate = false;
64   // Const qualifier for pointer to const object or object of const type.
65   bool IsConstant = false;
66   unsigned ElementBitwidth = 0;
67   VScaleVal Scale = 0;
68   bool Valid;
69 
70   std::string BuiltinStr;
71   std::string ClangBuiltinStr;
72   std::string Str;
73   std::string ShortStr;
74 
75 public:
76   RVVType() : RVVType(BasicType(), 0, StringRef()) {}
77   RVVType(BasicType BT, int Log2LMUL, StringRef prototype);
78 
79   // Return the string representation of a type, which is an encoded string for
80   // passing to the BUILTIN() macro in Builtins.def.
81   const std::string &getBuiltinStr() const { return BuiltinStr; }
82 
83   // Return the clang buitlin type for RVV vector type which are used in the
84   // riscv_vector.h header file.
85   const std::string &getClangBuiltinStr() const { return ClangBuiltinStr; }
86 
87   // Return the C/C++ string representation of a type for use in the
88   // riscv_vector.h header file.
89   const std::string &getTypeStr() const { return Str; }
90 
91   // Return the short name of a type for C/C++ name suffix.
92   const std::string &getShortStr() {
93     // Not all types are used in short name, so compute the short name by
94     // demanded.
95     if (ShortStr.empty())
96       initShortStr();
97     return ShortStr;
98   }
99 
100   bool isValid() const { return Valid; }
101   bool isScalar() const { return Scale.hasValue() && Scale.getValue() == 0; }
102   bool isVector() const { return Scale.hasValue() && Scale.getValue() != 0; }
103   bool isFloat() const { return ScalarType == ScalarTypeKind::Float; }
104   bool isSignedInteger() const {
105     return ScalarType == ScalarTypeKind::SignedInteger;
106   }
107   bool isFloatVector(unsigned Width) const {
108     return isVector() && isFloat() && ElementBitwidth == Width;
109   }
110 
111 private:
112   // Verify RVV vector type and set Valid.
113   bool verifyType() const;
114 
115   // Creates a type based on basic types of TypeRange
116   void applyBasicType();
117 
118   // Applies a prototype modifier to the current type. The result maybe an
119   // invalid type.
120   void applyModifier(StringRef prototype);
121 
122   // Compute and record a string for legal type.
123   void initBuiltinStr();
124   // Compute and record a builtin RVV vector type string.
125   void initClangBuiltinStr();
126   // Compute and record a type string for used in the header.
127   void initTypeStr();
128   // Compute and record a short name of a type for C/C++ name suffix.
129   void initShortStr();
130 };
131 
132 using RVVTypePtr = RVVType *;
133 using RVVTypes = std::vector<RVVTypePtr>;
134 
135 enum RISCVExtension : uint8_t {
136   Basic = 0,
137   F = 1 << 1,
138   D = 1 << 2,
139   Zfh = 1 << 3,
140   Zvamo = 1 << 4,
141 };
142 
143 // TODO refactor RVVIntrinsic class design after support all intrinsic
144 // combination. This represents an instantiation of an intrinsic with a
145 // particular type and prototype
146 class RVVIntrinsic {
147 
148 private:
149   std::string Name; // Builtin name
150   std::string MangledName;
151   std::string IRName;
152   bool HasSideEffects;
153   bool IsMask;
154   bool HasMaskedOffOperand;
155   bool HasVL;
156   bool HasNoMaskedOverloaded;
157   bool HasAutoDef; // There is automiatic definition in header
158   std::string ManualCodegen;
159   RVVTypePtr OutputType; // Builtin output type
160   RVVTypes InputTypes;   // Builtin input types
161   // The types we use to obtain the specific LLVM intrinsic. They are index of
162   // InputTypes. -1 means the return type.
163   std::vector<int64_t> IntrinsicTypes;
164   uint8_t RISCVExtensions = 0;
165 
166 public:
167   RVVIntrinsic(StringRef Name, StringRef Suffix, StringRef MangledName,
168                StringRef IRName, bool HasSideEffects, bool IsMask,
169                bool HasMaskedOffOperand, bool HasVL, bool HasNoMaskedOverloaded,
170                bool HasAutoDef, StringRef ManualCodegen, const RVVTypes &Types,
171                const std::vector<int64_t> &IntrinsicTypes,
172                StringRef RequiredExtension);
173   ~RVVIntrinsic() = default;
174 
175   StringRef getName() const { return Name; }
176   StringRef getMangledName() const { return MangledName; }
177   bool hasSideEffects() const { return HasSideEffects; }
178   bool hasMaskedOffOperand() const { return HasMaskedOffOperand; }
179   bool hasVL() const { return HasVL; }
180   bool hasNoMaskedOverloaded() const { return HasNoMaskedOverloaded; }
181   bool hasManualCodegen() const { return !ManualCodegen.empty(); }
182   bool hasAutoDef() const { return HasAutoDef; }
183   bool isMask() const { return IsMask; }
184   StringRef getIRName() const { return IRName; }
185   StringRef getManualCodegen() const { return ManualCodegen; }
186   uint8_t getRISCVExtensions() const { return RISCVExtensions; }
187 
188   // Return the type string for a BUILTIN() macro in Builtins.def.
189   std::string getBuiltinTypeStr() const;
190 
191   // Emit the code block for switch body in EmitRISCVBuiltinExpr, it should
192   // init the RVVIntrinsic ID and IntrinsicTypes.
193   void emitCodeGenSwitchBody(raw_ostream &o) const;
194 
195   // Emit the macros for mapping C/C++ intrinsic function to builtin functions.
196   void emitIntrinsicMacro(raw_ostream &o) const;
197 
198   // Emit the mangled function definition.
199   void emitMangledFuncDef(raw_ostream &o) const;
200 };
201 
202 class RVVEmitter {
203 private:
204   RecordKeeper &Records;
205   std::string HeaderCode;
206   // Concat BasicType, LMUL and Proto as key
207   StringMap<RVVType> LegalTypes;
208   StringSet<> IllegalTypes;
209 
210 public:
211   RVVEmitter(RecordKeeper &R) : Records(R) {}
212 
213   /// Emit riscv_vector.h
214   void createHeader(raw_ostream &o);
215 
216   /// Emit all the __builtin prototypes and code needed by Sema.
217   void createBuiltins(raw_ostream &o);
218 
219   /// Emit all the information needed to map builtin -> LLVM IR intrinsic.
220   void createCodeGen(raw_ostream &o);
221 
222   std::string getSuffixStr(char Type, int Log2LMUL, StringRef Prototypes);
223 
224 private:
225   /// Create all intrinsics and add them to \p Out
226   void createRVVIntrinsics(std::vector<std::unique_ptr<RVVIntrinsic>> &Out);
227   /// Compute output and input types by applying different config (basic type
228   /// and LMUL with type transformers). It also record result of type in legal
229   /// or illegal set to avoid compute the  same config again. The result maybe
230   /// have illegal RVVType.
231   Optional<RVVTypes> computeTypes(BasicType BT, int Log2LMUL,
232                                   ArrayRef<std::string> PrototypeSeq);
233   Optional<RVVTypePtr> computeType(BasicType BT, int Log2LMUL, StringRef Proto);
234 
235   /// Emit Acrh predecessor definitions and body, assume the element of Defs are
236   /// sorted by extension.
237   void emitArchMacroAndBody(
238       std::vector<std::unique_ptr<RVVIntrinsic>> &Defs, raw_ostream &o,
239       std::function<void(raw_ostream &, const RVVIntrinsic &)>);
240 
241   // Emit the architecture preprocessor definitions. Return true when emits
242   // non-empty string.
243   bool emitExtDefStr(uint8_t Extensions, raw_ostream &o);
244   // Slice Prototypes string into sub prototype string and process each sub
245   // prototype string individually in the Handler.
246   void parsePrototypes(StringRef Prototypes,
247                        std::function<void(StringRef)> Handler);
248 };
249 
250 } // namespace
251 
252 //===----------------------------------------------------------------------===//
253 // Type implementation
254 //===----------------------------------------------------------------------===//
255 
256 LMULType::LMULType(int NewLog2LMUL) {
257   // Check Log2LMUL is -3, -2, -1, 0, 1, 2, 3
258   assert(NewLog2LMUL <= 3 && NewLog2LMUL >= -3 && "Bad LMUL number!");
259   Log2LMUL = NewLog2LMUL;
260 }
261 
262 std::string LMULType::str() const {
263   if (Log2LMUL < 0)
264     return "mf" + utostr(1ULL << (-Log2LMUL));
265   return "m" + utostr(1ULL << Log2LMUL);
266 }
267 
268 VScaleVal LMULType::getScale(unsigned ElementBitwidth) const {
269   int Log2ScaleResult = 0;
270   switch (ElementBitwidth) {
271   default:
272     break;
273   case 8:
274     Log2ScaleResult = Log2LMUL + 3;
275     break;
276   case 16:
277     Log2ScaleResult = Log2LMUL + 2;
278     break;
279   case 32:
280     Log2ScaleResult = Log2LMUL + 1;
281     break;
282   case 64:
283     Log2ScaleResult = Log2LMUL;
284     break;
285   }
286   // Illegal vscale result would be less than 1
287   if (Log2ScaleResult < 0)
288     return None;
289   return 1 << Log2ScaleResult;
290 }
291 
292 void LMULType::MulLog2LMUL(int log2LMUL) { Log2LMUL += log2LMUL; }
293 
294 LMULType &LMULType::operator*=(uint32_t RHS) {
295   assert(isPowerOf2_32(RHS));
296   this->Log2LMUL = this->Log2LMUL + Log2_32(RHS);
297   return *this;
298 }
299 
300 RVVType::RVVType(BasicType BT, int Log2LMUL, StringRef prototype)
301     : BT(BT), LMUL(LMULType(Log2LMUL)) {
302   applyBasicType();
303   applyModifier(prototype);
304   Valid = verifyType();
305   if (Valid) {
306     initBuiltinStr();
307     initTypeStr();
308     if (isVector()) {
309       initClangBuiltinStr();
310     }
311   }
312 }
313 
314 // clang-format off
315 // boolean type are encoded the ratio of n (SEW/LMUL)
316 // SEW/LMUL | 1         | 2         | 4         | 8        | 16        | 32        | 64
317 // c type   | vbool64_t | vbool32_t | vbool16_t | vbool8_t | vbool4_t  | vbool2_t  | vbool1_t
318 // IR type  | nxv1i1    | nxv2i1    | nxv4i1    | nxv8i1   | nxv16i1   | nxv32i1   | nxv64i1
319 
320 // type\lmul | 1/8    | 1/4      | 1/2     | 1       | 2        | 4        | 8
321 // --------  |------  | -------- | ------- | ------- | -------- | -------- | --------
322 // i64       | N/A    | N/A      | N/A     | nxv1i64 | nxv2i64  | nxv4i64  | nxv8i64
323 // i32       | N/A    | N/A      | nxv1i32 | nxv2i32 | nxv4i32  | nxv8i32  | nxv16i32
324 // i16       | N/A    | nxv1i16  | nxv2i16 | nxv4i16 | nxv8i16  | nxv16i16 | nxv32i16
325 // i8        | nxv1i8 | nxv2i8   | nxv4i8  | nxv8i8  | nxv16i8  | nxv32i8  | nxv64i8
326 // double    | N/A    | N/A      | N/A     | nxv1f64 | nxv2f64  | nxv4f64  | nxv8f64
327 // float     | N/A    | N/A      | nxv1f32 | nxv2f32 | nxv4f32  | nxv8f32  | nxv16f32
328 // half      | N/A    | nxv1f16  | nxv2f16 | nxv4f16 | nxv8f16  | nxv16f16 | nxv32f16
329 // clang-format on
330 
331 bool RVVType::verifyType() const {
332   if (ScalarType == Invalid)
333     return false;
334   if (isScalar())
335     return true;
336   if (!Scale.hasValue())
337     return false;
338   if (isFloat() && ElementBitwidth == 8)
339     return false;
340   unsigned V = Scale.getValue();
341   switch (ElementBitwidth) {
342   case 1:
343   case 8:
344     // Check Scale is 1,2,4,8,16,32,64
345     return (V <= 64 && isPowerOf2_32(V));
346   case 16:
347     // Check Scale is 1,2,4,8,16,32
348     return (V <= 32 && isPowerOf2_32(V));
349   case 32:
350     // Check Scale is 1,2,4,8,16
351     return (V <= 16 && isPowerOf2_32(V));
352   case 64:
353     // Check Scale is 1,2,4,8
354     return (V <= 8 && isPowerOf2_32(V));
355   }
356   return false;
357 }
358 
359 void RVVType::initBuiltinStr() {
360   assert(isValid() && "RVVType is invalid");
361   switch (ScalarType) {
362   case ScalarTypeKind::Void:
363     BuiltinStr = "v";
364     return;
365   case ScalarTypeKind::Size_t:
366     BuiltinStr = "z";
367     if (IsImmediate)
368       BuiltinStr = "I" + BuiltinStr;
369     if (IsPointer)
370       BuiltinStr += "*";
371     return;
372   case ScalarTypeKind::Ptrdiff_t:
373     BuiltinStr = "Y";
374     return;
375   case ScalarTypeKind::UnsignedLong:
376     BuiltinStr = "ULi";
377     return;
378   case ScalarTypeKind::SignedLong:
379     BuiltinStr = "Li";
380     return;
381   case ScalarTypeKind::Boolean:
382     assert(ElementBitwidth == 1);
383     BuiltinStr += "b";
384     break;
385   case ScalarTypeKind::SignedInteger:
386   case ScalarTypeKind::UnsignedInteger:
387     switch (ElementBitwidth) {
388     case 8:
389       BuiltinStr += "c";
390       break;
391     case 16:
392       BuiltinStr += "s";
393       break;
394     case 32:
395       BuiltinStr += "i";
396       break;
397     case 64:
398       BuiltinStr += "Wi";
399       break;
400     default:
401       llvm_unreachable("Unhandled ElementBitwidth!");
402     }
403     if (isSignedInteger())
404       BuiltinStr = "S" + BuiltinStr;
405     else
406       BuiltinStr = "U" + BuiltinStr;
407     break;
408   case ScalarTypeKind::Float:
409     switch (ElementBitwidth) {
410     case 16:
411       BuiltinStr += "h";
412       break;
413     case 32:
414       BuiltinStr += "f";
415       break;
416     case 64:
417       BuiltinStr += "d";
418       break;
419     default:
420       llvm_unreachable("Unhandled ElementBitwidth!");
421     }
422     break;
423   default:
424     llvm_unreachable("ScalarType is invalid!");
425   }
426   if (IsImmediate)
427     BuiltinStr = "I" + BuiltinStr;
428   if (isScalar()) {
429     if (IsConstant)
430       BuiltinStr += "C";
431     if (IsPointer)
432       BuiltinStr += "*";
433     return;
434   }
435   BuiltinStr = "q" + utostr(Scale.getValue()) + BuiltinStr;
436 }
437 
438 void RVVType::initClangBuiltinStr() {
439   assert(isValid() && "RVVType is invalid");
440   assert(isVector() && "Handle Vector type only");
441 
442   ClangBuiltinStr = "__rvv_";
443   switch (ScalarType) {
444   case ScalarTypeKind::Boolean:
445     ClangBuiltinStr += "bool" + utostr(64 / Scale.getValue()) + "_t";
446     return;
447   case ScalarTypeKind::Float:
448     ClangBuiltinStr += "float";
449     break;
450   case ScalarTypeKind::SignedInteger:
451     ClangBuiltinStr += "int";
452     break;
453   case ScalarTypeKind::UnsignedInteger:
454     ClangBuiltinStr += "uint";
455     break;
456   default:
457     llvm_unreachable("ScalarTypeKind is invalid");
458   }
459   ClangBuiltinStr += utostr(ElementBitwidth) + LMUL.str() + "_t";
460 }
461 
462 void RVVType::initTypeStr() {
463   assert(isValid() && "RVVType is invalid");
464 
465   if (IsConstant)
466     Str += "const ";
467 
468   auto getTypeString = [&](StringRef TypeStr) {
469     if (isScalar())
470       return Twine(TypeStr + Twine(ElementBitwidth) + "_t").str();
471     return Twine("v" + TypeStr + Twine(ElementBitwidth) + LMUL.str() + "_t")
472         .str();
473   };
474 
475   switch (ScalarType) {
476   case ScalarTypeKind::Void:
477     Str = "void";
478     return;
479   case ScalarTypeKind::Size_t:
480     Str = "size_t";
481     if (IsPointer)
482       Str += " *";
483     return;
484   case ScalarTypeKind::Ptrdiff_t:
485     Str = "ptrdiff_t";
486     return;
487   case ScalarTypeKind::UnsignedLong:
488     Str = "unsigned long";
489     return;
490   case ScalarTypeKind::SignedLong:
491     Str = "long";
492     return;
493   case ScalarTypeKind::Boolean:
494     if (isScalar())
495       Str += "bool";
496     else
497       // Vector bool is special case, the formulate is
498       // `vbool<N>_t = MVT::nxv<64/N>i1` ex. vbool16_t = MVT::4i1
499       Str += "vbool" + utostr(64 / Scale.getValue()) + "_t";
500     break;
501   case ScalarTypeKind::Float:
502     if (isScalar()) {
503       if (ElementBitwidth == 64)
504         Str += "double";
505       else if (ElementBitwidth == 32)
506         Str += "float";
507       assert((ElementBitwidth == 32 || ElementBitwidth == 64) &&
508              "Unhandled floating type");
509     } else
510       Str += getTypeString("float");
511     break;
512   case ScalarTypeKind::SignedInteger:
513     Str += getTypeString("int");
514     break;
515   case ScalarTypeKind::UnsignedInteger:
516     Str += getTypeString("uint");
517     break;
518   default:
519     llvm_unreachable("ScalarType is invalid!");
520   }
521   if (IsPointer)
522     Str += " *";
523 }
524 
525 void RVVType::initShortStr() {
526   switch (ScalarType) {
527   case ScalarTypeKind::Boolean:
528     assert(isVector());
529     ShortStr = "b" + utostr(64 / Scale.getValue());
530     return;
531   case ScalarTypeKind::Float:
532     ShortStr = "f" + utostr(ElementBitwidth);
533     break;
534   case ScalarTypeKind::SignedInteger:
535     ShortStr = "i" + utostr(ElementBitwidth);
536     break;
537   case ScalarTypeKind::UnsignedInteger:
538     ShortStr = "u" + utostr(ElementBitwidth);
539     break;
540   default:
541     PrintFatalError("Unhandled case!");
542   }
543   if (isVector())
544     ShortStr += LMUL.str();
545 }
546 
547 void RVVType::applyBasicType() {
548   switch (BT) {
549   case 'c':
550     ElementBitwidth = 8;
551     ScalarType = ScalarTypeKind::SignedInteger;
552     break;
553   case 's':
554     ElementBitwidth = 16;
555     ScalarType = ScalarTypeKind::SignedInteger;
556     break;
557   case 'i':
558     ElementBitwidth = 32;
559     ScalarType = ScalarTypeKind::SignedInteger;
560     break;
561   case 'l':
562     ElementBitwidth = 64;
563     ScalarType = ScalarTypeKind::SignedInteger;
564     break;
565   case 'h':
566     ElementBitwidth = 16;
567     ScalarType = ScalarTypeKind::Float;
568     break;
569   case 'f':
570     ElementBitwidth = 32;
571     ScalarType = ScalarTypeKind::Float;
572     break;
573   case 'd':
574     ElementBitwidth = 64;
575     ScalarType = ScalarTypeKind::Float;
576     break;
577   default:
578     PrintFatalError("Unhandled type code!");
579   }
580   assert(ElementBitwidth != 0 && "Bad element bitwidth!");
581 }
582 
583 void RVVType::applyModifier(StringRef Transformer) {
584   if (Transformer.empty())
585     return;
586   // Handle primitive type transformer
587   auto PType = Transformer.back();
588   switch (PType) {
589   case 'e':
590     Scale = 0;
591     break;
592   case 'v':
593     Scale = LMUL.getScale(ElementBitwidth);
594     break;
595   case 'w':
596     ElementBitwidth *= 2;
597     LMUL *= 2;
598     Scale = LMUL.getScale(ElementBitwidth);
599     break;
600   case 'q':
601     ElementBitwidth *= 4;
602     LMUL *= 4;
603     Scale = LMUL.getScale(ElementBitwidth);
604     break;
605   case 'o':
606     ElementBitwidth *= 8;
607     LMUL *= 8;
608     Scale = LMUL.getScale(ElementBitwidth);
609     break;
610   case 'm':
611     ScalarType = ScalarTypeKind::Boolean;
612     Scale = LMUL.getScale(ElementBitwidth);
613     ElementBitwidth = 1;
614     break;
615   case '0':
616     ScalarType = ScalarTypeKind::Void;
617     break;
618   case 'z':
619     ScalarType = ScalarTypeKind::Size_t;
620     break;
621   case 't':
622     ScalarType = ScalarTypeKind::Ptrdiff_t;
623     break;
624   case 'u':
625     ScalarType = ScalarTypeKind::UnsignedLong;
626     break;
627   case 'l':
628     ScalarType = ScalarTypeKind::SignedLong;
629     break;
630   default:
631     PrintFatalError("Illegal primitive type transformers!");
632   }
633   Transformer = Transformer.drop_back();
634 
635   // Extract and compute complex type transformer. It can only appear one time.
636   if (Transformer.startswith("(")) {
637     size_t Idx = Transformer.find(')');
638     assert(Idx != StringRef::npos);
639     StringRef ComplexType = Transformer.slice(1, Idx);
640     Transformer = Transformer.drop_front(Idx + 1);
641     assert(Transformer.find('(') == StringRef::npos &&
642            "Only allow one complex type transformer");
643 
644     auto UpdateAndCheckComplexProto = [&]() {
645       Scale = LMUL.getScale(ElementBitwidth);
646       const StringRef VectorPrototypes("vwqom");
647       if (!VectorPrototypes.contains(PType))
648         PrintFatalError("Complex type transformer only supports vector type!");
649       if (Transformer.find_first_of("PCKWS") != StringRef::npos)
650         PrintFatalError(
651             "Illegal type transformer for Complex type transformer");
652     };
653     auto ComputeFixedLog2LMUL =
654         [&](StringRef Value,
655             std::function<bool(const int32_t &, const int32_t &)> Compare) {
656           int32_t Log2LMUL;
657           Value.getAsInteger(10, Log2LMUL);
658           if (!Compare(Log2LMUL, LMUL.Log2LMUL)) {
659             ScalarType = Invalid;
660             return false;
661           }
662           // Update new LMUL
663           LMUL = LMULType(Log2LMUL);
664           UpdateAndCheckComplexProto();
665           return true;
666         };
667     auto ComplexTT = ComplexType.split(":");
668     if (ComplexTT.first == "Log2EEW") {
669       uint32_t Log2EEW;
670       ComplexTT.second.getAsInteger(10, Log2EEW);
671       // update new elmul = (eew/sew) * lmul
672       LMUL.MulLog2LMUL(Log2EEW - Log2_32(ElementBitwidth));
673       // update new eew
674       ElementBitwidth = 1 << Log2EEW;
675       ScalarType = ScalarTypeKind::SignedInteger;
676       UpdateAndCheckComplexProto();
677     } else if (ComplexTT.first == "FixedSEW") {
678       uint32_t NewSEW;
679       ComplexTT.second.getAsInteger(10, NewSEW);
680       // Set invalid type if src and dst SEW are same.
681       if (ElementBitwidth == NewSEW) {
682         ScalarType = Invalid;
683         return;
684       }
685       // Update new SEW
686       ElementBitwidth = NewSEW;
687       UpdateAndCheckComplexProto();
688     } else if (ComplexTT.first == "LFixedLog2LMUL") {
689       // New LMUL should be larger than old
690       if (!ComputeFixedLog2LMUL(ComplexTT.second, std::greater<int32_t>()))
691         return;
692     } else if (ComplexTT.first == "SFixedLog2LMUL") {
693       // New LMUL should be smaller than old
694       if (!ComputeFixedLog2LMUL(ComplexTT.second, std::less<int32_t>()))
695         return;
696     } else {
697       PrintFatalError("Illegal complex type transformers!");
698     }
699   }
700 
701   // Compute the remain type transformers
702   for (char I : Transformer) {
703     switch (I) {
704     case 'P':
705       if (IsConstant)
706         PrintFatalError("'P' transformer cannot be used after 'C'");
707       if (IsPointer)
708         PrintFatalError("'P' transformer cannot be used twice");
709       IsPointer = true;
710       break;
711     case 'C':
712       if (IsConstant)
713         PrintFatalError("'C' transformer cannot be used twice");
714       IsConstant = true;
715       break;
716     case 'K':
717       IsImmediate = true;
718       break;
719     case 'U':
720       ScalarType = ScalarTypeKind::UnsignedInteger;
721       break;
722     case 'I':
723       ScalarType = ScalarTypeKind::SignedInteger;
724       break;
725     case 'F':
726       ScalarType = ScalarTypeKind::Float;
727       break;
728     case 'S':
729       LMUL = LMULType(0);
730       // Update ElementBitwidth need to update Scale too.
731       Scale = LMUL.getScale(ElementBitwidth);
732       break;
733     default:
734       PrintFatalError("Illegal non-primitive type transformer!");
735     }
736   }
737 }
738 
739 //===----------------------------------------------------------------------===//
740 // RVVIntrinsic implementation
741 //===----------------------------------------------------------------------===//
742 RVVIntrinsic::RVVIntrinsic(StringRef NewName, StringRef Suffix,
743                            StringRef NewMangledName, StringRef IRName,
744                            bool HasSideEffects, bool IsMask,
745                            bool HasMaskedOffOperand, bool HasVL,
746                            bool HasNoMaskedOverloaded, bool HasAutoDef,
747                            StringRef ManualCodegen, const RVVTypes &OutInTypes,
748                            const std::vector<int64_t> &NewIntrinsicTypes,
749                            StringRef RequiredExtension)
750     : IRName(IRName), HasSideEffects(HasSideEffects), IsMask(IsMask),
751       HasMaskedOffOperand(HasMaskedOffOperand), HasVL(HasVL),
752       HasNoMaskedOverloaded(HasNoMaskedOverloaded), HasAutoDef(HasAutoDef),
753       ManualCodegen(ManualCodegen.str()) {
754 
755   // Init Name and MangledName
756   Name = NewName.str();
757   if (NewMangledName.empty())
758     MangledName = NewName.split("_").first.str();
759   else
760     MangledName = NewMangledName.str();
761   if (!Suffix.empty())
762     Name += "_" + Suffix.str();
763   if (IsMask) {
764     Name += "_m";
765   }
766   // Init RISC-V extensions
767   for (const auto &T : OutInTypes) {
768     if (T->isFloatVector(16))
769       RISCVExtensions |= RISCVExtension::Zfh;
770     else if (T->isFloatVector(32))
771       RISCVExtensions |= RISCVExtension::F;
772     else if (T->isFloatVector(64))
773       RISCVExtensions |= RISCVExtension::D;
774   }
775   if (RequiredExtension == "Zvamo")
776     RISCVExtensions |= RISCVExtension::Zvamo;
777 
778   // Init OutputType and InputTypes
779   OutputType = OutInTypes[0];
780   InputTypes.assign(OutInTypes.begin() + 1, OutInTypes.end());
781 
782   // IntrinsicTypes is nonmasked version index. Need to update it
783   // if there is maskedoff operand (It is always in first operand).
784   IntrinsicTypes = NewIntrinsicTypes;
785   if (IsMask && HasMaskedOffOperand) {
786     for (auto &I : IntrinsicTypes) {
787       if (I >= 0)
788         I += 1;
789     }
790   }
791 }
792 
793 std::string RVVIntrinsic::getBuiltinTypeStr() const {
794   std::string S;
795   S += OutputType->getBuiltinStr();
796   for (const auto &T : InputTypes) {
797     S += T->getBuiltinStr();
798   }
799   return S;
800 }
801 
802 void RVVIntrinsic::emitCodeGenSwitchBody(raw_ostream &OS) const {
803   if (!getIRName().empty())
804     OS << "  ID = Intrinsic::riscv_" + getIRName() + ";\n";
805   if (hasManualCodegen()) {
806     OS << ManualCodegen;
807     OS << "break;\n";
808     return;
809   }
810 
811   if (isMask()) {
812     if (hasVL()) {
813       OS << "  std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end() - 1);\n";
814     } else {
815       OS << "  std::rotate(Ops.begin(), Ops.begin() + 1, Ops.end());\n";
816     }
817   }
818 
819   OS << "  IntrinsicTypes = {";
820   ListSeparator LS;
821   for (const auto &Idx : IntrinsicTypes) {
822     if (Idx == -1)
823       OS << LS << "ResultType";
824     else
825       OS << LS << "Ops[" << Idx << "]->getType()";
826   }
827 
828   // VL could be i64 or i32, need to encode it in IntrinsicTypes. VL is
829   // always last operand.
830   if (hasVL())
831     OS << ", Ops.back()->getType()";
832   OS << "};\n";
833   OS << "  break;\n";
834 }
835 
836 void RVVIntrinsic::emitIntrinsicMacro(raw_ostream &OS) const {
837   OS << "#define " << getName() << "(";
838   if (!InputTypes.empty()) {
839     ListSeparator LS;
840     for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
841       OS << LS << "op" << i;
842   }
843   OS << ") \\\n";
844   OS << "__builtin_rvv_" << getName() << "(";
845   if (!InputTypes.empty()) {
846     ListSeparator LS;
847     for (unsigned i = 0, e = InputTypes.size(); i != e; ++i)
848       OS << LS << "(" << InputTypes[i]->getTypeStr() << ")(op" << i << ")";
849   }
850   OS << ")\n";
851 }
852 
853 void RVVIntrinsic::emitMangledFuncDef(raw_ostream &OS) const {
854   OS << "__attribute__((clang_builtin_alias(";
855   OS << "__builtin_rvv_" << getName() << ")))\n";
856   OS << OutputType->getTypeStr() << " " << getMangledName() << "(";
857   // Emit function arguments
858   if (!InputTypes.empty()) {
859     ListSeparator LS;
860     for (unsigned i = 0; i < InputTypes.size(); ++i)
861       OS << LS << InputTypes[i]->getTypeStr() << " op" << i;
862   }
863   OS << ");\n\n";
864 }
865 
866 //===----------------------------------------------------------------------===//
867 // RVVEmitter implementation
868 //===----------------------------------------------------------------------===//
869 void RVVEmitter::createHeader(raw_ostream &OS) {
870 
871   OS << "/*===---- riscv_vector.h - RISC-V V-extension RVVIntrinsics "
872         "-------------------===\n"
873         " *\n"
874         " *\n"
875         " * Part of the LLVM Project, under the Apache License v2.0 with LLVM "
876         "Exceptions.\n"
877         " * See https://llvm.org/LICENSE.txt for license information.\n"
878         " * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n"
879         " *\n"
880         " *===-----------------------------------------------------------------"
881         "------===\n"
882         " */\n\n";
883 
884   OS << "#ifndef __RISCV_VECTOR_H\n";
885   OS << "#define __RISCV_VECTOR_H\n\n";
886 
887   OS << "#include <stdint.h>\n";
888   OS << "#include <stddef.h>\n\n";
889 
890   OS << "#ifndef __riscv_vector\n";
891   OS << "#error \"Vector intrinsics require the vector extension.\"\n";
892   OS << "#endif\n\n";
893 
894   OS << "#ifdef __cplusplus\n";
895   OS << "extern \"C\" {\n";
896   OS << "#endif\n\n";
897 
898   std::vector<std::unique_ptr<RVVIntrinsic>> Defs;
899   createRVVIntrinsics(Defs);
900 
901   // Print header code
902   if (!HeaderCode.empty()) {
903     OS << HeaderCode;
904   }
905 
906   auto printType = [&](auto T) {
907     OS << "typedef " << T->getClangBuiltinStr() << " " << T->getTypeStr()
908        << ";\n";
909   };
910 
911   constexpr int Log2LMULs[] = {-3, -2, -1, 0, 1, 2, 3};
912   // Print RVV boolean types.
913   for (int Log2LMUL : Log2LMULs) {
914     auto T = computeType('c', Log2LMUL, "m");
915     if (T.hasValue())
916       printType(T.getValue());
917   }
918   // Print RVV int/float types.
919   for (char I : StringRef("csil")) {
920     for (int Log2LMUL : Log2LMULs) {
921       auto T = computeType(I, Log2LMUL, "v");
922       if (T.hasValue()) {
923         printType(T.getValue());
924         auto UT = computeType(I, Log2LMUL, "Uv");
925         printType(UT.getValue());
926       }
927     }
928   }
929   OS << "#if defined(__riscv_zfh)\n";
930   for (int Log2LMUL : Log2LMULs) {
931     auto T = computeType('h', Log2LMUL, "v");
932     if (T.hasValue())
933       printType(T.getValue());
934   }
935   OS << "#endif\n";
936 
937   OS << "#if defined(__riscv_f)\n";
938   for (int Log2LMUL : Log2LMULs) {
939     auto T = computeType('f', Log2LMUL, "v");
940     if (T.hasValue())
941       printType(T.getValue());
942   }
943   OS << "#endif\n";
944 
945   OS << "#if defined(__riscv_d)\n";
946   for (int Log2LMUL : Log2LMULs) {
947     auto T = computeType('d', Log2LMUL, "v");
948     if (T.hasValue())
949       printType(T.getValue());
950   }
951   OS << "#endif\n\n";
952 
953   // The same extension include in the same arch guard marco.
954   std::stable_sort(Defs.begin(), Defs.end(),
955                    [](const std::unique_ptr<RVVIntrinsic> &A,
956                       const std::unique_ptr<RVVIntrinsic> &B) {
957                      return A->getRISCVExtensions() < B->getRISCVExtensions();
958                    });
959 
960   // Print intrinsic functions with macro
961   emitArchMacroAndBody(Defs, OS, [](raw_ostream &OS, const RVVIntrinsic &Inst) {
962     Inst.emitIntrinsicMacro(OS);
963   });
964 
965   OS << "#define __riscv_v_intrinsic_overloading 1\n";
966 
967   // Print Overloaded APIs
968   OS << "#define __rvv_overloaded static inline "
969         "__attribute__((__always_inline__, __nodebug__, __overloadable__))\n";
970 
971   emitArchMacroAndBody(Defs, OS, [](raw_ostream &OS, const RVVIntrinsic &Inst) {
972     if (!Inst.isMask() && !Inst.hasNoMaskedOverloaded())
973       return;
974     OS << "__rvv_overloaded ";
975     Inst.emitMangledFuncDef(OS);
976   });
977 
978   OS << "\n#ifdef __cplusplus\n";
979   OS << "}\n";
980   OS << "#endif // __riscv_vector\n";
981   OS << "#endif // __RISCV_VECTOR_H\n";
982 }
983 
984 void RVVEmitter::createBuiltins(raw_ostream &OS) {
985   std::vector<std::unique_ptr<RVVIntrinsic>> Defs;
986   createRVVIntrinsics(Defs);
987 
988   OS << "#if defined(TARGET_BUILTIN) && !defined(RISCVV_BUILTIN)\n";
989   OS << "#define RISCVV_BUILTIN(ID, TYPE, ATTRS) TARGET_BUILTIN(ID, TYPE, "
990         "ATTRS, \"experimental-v\")\n";
991   OS << "#endif\n";
992   for (auto &Def : Defs) {
993     OS << "RISCVV_BUILTIN(__builtin_rvv_" << Def->getName() << ",\""
994        << Def->getBuiltinTypeStr() << "\", ";
995     if (!Def->hasSideEffects())
996       OS << "\"n\")\n";
997     else
998       OS << "\"\")\n";
999   }
1000   OS << "#undef RISCVV_BUILTIN\n";
1001 }
1002 
1003 void RVVEmitter::createCodeGen(raw_ostream &OS) {
1004   std::vector<std::unique_ptr<RVVIntrinsic>> Defs;
1005   createRVVIntrinsics(Defs);
1006   // IR name could be empty, use the stable sort preserves the relative order.
1007   std::stable_sort(Defs.begin(), Defs.end(),
1008                    [](const std::unique_ptr<RVVIntrinsic> &A,
1009                       const std::unique_ptr<RVVIntrinsic> &B) {
1010                      return A->getIRName() < B->getIRName();
1011                    });
1012   // Print switch body when the ir name or ManualCodegen changes from previous
1013   // iteration.
1014   RVVIntrinsic *PrevDef = Defs.begin()->get();
1015   for (auto &Def : Defs) {
1016     StringRef CurIRName = Def->getIRName();
1017     if (CurIRName != PrevDef->getIRName() ||
1018         (Def->getManualCodegen() != PrevDef->getManualCodegen())) {
1019       PrevDef->emitCodeGenSwitchBody(OS);
1020     }
1021     PrevDef = Def.get();
1022     OS << "case RISCV::BI__builtin_rvv_" << Def->getName() << ":\n";
1023   }
1024   Defs.back()->emitCodeGenSwitchBody(OS);
1025   OS << "\n";
1026 }
1027 
1028 void RVVEmitter::parsePrototypes(StringRef Prototypes,
1029                                  std::function<void(StringRef)> Handler) {
1030   const StringRef Primaries("evwqom0ztul");
1031   while (!Prototypes.empty()) {
1032     size_t Idx = 0;
1033     // Skip over complex prototype because it could contain primitive type
1034     // character.
1035     if (Prototypes[0] == '(')
1036       Idx = Prototypes.find_first_of(')');
1037     Idx = Prototypes.find_first_of(Primaries, Idx);
1038     assert(Idx != StringRef::npos);
1039     Handler(Prototypes.slice(0, Idx + 1));
1040     Prototypes = Prototypes.drop_front(Idx + 1);
1041   }
1042 }
1043 
1044 std::string RVVEmitter::getSuffixStr(char Type, int Log2LMUL,
1045                                      StringRef Prototypes) {
1046   SmallVector<std::string> SuffixStrs;
1047   parsePrototypes(Prototypes, [&](StringRef Proto) {
1048     auto T = computeType(Type, Log2LMUL, Proto);
1049     SuffixStrs.push_back(T.getValue()->getShortStr());
1050   });
1051   return join(SuffixStrs, "_");
1052 }
1053 
1054 void RVVEmitter::createRVVIntrinsics(
1055     std::vector<std::unique_ptr<RVVIntrinsic>> &Out) {
1056   std::vector<Record *> RV = Records.getAllDerivedDefinitions("RVVBuiltin");
1057   for (auto *R : RV) {
1058     StringRef Name = R->getValueAsString("Name");
1059     StringRef SuffixProto = R->getValueAsString("Suffix");
1060     StringRef MangledName = R->getValueAsString("MangledName");
1061     StringRef Prototypes = R->getValueAsString("Prototype");
1062     StringRef TypeRange = R->getValueAsString("TypeRange");
1063     bool HasMask = R->getValueAsBit("HasMask");
1064     bool HasMaskedOffOperand = R->getValueAsBit("HasMaskedOffOperand");
1065     bool HasVL = R->getValueAsBit("HasVL");
1066     bool HasNoMaskedOverloaded = R->getValueAsBit("HasNoMaskedOverloaded");
1067     bool HasSideEffects = R->getValueAsBit("HasSideEffects");
1068     std::vector<int64_t> Log2LMULList = R->getValueAsListOfInts("Log2LMUL");
1069     StringRef ManualCodegen = R->getValueAsString("ManualCodegen");
1070     StringRef ManualCodegenMask = R->getValueAsString("ManualCodegenMask");
1071     std::vector<int64_t> IntrinsicTypes =
1072         R->getValueAsListOfInts("IntrinsicTypes");
1073     StringRef RequiredExtension = R->getValueAsString("RequiredExtension");
1074     StringRef IRName = R->getValueAsString("IRName");
1075     StringRef IRNameMask = R->getValueAsString("IRNameMask");
1076 
1077     StringRef HeaderCodeStr = R->getValueAsString("HeaderCode");
1078     bool HasAutoDef = HeaderCodeStr.empty();
1079     if (!HeaderCodeStr.empty()) {
1080       HeaderCode += HeaderCodeStr.str();
1081     }
1082     // Parse prototype and create a list of primitive type with transformers
1083     // (operand) in ProtoSeq. ProtoSeq[0] is output operand.
1084     SmallVector<std::string> ProtoSeq;
1085     parsePrototypes(Prototypes, [&ProtoSeq](StringRef Proto) {
1086       ProtoSeq.push_back(Proto.str());
1087     });
1088 
1089     // Compute Builtin types
1090     SmallVector<std::string> ProtoMaskSeq = ProtoSeq;
1091     if (HasMask) {
1092       // If HasMaskedOffOperand, insert result type as first input operand.
1093       if (HasMaskedOffOperand)
1094         ProtoMaskSeq.insert(ProtoMaskSeq.begin() + 1, ProtoSeq[0]);
1095       // If HasMask, insert 'm' as first input operand.
1096       ProtoMaskSeq.insert(ProtoMaskSeq.begin() + 1, "m");
1097     }
1098     // If HasVL, append 'z' to last operand
1099     if (HasVL) {
1100       ProtoSeq.push_back("z");
1101       ProtoMaskSeq.push_back("z");
1102     }
1103 
1104     // Create Intrinsics for each type and LMUL.
1105     for (char I : TypeRange) {
1106       for (int Log2LMUL : Log2LMULList) {
1107         Optional<RVVTypes> Types = computeTypes(I, Log2LMUL, ProtoSeq);
1108         // Ignored to create new intrinsic if there are any illegal types.
1109         if (!Types.hasValue())
1110           continue;
1111 
1112         auto SuffixStr = getSuffixStr(I, Log2LMUL, SuffixProto);
1113         // Create a non-mask intrinsic
1114         Out.push_back(std::make_unique<RVVIntrinsic>(
1115             Name, SuffixStr, MangledName, IRName, HasSideEffects,
1116             /*IsMask=*/false, /*HasMaskedOffOperand=*/false, HasVL,
1117             HasNoMaskedOverloaded, HasAutoDef, ManualCodegen, Types.getValue(),
1118             IntrinsicTypes, RequiredExtension));
1119         if (HasMask) {
1120           // Create a mask intrinsic
1121           Optional<RVVTypes> MaskTypes =
1122               computeTypes(I, Log2LMUL, ProtoMaskSeq);
1123           Out.push_back(std::make_unique<RVVIntrinsic>(
1124               Name, SuffixStr, MangledName, IRNameMask, HasSideEffects,
1125               /*IsMask=*/true, HasMaskedOffOperand, HasVL,
1126               HasNoMaskedOverloaded, HasAutoDef, ManualCodegenMask,
1127               MaskTypes.getValue(), IntrinsicTypes, RequiredExtension));
1128         }
1129       } // end for Log2LMULList
1130     }   // end for TypeRange
1131   }
1132 }
1133 
1134 Optional<RVVTypes>
1135 RVVEmitter::computeTypes(BasicType BT, int Log2LMUL,
1136                          ArrayRef<std::string> PrototypeSeq) {
1137   RVVTypes Types;
1138   for (const std::string &Proto : PrototypeSeq) {
1139     auto T = computeType(BT, Log2LMUL, Proto);
1140     if (!T.hasValue())
1141       return llvm::None;
1142     // Record legal type index
1143     Types.push_back(T.getValue());
1144   }
1145   return Types;
1146 }
1147 
1148 Optional<RVVTypePtr> RVVEmitter::computeType(BasicType BT, int Log2LMUL,
1149                                              StringRef Proto) {
1150   std::string Idx = Twine(Twine(BT) + Twine(Log2LMUL) + Proto).str();
1151   // Search first
1152   auto It = LegalTypes.find(Idx);
1153   if (It != LegalTypes.end())
1154     return &(It->second);
1155   if (IllegalTypes.count(Idx))
1156     return llvm::None;
1157   // Compute type and record the result.
1158   RVVType T(BT, Log2LMUL, Proto);
1159   if (T.isValid()) {
1160     // Record legal type index and value.
1161     LegalTypes.insert({Idx, T});
1162     return &(LegalTypes[Idx]);
1163   }
1164   // Record illegal type index.
1165   IllegalTypes.insert(Idx);
1166   return llvm::None;
1167 }
1168 
1169 void RVVEmitter::emitArchMacroAndBody(
1170     std::vector<std::unique_ptr<RVVIntrinsic>> &Defs, raw_ostream &OS,
1171     std::function<void(raw_ostream &, const RVVIntrinsic &)> PrintBody) {
1172   uint8_t PrevExt = (*Defs.begin())->getRISCVExtensions();
1173   bool NeedEndif = emitExtDefStr(PrevExt, OS);
1174   for (auto &Def : Defs) {
1175     uint8_t CurExt = Def->getRISCVExtensions();
1176     if (CurExt != PrevExt) {
1177       if (NeedEndif)
1178         OS << "#endif\n\n";
1179       NeedEndif = emitExtDefStr(CurExt, OS);
1180       PrevExt = CurExt;
1181     }
1182     if (Def->hasAutoDef())
1183       PrintBody(OS, *Def);
1184   }
1185   if (NeedEndif)
1186     OS << "#endif\n\n";
1187 }
1188 
1189 bool RVVEmitter::emitExtDefStr(uint8_t Extents, raw_ostream &OS) {
1190   if (Extents == RISCVExtension::Basic)
1191     return false;
1192   OS << "#if ";
1193   ListSeparator LS(" && ");
1194   if (Extents & RISCVExtension::F)
1195     OS << LS << "defined(__riscv_f)";
1196   if (Extents & RISCVExtension::D)
1197     OS << LS << "defined(__riscv_d)";
1198   if (Extents & RISCVExtension::Zfh)
1199     OS << LS << "defined(__riscv_zfh)";
1200   if (Extents & RISCVExtension::Zvamo)
1201     OS << LS << "defined(__riscv_zvamo)";
1202   OS << "\n";
1203   return true;
1204 }
1205 
1206 namespace clang {
1207 void EmitRVVHeader(RecordKeeper &Records, raw_ostream &OS) {
1208   RVVEmitter(Records).createHeader(OS);
1209 }
1210 
1211 void EmitRVVBuiltins(RecordKeeper &Records, raw_ostream &OS) {
1212   RVVEmitter(Records).createBuiltins(OS);
1213 }
1214 
1215 void EmitRVVBuiltinCG(RecordKeeper &Records, raw_ostream &OS) {
1216   RVVEmitter(Records).createCodeGen(OS);
1217 }
1218 
1219 } // End namespace clang
1220