1 //===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is responsible for emitting arm_neon.h, which includes
11 // a declaration and definition of each function specified by the ARM NEON
12 // compiler interface. See ARM document DUI0348B.
14 // Each NEON instruction is implemented in terms of 1 or more functions which
15 // are suffixed with the element type of the input vectors. Functions may be
16 // implemented in terms of generic vector operations such as +, *, -, etc. or
17 // by calling a __builtin_-prefixed function which will be handled by clang's
20 // Additional validation code can be generated by this file when runHeader() is
21 // called, rather than the normal run() entry point. A complete set of tests
22 // for Neon intrinsics can be generated by calling the runTests() entry point.
24 //===----------------------------------------------------------------------===//
26 #include "NeonEmitter.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
34 /// ParseTypes - break down a string such as "fQf" into a vector of StringRefs,
35 /// which each StringRef representing a single type declared in the string.
36 /// for "fQf" we would end up with 2 StringRefs, "f", and "Qf", representing
37 /// 2xfloat and 4xfloat respectively.
38 static void ParseTypes(Record *r, std::string &s,
39 SmallVectorImpl<StringRef> &TV) {
40 const char *data = s.data();
43 for (unsigned i = 0, e = s.size(); i != e; ++i, ++len) {
44 if (data[len] == 'P' || data[len] == 'Q' || data[len] == 'U')
56 throw TGError(r->getLoc(),
57 "Unexpected letter: " + std::string(data + len, 1));
60 TV.push_back(StringRef(data, len + 1));
66 /// Widen - Convert a type code into the next wider type. char -> short,
67 /// short -> int, etc.
68 static char Widen(const char t) {
76 default: throw "unhandled type in widen!";
81 /// Narrow - Convert a type code into the next smaller type. short -> char,
82 /// float -> half float, etc.
83 static char Narrow(const char t) {
93 default: throw "unhandled type in narrow!";
98 /// For a particular StringRef, return the base type code, and whether it has
99 /// the quad-vector, polynomial, or unsigned modifiers set.
100 static char ClassifyType(StringRef ty, bool &quad, bool &poly, bool &usgn) {
104 if (ty[off] == 'Q') {
110 if (ty[off] == 'P') {
115 // remember unsigned.
116 if (ty[off] == 'U') {
121 // base type to get the type string for.
125 /// ModType - Transform a type code and its modifiers based on a mod code. The
126 /// mod code definitions may be found at the top of arm_neon.td.
127 static char ModType(const char mod, char type, bool &quad, bool &poly,
128 bool &usgn, bool &scal, bool &cnst, bool &pntr) {
201 /// TypeString - for a modifier and type, generate the name of the typedef for
202 /// that type. QUc -> uint8x8_t.
203 static std::string TypeString(const char mod, StringRef typestr) {
216 // base type to get the type string for.
217 char type = ClassifyType(typestr, quad, poly, usgn);
219 // Based on the modifying character, change the type and width if necessary.
220 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
229 s += poly ? "poly8" : "int8";
232 s += quad ? "x16" : "x8";
235 s += poly ? "poly16" : "int16";
238 s += quad ? "x8" : "x4";
244 s += quad ? "x4" : "x2";
250 s += quad ? "x2" : "x1";
256 s += quad ? "x8" : "x4";
262 s += quad ? "x4" : "x2";
265 throw "unhandled type!";
276 // Append _t, finishing the type string typedef type.
288 /// BuiltinTypeString - for a modifier and type, generate the clang
289 /// BuiltinsARM.def prototype code for the function. See the top of clang's
290 /// Builtins.def for a description of the type strings.
291 static std::string BuiltinTypeString(const char mod, StringRef typestr,
292 ClassKind ck, bool ret) {
305 // base type to get the type string for.
306 char type = ClassifyType(typestr, quad, poly, usgn);
308 // Based on the modifying character, change the type and width if necessary.
309 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
311 // All pointers are void* pointers. Change type to 'v' now.
317 // Treat half-float ('h') types as unsigned short ('s') types.
322 usgn = usgn | poly | ((ck == ClassI || ck == ClassW) && scal && type != 'f');
329 else if (type == 'c')
330 s.push_back('S'); // make chars explicitly signed
332 if (type == 'l') // 64-bit long
344 // Since the return value must be one type, return a vector type of the
345 // appropriate width which we will bitcast. An exception is made for
346 // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
347 // fashion, storing them to a pointer arg.
349 if (mod >= '2' && mod <= '4')
350 return "vv*"; // void result with void* first argument
351 if (mod == 'f' || (ck != ClassB && type == 'f'))
352 return quad ? "V4f" : "V2f";
353 if (ck != ClassB && type == 's')
354 return quad ? "V8s" : "V4s";
355 if (ck != ClassB && type == 'i')
356 return quad ? "V4i" : "V2i";
357 if (ck != ClassB && type == 'l')
358 return quad ? "V2LLi" : "V1LLi";
360 return quad ? "V16Sc" : "V8Sc";
363 // Non-return array types are passed as individual vectors.
365 return quad ? "V16ScV16Sc" : "V8ScV8Sc";
367 return quad ? "V16ScV16ScV16Sc" : "V8ScV8ScV8Sc";
369 return quad ? "V16ScV16ScV16ScV16Sc" : "V8ScV8ScV8ScV8Sc";
371 if (mod == 'f' || (ck != ClassB && type == 'f'))
372 return quad ? "V4f" : "V2f";
373 if (ck != ClassB && type == 's')
374 return quad ? "V8s" : "V4s";
375 if (ck != ClassB && type == 'i')
376 return quad ? "V4i" : "V2i";
377 if (ck != ClassB && type == 'l')
378 return quad ? "V2LLi" : "V1LLi";
380 return quad ? "V16Sc" : "V8Sc";
383 /// MangleName - Append a type or width suffix to a base neon function name,
384 /// and insert a 'q' in the appropriate location if the operation works on
385 /// 128b rather than 64b. E.g. turn "vst2_lane" into "vst2q_lane_f32", etc.
386 static std::string MangleName(const std::string &name, StringRef typestr,
388 if (name == "vcvt_f32_f16")
394 char type = ClassifyType(typestr, quad, poly, usgn);
396 std::string s = name;
401 case ClassS: s += poly ? "_p8" : usgn ? "_u8" : "_s8"; break;
402 case ClassI: s += "_i8"; break;
403 case ClassW: s += "_8"; break;
409 case ClassS: s += poly ? "_p16" : usgn ? "_u16" : "_s16"; break;
410 case ClassI: s += "_i16"; break;
411 case ClassW: s += "_16"; break;
417 case ClassS: s += usgn ? "_u32" : "_s32"; break;
418 case ClassI: s += "_i32"; break;
419 case ClassW: s += "_32"; break;
425 case ClassS: s += usgn ? "_u64" : "_s64"; break;
426 case ClassI: s += "_i64"; break;
427 case ClassW: s += "_64"; break;
434 case ClassI: s += "_f16"; break;
435 case ClassW: s += "_16"; break;
442 case ClassI: s += "_f32"; break;
443 case ClassW: s += "_32"; break;
448 throw "unhandled type!";
454 // Insert a 'q' before the first '_' character so that it ends up before
455 // _lane or _n on vector-scalar operations.
457 size_t pos = s.find('_');
458 s = s.insert(pos, "q");
463 // Generate the string "(argtype a, argtype b, ...)"
464 static std::string GenArgs(const std::string &proto, StringRef typestr) {
465 bool define = proto.find('i') != std::string::npos;
471 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
473 // Immediate macro arguments are used directly instead of being assigned
474 // to local temporaries; prepend an underscore prefix to make their
475 // names consistent with the local temporaries.
479 s += TypeString(proto[i], typestr) + " __";
490 // Macro arguments are not type-checked like inline function arguments, so
491 // assign them to local temporaries to get the right type checking.
492 static std::string GenMacroLocals(const std::string &proto, StringRef typestr) {
496 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
497 // Do not create a temporary for an immediate argument.
498 // That would defeat the whole point of using a macro!
499 if (proto[i] == 'i') continue;
501 s += TypeString(proto[i], typestr) + " __";
512 // Use the vmovl builtin to sign-extend or zero-extend a vector.
513 static std::string Extend(StringRef typestr, const std::string &a) {
515 s = MangleName("vmovl", typestr, ClassS);
520 static std::string Duplicate(unsigned nElts, StringRef typestr,
521 const std::string &a) {
524 s = "(" + TypeString('d', typestr) + "){ ";
525 for (unsigned i = 0; i != nElts; ++i) {
535 static std::string SplatLane(unsigned nElts, const std::string &vec,
536 const std::string &lane) {
537 std::string s = "__builtin_shufflevector(" + vec + ", " + vec;
538 for (unsigned i = 0; i < nElts; ++i)
544 static unsigned GetNumElements(StringRef typestr, bool &quad) {
547 char type = ClassifyType(typestr, quad, dummy, dummy);
550 case 'c': nElts = 8; break;
551 case 's': nElts = 4; break;
552 case 'i': nElts = 2; break;
553 case 'l': nElts = 1; break;
554 case 'h': nElts = 4; break;
555 case 'f': nElts = 2; break;
557 throw "unhandled type!";
560 if (quad) nElts <<= 1;
564 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
565 static std::string GenOpString(OpKind op, const std::string &proto,
568 unsigned nElts = GetNumElements(typestr, quad);
570 // If this builtin takes an immediate argument, we need to #define it rather
571 // than use a standard declaration, so that SemaChecking can range check
572 // the immediate passed by the user.
573 bool define = proto.find('i') != std::string::npos;
575 std::string ts = TypeString(proto[0], typestr);
577 if (op == OpHi || op == OpLo) {
578 s = "union { " + ts + " r; double d; } u; u.d = ";
579 } else if (!define) {
588 s += Extend(typestr, "__a") + " + " + Extend(typestr, "__b") + ";";
591 s += "__a + " + Extend(typestr, "__b") + ";";
597 s += Extend(typestr, "__a") + " - " + Extend(typestr, "__b") + ";";
600 s += "__a - " + Extend(typestr, "__b") + ";";
603 s += "__a * " + Duplicate(nElts, typestr, "__b") + ";";
606 s += "__a * " + SplatLane(nElts, "__b", "__c") + ";";
612 s += Extend(typestr, "__a") + " * " +
613 Extend(typestr, Duplicate(nElts << (int)quad, typestr, "__b")) + ";";
616 s += Extend(typestr, "__a") + " * " +
617 Extend(typestr, SplatLane(nElts, "__b", "__c")) + ";";
620 s += Extend(typestr, "__a") + " * " + Extend(typestr, "__b") + ";";
623 s += "__a + (__b * " + Duplicate(nElts, typestr, "__c") + ");";
626 s += "__a + (__b * " + SplatLane(nElts, "__c", "__d") + ");";
629 s += "__a + (__b * __c);";
632 s += "__a + (" + Extend(typestr, "__b") + " * " +
633 Extend(typestr, Duplicate(nElts, typestr, "__c")) + ");";
636 s += "__a + (" + Extend(typestr, "__b") + " * " +
637 Extend(typestr, SplatLane(nElts, "__c", "__d")) + ");";
640 s += "__a + (" + Extend(typestr, "__b") + " * " +
641 Extend(typestr, "__c") + ");";
644 s += "__a - (__b * " + Duplicate(nElts, typestr, "__c") + ");";
647 s += "__a - (__b * " + SplatLane(nElts, "__c", "__d") + ");";
650 s += "__a - (__b * __c);";
653 s += "__a - (" + Extend(typestr, "__b") + " * " +
654 Extend(typestr, Duplicate(nElts, typestr, "__c")) + ");";
657 s += "__a - (" + Extend(typestr, "__b") + " * " +
658 Extend(typestr, SplatLane(nElts, "__c", "__d")) + ");";
661 s += "__a - (" + Extend(typestr, "__b") + " * " +
662 Extend(typestr, "__c") + ");";
665 s += MangleName("vqdmull", typestr, ClassS) + "(__a, " +
666 SplatLane(nElts, "__b", "__c") + ");";
669 s += MangleName("vqdmlal", typestr, ClassS) + "(__a, __b, " +
670 SplatLane(nElts, "__c", "__d") + ");";
673 s += MangleName("vqdmlsl", typestr, ClassS) + "(__a, __b, " +
674 SplatLane(nElts, "__c", "__d") + ");";
677 s += MangleName("vqdmulh", typestr, ClassS) + "(__a, " +
678 SplatLane(nElts, "__b", "__c") + ");";
681 s += MangleName("vqrdmulh", typestr, ClassS) + "(__a, " +
682 SplatLane(nElts, "__b", "__c") + ");";
685 s += "(" + ts + ")(__a == __b);";
688 s += "(" + ts + ")(__a >= __b);";
691 s += "(" + ts + ")(__a <= __b);";
694 s += "(" + ts + ")(__a > __b);";
697 s += "(" + ts + ")(__a < __b);";
721 s += "(" + ts + ")__a;";
724 s += "(" + ts + ")__builtin_shufflevector((int64x1_t)__a";
725 s += ", (int64x1_t)__b, 0, 1);";
728 s += "(((float64x2_t)__a)[1]);";
731 s += "(((float64x2_t)__a)[0]);";
734 s += Duplicate(nElts, typestr, "__a") + ";";
737 s += SplatLane(nElts, "__a", "__b") + ";";
740 // ((0 & 1) | (~0 & 2))
742 ts = TypeString(proto[1], typestr);
743 s += "((__a & (" + ts + ")__b) | ";
744 s += "(~__a & (" + ts + ")__c));";
747 s += "__builtin_shufflevector(__a, __a";
748 for (unsigned i = 2; i <= nElts; i += 2)
749 for (unsigned j = 0; j != 2; ++j)
750 s += ", " + utostr(i - j - 1);
754 unsigned WordElts = nElts >> (1 + (int)quad);
755 s += "__builtin_shufflevector(__a, __a";
756 for (unsigned i = WordElts; i <= nElts; i += WordElts)
757 for (unsigned j = 0; j != WordElts; ++j)
758 s += ", " + utostr(i - j - 1);
763 unsigned DblWordElts = nElts >> (int)quad;
764 s += "__builtin_shufflevector(__a, __a";
765 for (unsigned i = DblWordElts; i <= nElts; i += DblWordElts)
766 for (unsigned j = 0; j != DblWordElts; ++j)
767 s += ", " + utostr(i - j - 1);
772 std::string abd = MangleName("vabd", typestr, ClassS) + "(__a, __b)";
773 if (typestr[0] != 'U') {
774 // vabd results are always unsigned and must be zero-extended.
775 std::string utype = "U" + typestr.str();
776 s += "(" + TypeString(proto[0], typestr) + ")";
777 abd = "(" + TypeString('d', utype) + ")" + abd;
778 s += Extend(utype, abd) + ";";
780 s += Extend(typestr, abd) + ";";
785 s += "__a + " + MangleName("vabd", typestr, ClassS) + "(__b, __c);";
789 std::string abd = MangleName("vabd", typestr, ClassS) + "(__b, __c)";
790 if (typestr[0] != 'U') {
791 // vabd results are always unsigned and must be zero-extended.
792 std::string utype = "U" + typestr.str();
793 s += "(" + TypeString(proto[0], typestr) + ")";
794 abd = "(" + TypeString('d', utype) + ")" + abd;
795 s += Extend(utype, abd) + ";";
797 s += Extend(typestr, abd) + ";";
802 throw "unknown OpKind!";
805 if (op == OpHi || op == OpLo) {
813 static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
814 unsigned mod = proto[0];
817 if (mod == 'v' || mod == 'f')
827 // Base type to get the type string for.
828 char type = ClassifyType(typestr, quad, poly, usgn);
830 // Based on the modifying character, change the type and width if necessary.
831 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
835 if (quad && proto[1] != 'g')
858 throw "unhandled type!";
864 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
865 static std::string GenBuiltin(const std::string &name, const std::string &proto,
866 StringRef typestr, ClassKind ck) {
869 // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
870 // sret-like argument.
871 bool sret = (proto[0] >= '2' && proto[0] <= '4');
873 // If this builtin takes an immediate argument, we need to #define it rather
874 // than use a standard declaration, so that SemaChecking can range check
875 // the immediate passed by the user.
876 bool define = proto.find('i') != std::string::npos;
878 // Check if the prototype has a scalar operand with the type of the vector
879 // elements. If not, bitcasting the args will take care of arg checking.
880 // The actual signedness etc. will be taken care of with special enums.
881 if (proto.find('s') == std::string::npos)
884 if (proto[0] != 'v') {
885 std::string ts = TypeString(proto[0], typestr);
895 s += "return (" + ts + ")";
899 bool splat = proto.find('a') != std::string::npos;
901 s += "__builtin_neon_";
903 // Call the non-splat builtin: chop off the "_n" suffix from the name.
904 std::string vname(name, 0, name.size()-2);
905 s += MangleName(vname, typestr, ck);
907 s += MangleName(name, typestr, ck);
911 // Pass the address of the return variable as the first argument to sret-like
917 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
918 std::string args = std::string(&arg, 1);
920 // Use the local temporaries instead of the macro arguments.
923 bool argQuad = false;
924 bool argPoly = false;
925 bool argUsgn = false;
926 bool argScalar = false;
928 char argType = ClassifyType(typestr, argQuad, argPoly, argUsgn);
929 argType = ModType(proto[i], argType, argQuad, argPoly, argUsgn, argScalar,
932 // Handle multiple-vector values specially, emitting each subvector as an
933 // argument to the __builtin.
934 if (proto[i] >= '2' && proto[i] <= '4') {
935 // Check if an explicit cast is needed.
936 if (argType != 'c' || argPoly || argUsgn)
937 args = (argQuad ? "(int8x16_t)" : "(int8x8_t)") + args;
939 for (unsigned vi = 0, ve = proto[i] - '0'; vi != ve; ++vi) {
940 s += args + ".val[" + utostr(vi) + "]";
950 if (splat && (i + 1) == e)
951 args = Duplicate(GetNumElements(typestr, argQuad), typestr, args);
953 // Check if an explicit cast is needed.
954 if ((splat || !argScalar) &&
955 ((ck == ClassB && argType != 'c') || argPoly || argUsgn)) {
956 std::string argTypeStr = "c";
958 argTypeStr = argType;
960 argTypeStr = "Q" + argTypeStr;
961 args = "(" + TypeString('d', argTypeStr) + ")" + args;
969 // Extra constant integer to hold type class enum for this function, e.g. s8
971 s += ", " + utostr(GetNeonEnum(proto, typestr));
975 if (proto[0] != 'v' && sret) {
984 static std::string GenBuiltinDef(const std::string &name,
985 const std::string &proto,
986 StringRef typestr, ClassKind ck) {
987 std::string s("BUILTIN(__builtin_neon_");
989 // If all types are the same size, bitcasting the args will take care
990 // of arg checking. The actual signedness etc. will be taken care of with
992 if (proto.find('s') == std::string::npos)
995 s += MangleName(name, typestr, ck);
998 for (unsigned i = 0, e = proto.size(); i != e; ++i)
999 s += BuiltinTypeString(proto[i], typestr, ck, i == 0);
1001 // Extra constant integer to hold type class enum for this function, e.g. s8
1009 static std::string GenIntrinsic(const std::string &name,
1010 const std::string &proto,
1011 StringRef outTypeStr, StringRef inTypeStr,
1012 OpKind kind, ClassKind classKind) {
1013 assert(!proto.empty() && "");
1014 bool define = proto.find('i') != std::string::npos;
1017 // static always inline + return type
1021 s += "__ai " + TypeString(proto[0], outTypeStr) + " ";
1023 // Function name with type suffix
1024 std::string mangledName = MangleName(name, outTypeStr, ClassS);
1025 if (outTypeStr != inTypeStr) {
1026 // If the input type is different (e.g., for vreinterpret), append a suffix
1027 // for the input type. String off a "Q" (quad) prefix so that MangleName
1028 // does not insert another "q" in the name.
1029 unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1030 StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1031 mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1035 // Function arguments
1036 s += GenArgs(proto, inTypeStr);
1040 s += " __extension__ ({ \\\n ";
1041 s += GenMacroLocals(proto, inTypeStr);
1047 s += GenOpString(kind, proto, outTypeStr);
1049 s += GenBuiltin(name, proto, outTypeStr, classKind);
1058 /// run - Read the records in arm_neon.td and output arm_neon.h. arm_neon.h
1059 /// is comprised of type definitions and function declarations.
1060 void NeonEmitter::run(raw_ostream &OS) {
1062 "/*===---- arm_neon.h - ARM Neon intrinsics ------------------------------"
1065 " * Permission is hereby granted, free of charge, to any person obtaining "
1067 " * of this software and associated documentation files (the \"Software\"),"
1069 " * in the Software without restriction, including without limitation the "
1071 " * to use, copy, modify, merge, publish, distribute, sublicense, "
1073 " * copies of the Software, and to permit persons to whom the Software is\n"
1074 " * furnished to do so, subject to the following conditions:\n"
1076 " * The above copyright notice and this permission notice shall be "
1078 " * all copies or substantial portions of the Software.\n"
1080 " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
1082 " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
1083 "MERCHANTABILITY,\n"
1084 " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
1086 " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
1088 " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
1090 " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
1092 " * THE SOFTWARE.\n"
1094 " *===--------------------------------------------------------------------"
1098 OS << "#ifndef __ARM_NEON_H\n";
1099 OS << "#define __ARM_NEON_H\n\n";
1101 OS << "#ifndef __ARM_NEON__\n";
1102 OS << "#error \"NEON support not enabled\"\n";
1105 OS << "#include <stdint.h>\n\n";
1107 // Emit NEON-specific scalar typedefs.
1108 OS << "typedef float float32_t;\n";
1109 OS << "typedef int8_t poly8_t;\n";
1110 OS << "typedef int16_t poly16_t;\n";
1111 OS << "typedef uint16_t float16_t;\n";
1113 // Emit Neon vector typedefs.
1114 std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
1115 SmallVector<StringRef, 24> TDTypeVec;
1116 ParseTypes(0, TypedefTypes, TDTypeVec);
1118 // Emit vector typedefs.
1119 for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1120 bool dummy, quad = false, poly = false;
1121 (void) ClassifyType(TDTypeVec[i], quad, poly, dummy);
1123 OS << "typedef __attribute__((neon_polyvector_type(";
1125 OS << "typedef __attribute__((neon_vector_type(";
1127 unsigned nElts = GetNumElements(TDTypeVec[i], quad);
1128 OS << utostr(nElts) << "))) ";
1132 OS << TypeString('s', TDTypeVec[i]);
1133 OS << " " << TypeString('d', TDTypeVec[i]) << ";\n";
1136 OS << "typedef __attribute__((__vector_size__(8))) "
1137 "double float64x1_t;\n";
1138 OS << "typedef __attribute__((__vector_size__(16))) "
1139 "double float64x2_t;\n";
1142 // Emit struct typedefs.
1143 for (unsigned vi = 2; vi != 5; ++vi) {
1144 for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1145 std::string ts = TypeString('d', TDTypeVec[i]);
1146 std::string vs = TypeString('0' + vi, TDTypeVec[i]);
1147 OS << "typedef struct " << vs << " {\n";
1148 OS << " " << ts << " val";
1149 OS << "[" << utostr(vi) << "]";
1151 OS << vs << ";\n\n";
1155 OS << "#define __ai static __attribute__((__always_inline__))\n\n";
1157 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1159 // Emit vmovl and vabd intrinsics first so they can be used by other
1160 // intrinsics. (Some of the saturating multiply instructions are also
1161 // used to implement the corresponding "_lane" variants, but tablegen
1162 // sorts the records into alphabetical order so that the "_lane" variants
1163 // come after the intrinsics they use.)
1164 emitIntrinsic(OS, Records.getDef("VMOVL"));
1165 emitIntrinsic(OS, Records.getDef("VABD"));
1167 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1169 if (R->getName() != "VMOVL" && R->getName() != "VABD")
1170 emitIntrinsic(OS, R);
1173 OS << "#undef __ai\n\n";
1174 OS << "#endif /* __ARM_NEON_H */\n";
1177 /// emitIntrinsic - Write out the arm_neon.h header file definitions for the
1178 /// intrinsics specified by record R.
1179 void NeonEmitter::emitIntrinsic(raw_ostream &OS, Record *R) {
1180 std::string name = R->getValueAsString("Name");
1181 std::string Proto = R->getValueAsString("Prototype");
1182 std::string Types = R->getValueAsString("Types");
1184 SmallVector<StringRef, 16> TypeVec;
1185 ParseTypes(R, Types, TypeVec);
1187 OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1189 ClassKind classKind = ClassNone;
1190 if (R->getSuperClasses().size() >= 2)
1191 classKind = ClassMap[R->getSuperClasses()[1]];
1192 if (classKind == ClassNone && kind == OpNone)
1193 throw TGError(R->getLoc(), "Builtin has no class kind");
1195 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1196 if (kind == OpReinterpret) {
1197 bool outQuad = false;
1199 (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1200 for (unsigned srcti = 0, srcte = TypeVec.size();
1201 srcti != srcte; ++srcti) {
1202 bool inQuad = false;
1203 (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1204 if (srcti == ti || inQuad != outQuad)
1206 OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[srcti],
1210 OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[ti],
1217 static unsigned RangeFromType(const char mod, StringRef typestr) {
1218 // base type to get the type string for.
1219 bool quad = false, dummy = false;
1220 char type = ClassifyType(typestr, quad, dummy, dummy);
1221 type = ModType(mod, type, quad, dummy, dummy, dummy, dummy, dummy);
1225 return (8 << (int)quad) - 1;
1228 return (4 << (int)quad) - 1;
1231 return (2 << (int)quad) - 1;
1233 return (1 << (int)quad) - 1;
1235 throw "unhandled type!";
1238 assert(0 && "unreachable");
1242 /// runHeader - Emit a file with sections defining:
1243 /// 1. the NEON section of BuiltinsARM.def.
1244 /// 2. the SemaChecking code for the type overload checking.
1245 /// 3. the SemaChecking code for validation of intrinsic immedate arguments.
1246 void NeonEmitter::runHeader(raw_ostream &OS) {
1247 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1249 StringMap<OpKind> EmittedMap;
1251 // Generate BuiltinsARM.def for NEON
1252 OS << "#ifdef GET_NEON_BUILTINS\n";
1253 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1255 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1259 std::string Proto = R->getValueAsString("Prototype");
1261 // Functions with 'a' (the splat code) in the type prototype should not get
1262 // their own builtin as they use the non-splat variant.
1263 if (Proto.find('a') != std::string::npos)
1266 std::string Types = R->getValueAsString("Types");
1267 SmallVector<StringRef, 16> TypeVec;
1268 ParseTypes(R, Types, TypeVec);
1270 if (R->getSuperClasses().size() < 2)
1271 throw TGError(R->getLoc(), "Builtin has no class kind");
1273 std::string name = R->getValueAsString("Name");
1274 ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1276 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1277 // Generate the BuiltinsARM.def declaration for this builtin, ensuring
1278 // that each unique BUILTIN() macro appears only once in the output
1280 std::string bd = GenBuiltinDef(name, Proto, TypeVec[ti], ck);
1281 if (EmittedMap.count(bd))
1284 EmittedMap[bd] = OpNone;
1290 // Generate the overloaded type checking code for SemaChecking.cpp
1291 OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1292 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1294 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1298 std::string Proto = R->getValueAsString("Prototype");
1299 std::string Types = R->getValueAsString("Types");
1300 std::string name = R->getValueAsString("Name");
1302 // Functions with 'a' (the splat code) in the type prototype should not get
1303 // their own builtin as they use the non-splat variant.
1304 if (Proto.find('a') != std::string::npos)
1307 // Functions which have a scalar argument cannot be overloaded, no need to
1308 // check them if we are emitting the type checking code.
1309 if (Proto.find('s') != std::string::npos)
1312 SmallVector<StringRef, 16> TypeVec;
1313 ParseTypes(R, Types, TypeVec);
1315 if (R->getSuperClasses().size() < 2)
1316 throw TGError(R->getLoc(), "Builtin has no class kind");
1318 int si = -1, qi = -1;
1319 unsigned mask = 0, qmask = 0;
1320 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1321 // Generate the switch case(s) for this builtin for the type validation.
1322 bool quad = false, poly = false, usgn = false;
1323 (void) ClassifyType(TypeVec[ti], quad, poly, usgn);
1327 qmask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1330 mask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1334 OS << "case ARM::BI__builtin_neon_"
1335 << MangleName(name, TypeVec[si], ClassB)
1336 << ": mask = " << "0x" << utohexstr(mask) << "; break;\n";
1338 OS << "case ARM::BI__builtin_neon_"
1339 << MangleName(name, TypeVec[qi], ClassB)
1340 << ": mask = " << "0x" << utohexstr(qmask) << "; break;\n";
1344 // Generate the intrinsic range checking code for shift/lane immediates.
1345 OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
1346 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1349 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1353 std::string name = R->getValueAsString("Name");
1354 std::string Proto = R->getValueAsString("Prototype");
1355 std::string Types = R->getValueAsString("Types");
1357 // Functions with 'a' (the splat code) in the type prototype should not get
1358 // their own builtin as they use the non-splat variant.
1359 if (Proto.find('a') != std::string::npos)
1362 // Functions which do not have an immediate do not need to have range
1363 // checking code emitted.
1364 size_t immPos = Proto.find('i');
1365 if (immPos == std::string::npos)
1368 SmallVector<StringRef, 16> TypeVec;
1369 ParseTypes(R, Types, TypeVec);
1371 if (R->getSuperClasses().size() < 2)
1372 throw TGError(R->getLoc(), "Builtin has no class kind");
1374 ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1376 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1377 std::string namestr, shiftstr, rangestr;
1379 // Builtins which are overloaded by type will need to have their upper
1380 // bound computed at Sema time based on the type constant.
1381 if (Proto.find('s') == std::string::npos) {
1383 if (R->getValueAsBit("isShift")) {
1384 shiftstr = ", true";
1386 // Right shifts have an 'r' in the name, left shifts do not.
1387 if (name.find('r') != std::string::npos)
1388 rangestr = "l = 1; ";
1390 rangestr += "u = RFT(TV" + shiftstr + ")";
1392 // The immediate generally refers to a lane in the preceding argument.
1393 assert(immPos > 0 && "unexpected immediate operand");
1394 rangestr = "u = " + utostr(RangeFromType(Proto[immPos-1], TypeVec[ti]));
1396 // Make sure cases appear only once by uniquing them in a string map.
1397 namestr = MangleName(name, TypeVec[ti], ck);
1398 if (EmittedMap.count(namestr))
1400 EmittedMap[namestr] = OpNone;
1402 // Calculate the index of the immediate that should be range checked.
1403 unsigned immidx = 0;
1405 // Builtins that return a struct of multiple vectors have an extra
1406 // leading arg for the struct return.
1407 if (Proto[0] >= '2' && Proto[0] <= '4')
1410 // Add one to the index for each argument until we reach the immediate
1411 // to be checked. Structs of vectors are passed as multiple arguments.
1412 for (unsigned ii = 1, ie = Proto.size(); ii != ie; ++ii) {
1413 switch (Proto[ii]) {
1414 default: immidx += 1; break;
1415 case '2': immidx += 2; break;
1416 case '3': immidx += 3; break;
1417 case '4': immidx += 4; break;
1418 case 'i': ie = ii + 1; break;
1421 OS << "case ARM::BI__builtin_neon_" << MangleName(name, TypeVec[ti], ck)
1422 << ": i = " << immidx << "; " << rangestr << "; break;\n";
1428 /// GenTest - Write out a test for the intrinsic specified by the name and
1429 /// type strings, including the embedded patterns for FileCheck to match.
1430 static std::string GenTest(const std::string &name,
1431 const std::string &proto,
1432 StringRef outTypeStr, StringRef inTypeStr,
1434 assert(!proto.empty() && "");
1437 // Function name with type suffix
1438 std::string mangledName = MangleName(name, outTypeStr, ClassS);
1439 if (outTypeStr != inTypeStr) {
1440 // If the input type is different (e.g., for vreinterpret), append a suffix
1441 // for the input type. String off a "Q" (quad) prefix so that MangleName
1442 // does not insert another "q" in the name.
1443 unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1444 StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1445 mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1448 // Emit the FileCheck patterns.
1449 s += "// CHECK: test_" + mangledName + "\n";
1450 // s += "// CHECK: \n"; // FIXME: + expected instruction opcode.
1452 // Emit the start of the test function.
1453 s += TypeString(proto[0], outTypeStr) + " test_" + mangledName + "(";
1456 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1457 // Do not create arguments for values that must be immediate constants.
1458 if (proto[i] == 'i')
1460 s += comma + TypeString(proto[i], inTypeStr) + " ";
1466 if (proto[0] != 'v')
1468 s += mangledName + "(";
1470 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1471 if (proto[i] == 'i') {
1472 // For immediate operands, test the maximum value.
1476 // The immediate generally refers to a lane in the preceding argument.
1477 s += utostr(RangeFromType(proto[i-1], inTypeStr));
1488 /// runTests - Write out a complete set of tests for all of the Neon
1490 void NeonEmitter::runTests(raw_ostream &OS) {
1492 "// RUN: %clang_cc1 -triple thumbv7-apple-darwin \\\n"
1493 "// RUN: -target-cpu cortex-a8 -ffreestanding -S -o - %s | FileCheck %s\n"
1495 "#include <arm_neon.h>\n"
1498 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1499 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1501 std::string name = R->getValueAsString("Name");
1502 std::string Proto = R->getValueAsString("Prototype");
1503 std::string Types = R->getValueAsString("Types");
1504 bool isShift = R->getValueAsBit("isShift");
1506 SmallVector<StringRef, 16> TypeVec;
1507 ParseTypes(R, Types, TypeVec);
1509 OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1510 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1511 if (kind == OpReinterpret) {
1512 bool outQuad = false;
1514 (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1515 for (unsigned srcti = 0, srcte = TypeVec.size();
1516 srcti != srcte; ++srcti) {
1517 bool inQuad = false;
1518 (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1519 if (srcti == ti || inQuad != outQuad)
1521 OS << GenTest(name, Proto, TypeVec[ti], TypeVec[srcti], isShift);
1524 OS << GenTest(name, Proto, TypeVec[ti], TypeVec[ti], isShift);