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) {
78 default: throw "unhandled type in widen!";
83 /// Narrow - Convert a type code into the next smaller type. short -> char,
84 /// float -> half float, etc.
85 static char Narrow(const char t) {
95 default: throw "unhandled type in narrow!";
100 /// For a particular StringRef, return the base type code, and whether it has
101 /// the quad-vector, polynomial, or unsigned modifiers set.
102 static char ClassifyType(StringRef ty, bool &quad, bool &poly, bool &usgn) {
106 if (ty[off] == 'Q') {
112 if (ty[off] == 'P') {
117 // remember unsigned.
118 if (ty[off] == 'U') {
123 // base type to get the type string for.
127 /// ModType - Transform a type code and its modifiers based on a mod code. The
128 /// mod code definitions may be found at the top of arm_neon.td.
129 static char ModType(const char mod, char type, bool &quad, bool &poly,
130 bool &usgn, bool &scal, bool &cnst, bool &pntr) {
203 /// TypeString - for a modifier and type, generate the name of the typedef for
204 /// that type. QUc -> uint8x8_t.
205 static std::string TypeString(const char mod, StringRef typestr) {
218 // base type to get the type string for.
219 char type = ClassifyType(typestr, quad, poly, usgn);
221 // Based on the modifying character, change the type and width if necessary.
222 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
231 s += poly ? "poly8" : "int8";
234 s += quad ? "x16" : "x8";
237 s += poly ? "poly16" : "int16";
240 s += quad ? "x8" : "x4";
246 s += quad ? "x4" : "x2";
252 s += quad ? "x2" : "x1";
258 s += quad ? "x8" : "x4";
264 s += quad ? "x4" : "x2";
267 throw "unhandled type!";
278 // Append _t, finishing the type string typedef type.
290 /// BuiltinTypeString - for a modifier and type, generate the clang
291 /// BuiltinsARM.def prototype code for the function. See the top of clang's
292 /// Builtins.def for a description of the type strings.
293 static std::string BuiltinTypeString(const char mod, StringRef typestr,
294 ClassKind ck, bool ret) {
307 // base type to get the type string for.
308 char type = ClassifyType(typestr, quad, poly, usgn);
310 // Based on the modifying character, change the type and width if necessary.
311 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
313 // All pointers are void* pointers. Change type to 'v' now.
319 // Treat half-float ('h') types as unsigned short ('s') types.
324 usgn = usgn | poly | ((ck == ClassI || ck == ClassW) && scal && type != 'f');
331 else if (type == 'c')
332 s.push_back('S'); // make chars explicitly signed
334 if (type == 'l') // 64-bit long
346 // Since the return value must be one type, return a vector type of the
347 // appropriate width which we will bitcast. An exception is made for
348 // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
349 // fashion, storing them to a pointer arg.
351 if (mod >= '2' && mod <= '4')
352 return "vv*"; // void result with void* first argument
353 if (mod == 'f' || (ck != ClassB && type == 'f'))
354 return quad ? "V4f" : "V2f";
355 if (ck != ClassB && type == 's')
356 return quad ? "V8s" : "V4s";
357 if (ck != ClassB && type == 'i')
358 return quad ? "V4i" : "V2i";
359 if (ck != ClassB && type == 'l')
360 return quad ? "V2LLi" : "V1LLi";
362 return quad ? "V16Sc" : "V8Sc";
365 // Non-return array types are passed as individual vectors.
367 return quad ? "V16ScV16Sc" : "V8ScV8Sc";
369 return quad ? "V16ScV16ScV16Sc" : "V8ScV8ScV8Sc";
371 return quad ? "V16ScV16ScV16ScV16Sc" : "V8ScV8ScV8ScV8Sc";
373 if (mod == 'f' || (ck != ClassB && type == 'f'))
374 return quad ? "V4f" : "V2f";
375 if (ck != ClassB && type == 's')
376 return quad ? "V8s" : "V4s";
377 if (ck != ClassB && type == 'i')
378 return quad ? "V4i" : "V2i";
379 if (ck != ClassB && type == 'l')
380 return quad ? "V2LLi" : "V1LLi";
382 return quad ? "V16Sc" : "V8Sc";
385 /// MangleName - Append a type or width suffix to a base neon function name,
386 /// and insert a 'q' in the appropriate location if the operation works on
387 /// 128b rather than 64b. E.g. turn "vst2_lane" into "vst2q_lane_f32", etc.
388 static std::string MangleName(const std::string &name, StringRef typestr,
390 if (name == "vcvt_f32_f16")
396 char type = ClassifyType(typestr, quad, poly, usgn);
398 std::string s = name;
403 case ClassS: s += poly ? "_p8" : usgn ? "_u8" : "_s8"; break;
404 case ClassI: s += "_i8"; break;
405 case ClassW: s += "_8"; break;
411 case ClassS: s += poly ? "_p16" : usgn ? "_u16" : "_s16"; break;
412 case ClassI: s += "_i16"; break;
413 case ClassW: s += "_16"; break;
419 case ClassS: s += usgn ? "_u32" : "_s32"; break;
420 case ClassI: s += "_i32"; break;
421 case ClassW: s += "_32"; break;
427 case ClassS: s += usgn ? "_u64" : "_s64"; break;
428 case ClassI: s += "_i64"; break;
429 case ClassW: s += "_64"; break;
436 case ClassI: s += "_f16"; break;
437 case ClassW: s += "_16"; break;
444 case ClassI: s += "_f32"; break;
445 case ClassW: s += "_32"; break;
450 throw "unhandled type!";
456 // Insert a 'q' before the first '_' character so that it ends up before
457 // _lane or _n on vector-scalar operations.
459 size_t pos = s.find('_');
460 s = s.insert(pos, "q");
465 // Generate the string "(argtype a, argtype b, ...)"
466 static std::string GenArgs(const std::string &proto, StringRef typestr) {
467 bool define = proto.find('i') != std::string::npos;
473 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
475 // Immediate macro arguments are used directly instead of being assigned
476 // to local temporaries; prepend an underscore prefix to make their
477 // names consistent with the local temporaries.
481 s += TypeString(proto[i], typestr) + " __";
492 // Macro arguments are not type-checked like inline function arguments, so
493 // assign them to local temporaries to get the right type checking.
494 static std::string GenMacroLocals(const std::string &proto, StringRef typestr) {
498 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
499 // Do not create a temporary for an immediate argument.
500 // That would defeat the whole point of using a macro!
501 if (proto[i] == 'i') continue;
503 s += TypeString(proto[i], typestr) + " __";
514 // Use the vmovl builtin to sign-extend or zero-extend a vector.
515 static std::string Extend(StringRef typestr, const std::string &a) {
517 s = MangleName("vmovl", typestr, ClassS);
522 static std::string Duplicate(unsigned nElts, StringRef typestr,
523 const std::string &a) {
526 s = "(" + TypeString('d', typestr) + "){ ";
527 for (unsigned i = 0; i != nElts; ++i) {
537 static std::string SplatLane(unsigned nElts, const std::string &vec,
538 const std::string &lane) {
539 std::string s = "__builtin_shufflevector(" + vec + ", " + vec;
540 for (unsigned i = 0; i < nElts; ++i)
546 static unsigned GetNumElements(StringRef typestr, bool &quad) {
549 char type = ClassifyType(typestr, quad, dummy, dummy);
552 case 'c': nElts = 8; break;
553 case 's': nElts = 4; break;
554 case 'i': nElts = 2; break;
555 case 'l': nElts = 1; break;
556 case 'h': nElts = 4; break;
557 case 'f': nElts = 2; break;
559 throw "unhandled type!";
562 if (quad) nElts <<= 1;
566 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
567 static std::string GenOpString(OpKind op, const std::string &proto,
570 unsigned nElts = GetNumElements(typestr, quad);
572 // If this builtin takes an immediate argument, we need to #define it rather
573 // than use a standard declaration, so that SemaChecking can range check
574 // the immediate passed by the user.
575 bool define = proto.find('i') != std::string::npos;
577 std::string ts = TypeString(proto[0], typestr);
579 if (op == OpHi || op == OpLo) {
580 s = "union { " + ts + " r; double d; } u; u.d = ";
581 } else if (!define) {
590 s += Extend(typestr, "__a") + " + " + Extend(typestr, "__b") + ";";
593 s += "__a + " + Extend(typestr, "__b") + ";";
599 s += Extend(typestr, "__a") + " - " + Extend(typestr, "__b") + ";";
602 s += "__a - " + Extend(typestr, "__b") + ";";
605 s += "__a * " + Duplicate(nElts, typestr, "__b") + ";";
608 s += "__a * " + SplatLane(nElts, "__b", "__c") + ";";
614 s += Extend(typestr, "__a") + " * " +
615 Extend(typestr, Duplicate(nElts << (int)quad, typestr, "__b")) + ";";
618 s += Extend(typestr, "__a") + " * " +
619 Extend(typestr, SplatLane(nElts, "__b", "__c")) + ";";
622 s += Extend(typestr, "__a") + " * " + Extend(typestr, "__b") + ";";
625 s += "__a + (__b * " + Duplicate(nElts, typestr, "__c") + ");";
628 s += "__a + (__b * " + SplatLane(nElts, "__c", "__d") + ");";
631 s += "__a + (__b * __c);";
634 s += "__a + (" + Extend(typestr, "__b") + " * " +
635 Extend(typestr, Duplicate(nElts, typestr, "__c")) + ");";
638 s += "__a + (" + Extend(typestr, "__b") + " * " +
639 Extend(typestr, SplatLane(nElts, "__c", "__d")) + ");";
642 s += "__a + (" + Extend(typestr, "__b") + " * " +
643 Extend(typestr, "__c") + ");";
646 s += "__a - (__b * " + Duplicate(nElts, typestr, "__c") + ");";
649 s += "__a - (__b * " + SplatLane(nElts, "__c", "__d") + ");";
652 s += "__a - (__b * __c);";
655 s += "__a - (" + Extend(typestr, "__b") + " * " +
656 Extend(typestr, Duplicate(nElts, typestr, "__c")) + ");";
659 s += "__a - (" + Extend(typestr, "__b") + " * " +
660 Extend(typestr, SplatLane(nElts, "__c", "__d")) + ");";
663 s += "__a - (" + Extend(typestr, "__b") + " * " +
664 Extend(typestr, "__c") + ");";
667 s += MangleName("vqdmull", typestr, ClassS) + "(__a, " +
668 SplatLane(nElts, "__b", "__c") + ");";
671 s += MangleName("vqdmlal", typestr, ClassS) + "(__a, __b, " +
672 SplatLane(nElts, "__c", "__d") + ");";
675 s += MangleName("vqdmlsl", typestr, ClassS) + "(__a, __b, " +
676 SplatLane(nElts, "__c", "__d") + ");";
679 s += MangleName("vqdmulh", typestr, ClassS) + "(__a, " +
680 SplatLane(nElts, "__b", "__c") + ");";
683 s += MangleName("vqrdmulh", typestr, ClassS) + "(__a, " +
684 SplatLane(nElts, "__b", "__c") + ");";
687 s += "(" + ts + ")(__a == __b);";
690 s += "(" + ts + ")(__a >= __b);";
693 s += "(" + ts + ")(__a <= __b);";
696 s += "(" + ts + ")(__a > __b);";
699 s += "(" + ts + ")(__a < __b);";
723 s += "(" + ts + ")__a;";
726 s += "(" + ts + ")__builtin_shufflevector((int64x1_t)__a";
727 s += ", (int64x1_t)__b, 0, 1);";
730 s += "(((float64x2_t)__a)[1]);";
733 s += "(((float64x2_t)__a)[0]);";
736 s += Duplicate(nElts, typestr, "__a") + ";";
739 s += SplatLane(nElts, "__a", "__b") + ";";
742 // ((0 & 1) | (~0 & 2))
744 ts = TypeString(proto[1], typestr);
745 s += "((__a & (" + ts + ")__b) | ";
746 s += "(~__a & (" + ts + ")__c));";
749 s += "__builtin_shufflevector(__a, __a";
750 for (unsigned i = 2; i <= nElts; i += 2)
751 for (unsigned j = 0; j != 2; ++j)
752 s += ", " + utostr(i - j - 1);
756 unsigned WordElts = nElts >> (1 + (int)quad);
757 s += "__builtin_shufflevector(__a, __a";
758 for (unsigned i = WordElts; i <= nElts; i += WordElts)
759 for (unsigned j = 0; j != WordElts; ++j)
760 s += ", " + utostr(i - j - 1);
765 unsigned DblWordElts = nElts >> (int)quad;
766 s += "__builtin_shufflevector(__a, __a";
767 for (unsigned i = DblWordElts; i <= nElts; i += DblWordElts)
768 for (unsigned j = 0; j != DblWordElts; ++j)
769 s += ", " + utostr(i - j - 1);
774 std::string abd = MangleName("vabd", typestr, ClassS) + "(__a, __b)";
775 if (typestr[0] != 'U') {
776 // vabd results are always unsigned and must be zero-extended.
777 std::string utype = "U" + typestr.str();
778 s += "(" + TypeString(proto[0], typestr) + ")";
779 abd = "(" + TypeString('d', utype) + ")" + abd;
780 s += Extend(utype, abd) + ";";
782 s += Extend(typestr, abd) + ";";
787 s += "__a + " + MangleName("vabd", typestr, ClassS) + "(__b, __c);";
791 std::string abd = MangleName("vabd", typestr, ClassS) + "(__b, __c)";
792 if (typestr[0] != 'U') {
793 // vabd results are always unsigned and must be zero-extended.
794 std::string utype = "U" + typestr.str();
795 s += "(" + TypeString(proto[0], typestr) + ")";
796 abd = "(" + TypeString('d', utype) + ")" + abd;
797 s += Extend(utype, abd) + ";";
799 s += Extend(typestr, abd) + ";";
804 throw "unknown OpKind!";
807 if (op == OpHi || op == OpLo) {
815 static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
816 unsigned mod = proto[0];
819 if (mod == 'v' || mod == 'f')
829 // Base type to get the type string for.
830 char type = ClassifyType(typestr, quad, poly, usgn);
832 // Based on the modifying character, change the type and width if necessary.
833 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
837 if (quad && proto[1] != 'g')
860 throw "unhandled type!";
866 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
867 static std::string GenBuiltin(const std::string &name, const std::string &proto,
868 StringRef typestr, ClassKind ck) {
871 // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
872 // sret-like argument.
873 bool sret = (proto[0] >= '2' && proto[0] <= '4');
875 // If this builtin takes an immediate argument, we need to #define it rather
876 // than use a standard declaration, so that SemaChecking can range check
877 // the immediate passed by the user.
878 bool define = proto.find('i') != std::string::npos;
880 // Check if the prototype has a scalar operand with the type of the vector
881 // elements. If not, bitcasting the args will take care of arg checking.
882 // The actual signedness etc. will be taken care of with special enums.
883 if (proto.find('s') == std::string::npos)
886 if (proto[0] != 'v') {
887 std::string ts = TypeString(proto[0], typestr);
897 s += "return (" + ts + ")";
901 bool splat = proto.find('a') != std::string::npos;
903 s += "__builtin_neon_";
905 // Call the non-splat builtin: chop off the "_n" suffix from the name.
906 std::string vname(name, 0, name.size()-2);
907 s += MangleName(vname, typestr, ck);
909 s += MangleName(name, typestr, ck);
913 // Pass the address of the return variable as the first argument to sret-like
919 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
920 std::string args = std::string(&arg, 1);
922 // Use the local temporaries instead of the macro arguments.
925 bool argQuad = false;
926 bool argPoly = false;
927 bool argUsgn = false;
928 bool argScalar = false;
930 char argType = ClassifyType(typestr, argQuad, argPoly, argUsgn);
931 argType = ModType(proto[i], argType, argQuad, argPoly, argUsgn, argScalar,
934 // Handle multiple-vector values specially, emitting each subvector as an
935 // argument to the __builtin.
936 if (proto[i] >= '2' && proto[i] <= '4') {
937 // Check if an explicit cast is needed.
938 if (argType != 'c' || argPoly || argUsgn)
939 args = (argQuad ? "(int8x16_t)" : "(int8x8_t)") + args;
941 for (unsigned vi = 0, ve = proto[i] - '0'; vi != ve; ++vi) {
942 s += args + ".val[" + utostr(vi) + "]";
952 if (splat && (i + 1) == e)
953 args = Duplicate(GetNumElements(typestr, argQuad), typestr, args);
955 // Check if an explicit cast is needed.
956 if ((splat || !argScalar) &&
957 ((ck == ClassB && argType != 'c') || argPoly || argUsgn)) {
958 std::string argTypeStr = "c";
960 argTypeStr = argType;
962 argTypeStr = "Q" + argTypeStr;
963 args = "(" + TypeString('d', argTypeStr) + ")" + args;
971 // Extra constant integer to hold type class enum for this function, e.g. s8
973 s += ", " + utostr(GetNeonEnum(proto, typestr));
977 if (proto[0] != 'v' && sret) {
986 static std::string GenBuiltinDef(const std::string &name,
987 const std::string &proto,
988 StringRef typestr, ClassKind ck) {
989 std::string s("BUILTIN(__builtin_neon_");
991 // If all types are the same size, bitcasting the args will take care
992 // of arg checking. The actual signedness etc. will be taken care of with
994 if (proto.find('s') == std::string::npos)
997 s += MangleName(name, typestr, ck);
1000 for (unsigned i = 0, e = proto.size(); i != e; ++i)
1001 s += BuiltinTypeString(proto[i], typestr, ck, i == 0);
1003 // Extra constant integer to hold type class enum for this function, e.g. s8
1011 static std::string GenIntrinsic(const std::string &name,
1012 const std::string &proto,
1013 StringRef outTypeStr, StringRef inTypeStr,
1014 OpKind kind, ClassKind classKind) {
1015 assert(!proto.empty() && "");
1016 bool define = proto.find('i') != std::string::npos;
1019 // static always inline + return type
1023 s += "__ai " + TypeString(proto[0], outTypeStr) + " ";
1025 // Function name with type suffix
1026 std::string mangledName = MangleName(name, outTypeStr, ClassS);
1027 if (outTypeStr != inTypeStr) {
1028 // If the input type is different (e.g., for vreinterpret), append a suffix
1029 // for the input type. String off a "Q" (quad) prefix so that MangleName
1030 // does not insert another "q" in the name.
1031 unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1032 StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1033 mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1037 // Function arguments
1038 s += GenArgs(proto, inTypeStr);
1042 s += " __extension__ ({ \\\n ";
1043 s += GenMacroLocals(proto, inTypeStr);
1049 s += GenOpString(kind, proto, outTypeStr);
1051 s += GenBuiltin(name, proto, outTypeStr, classKind);
1060 /// run - Read the records in arm_neon.td and output arm_neon.h. arm_neon.h
1061 /// is comprised of type definitions and function declarations.
1062 void NeonEmitter::run(raw_ostream &OS) {
1064 "/*===---- arm_neon.h - ARM Neon intrinsics ------------------------------"
1067 " * Permission is hereby granted, free of charge, to any person obtaining "
1069 " * of this software and associated documentation files (the \"Software\"),"
1071 " * in the Software without restriction, including without limitation the "
1073 " * to use, copy, modify, merge, publish, distribute, sublicense, "
1075 " * copies of the Software, and to permit persons to whom the Software is\n"
1076 " * furnished to do so, subject to the following conditions:\n"
1078 " * The above copyright notice and this permission notice shall be "
1080 " * all copies or substantial portions of the Software.\n"
1082 " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
1084 " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
1085 "MERCHANTABILITY,\n"
1086 " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
1088 " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
1090 " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
1092 " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
1094 " * THE SOFTWARE.\n"
1096 " *===--------------------------------------------------------------------"
1100 OS << "#ifndef __ARM_NEON_H\n";
1101 OS << "#define __ARM_NEON_H\n\n";
1103 OS << "#ifndef __ARM_NEON__\n";
1104 OS << "#error \"NEON support not enabled\"\n";
1107 OS << "#include <stdint.h>\n\n";
1109 // Emit NEON-specific scalar typedefs.
1110 OS << "typedef float float32_t;\n";
1111 OS << "typedef int8_t poly8_t;\n";
1112 OS << "typedef int16_t poly16_t;\n";
1113 OS << "typedef uint16_t float16_t;\n";
1115 // Emit Neon vector typedefs.
1116 std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
1117 SmallVector<StringRef, 24> TDTypeVec;
1118 ParseTypes(0, TypedefTypes, TDTypeVec);
1120 // Emit vector typedefs.
1121 for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1122 bool dummy, quad = false, poly = false;
1123 (void) ClassifyType(TDTypeVec[i], quad, poly, dummy);
1125 OS << "typedef __attribute__((neon_polyvector_type(";
1127 OS << "typedef __attribute__((neon_vector_type(";
1129 unsigned nElts = GetNumElements(TDTypeVec[i], quad);
1130 OS << utostr(nElts) << "))) ";
1134 OS << TypeString('s', TDTypeVec[i]);
1135 OS << " " << TypeString('d', TDTypeVec[i]) << ";\n";
1138 OS << "typedef __attribute__((__vector_size__(8))) "
1139 "double float64x1_t;\n";
1140 OS << "typedef __attribute__((__vector_size__(16))) "
1141 "double float64x2_t;\n";
1144 // Emit struct typedefs.
1145 for (unsigned vi = 2; vi != 5; ++vi) {
1146 for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1147 std::string ts = TypeString('d', TDTypeVec[i]);
1148 std::string vs = TypeString('0' + vi, TDTypeVec[i]);
1149 OS << "typedef struct " << vs << " {\n";
1150 OS << " " << ts << " val";
1151 OS << "[" << utostr(vi) << "]";
1153 OS << vs << ";\n\n";
1157 OS << "#define __ai static __attribute__((__always_inline__))\n\n";
1159 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1161 // Emit vmovl and vabd intrinsics first so they can be used by other
1162 // intrinsics. (Some of the saturating multiply instructions are also
1163 // used to implement the corresponding "_lane" variants, but tablegen
1164 // sorts the records into alphabetical order so that the "_lane" variants
1165 // come after the intrinsics they use.)
1166 emitIntrinsic(OS, Records.getDef("VMOVL"));
1167 emitIntrinsic(OS, Records.getDef("VABD"));
1169 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1171 if (R->getName() != "VMOVL" && R->getName() != "VABD")
1172 emitIntrinsic(OS, R);
1175 OS << "#undef __ai\n\n";
1176 OS << "#endif /* __ARM_NEON_H */\n";
1179 /// emitIntrinsic - Write out the arm_neon.h header file definitions for the
1180 /// intrinsics specified by record R.
1181 void NeonEmitter::emitIntrinsic(raw_ostream &OS, Record *R) {
1182 std::string name = R->getValueAsString("Name");
1183 std::string Proto = R->getValueAsString("Prototype");
1184 std::string Types = R->getValueAsString("Types");
1186 SmallVector<StringRef, 16> TypeVec;
1187 ParseTypes(R, Types, TypeVec);
1189 OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1191 ClassKind classKind = ClassNone;
1192 if (R->getSuperClasses().size() >= 2)
1193 classKind = ClassMap[R->getSuperClasses()[1]];
1194 if (classKind == ClassNone && kind == OpNone)
1195 throw TGError(R->getLoc(), "Builtin has no class kind");
1197 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1198 if (kind == OpReinterpret) {
1199 bool outQuad = false;
1201 (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1202 for (unsigned srcti = 0, srcte = TypeVec.size();
1203 srcti != srcte; ++srcti) {
1204 bool inQuad = false;
1205 (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1206 if (srcti == ti || inQuad != outQuad)
1208 OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[srcti],
1212 OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[ti],
1219 static unsigned RangeFromType(const char mod, StringRef typestr) {
1220 // base type to get the type string for.
1221 bool quad = false, dummy = false;
1222 char type = ClassifyType(typestr, quad, dummy, dummy);
1223 type = ModType(mod, type, quad, dummy, dummy, dummy, dummy, dummy);
1227 return (8 << (int)quad) - 1;
1230 return (4 << (int)quad) - 1;
1233 return (2 << (int)quad) - 1;
1235 return (1 << (int)quad) - 1;
1237 throw "unhandled type!";
1240 assert(0 && "unreachable");
1244 /// runHeader - Emit a file with sections defining:
1245 /// 1. the NEON section of BuiltinsARM.def.
1246 /// 2. the SemaChecking code for the type overload checking.
1247 /// 3. the SemaChecking code for validation of intrinsic immedate arguments.
1248 void NeonEmitter::runHeader(raw_ostream &OS) {
1249 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1251 StringMap<OpKind> EmittedMap;
1253 // Generate BuiltinsARM.def for NEON
1254 OS << "#ifdef GET_NEON_BUILTINS\n";
1255 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1257 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1261 std::string Proto = R->getValueAsString("Prototype");
1263 // Functions with 'a' (the splat code) in the type prototype should not get
1264 // their own builtin as they use the non-splat variant.
1265 if (Proto.find('a') != std::string::npos)
1268 std::string Types = R->getValueAsString("Types");
1269 SmallVector<StringRef, 16> TypeVec;
1270 ParseTypes(R, Types, TypeVec);
1272 if (R->getSuperClasses().size() < 2)
1273 throw TGError(R->getLoc(), "Builtin has no class kind");
1275 std::string name = R->getValueAsString("Name");
1276 ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1278 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1279 // Generate the BuiltinsARM.def declaration for this builtin, ensuring
1280 // that each unique BUILTIN() macro appears only once in the output
1282 std::string bd = GenBuiltinDef(name, Proto, TypeVec[ti], ck);
1283 if (EmittedMap.count(bd))
1286 EmittedMap[bd] = OpNone;
1292 // Generate the overloaded type checking code for SemaChecking.cpp
1293 OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1294 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1296 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1300 std::string Proto = R->getValueAsString("Prototype");
1301 std::string Types = R->getValueAsString("Types");
1302 std::string name = R->getValueAsString("Name");
1304 // Functions with 'a' (the splat code) in the type prototype should not get
1305 // their own builtin as they use the non-splat variant.
1306 if (Proto.find('a') != std::string::npos)
1309 // Functions which have a scalar argument cannot be overloaded, no need to
1310 // check them if we are emitting the type checking code.
1311 if (Proto.find('s') != std::string::npos)
1314 SmallVector<StringRef, 16> TypeVec;
1315 ParseTypes(R, Types, TypeVec);
1317 if (R->getSuperClasses().size() < 2)
1318 throw TGError(R->getLoc(), "Builtin has no class kind");
1320 int si = -1, qi = -1;
1321 unsigned mask = 0, qmask = 0;
1322 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1323 // Generate the switch case(s) for this builtin for the type validation.
1324 bool quad = false, poly = false, usgn = false;
1325 (void) ClassifyType(TypeVec[ti], quad, poly, usgn);
1329 qmask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1332 mask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1336 OS << "case ARM::BI__builtin_neon_"
1337 << MangleName(name, TypeVec[si], ClassB)
1338 << ": mask = " << "0x" << utohexstr(mask) << "; break;\n";
1340 OS << "case ARM::BI__builtin_neon_"
1341 << MangleName(name, TypeVec[qi], ClassB)
1342 << ": mask = " << "0x" << utohexstr(qmask) << "; break;\n";
1346 // Generate the intrinsic range checking code for shift/lane immediates.
1347 OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
1348 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1351 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1355 std::string name = R->getValueAsString("Name");
1356 std::string Proto = R->getValueAsString("Prototype");
1357 std::string Types = R->getValueAsString("Types");
1359 // Functions with 'a' (the splat code) in the type prototype should not get
1360 // their own builtin as they use the non-splat variant.
1361 if (Proto.find('a') != std::string::npos)
1364 // Functions which do not have an immediate do not need to have range
1365 // checking code emitted.
1366 size_t immPos = Proto.find('i');
1367 if (immPos == std::string::npos)
1370 SmallVector<StringRef, 16> TypeVec;
1371 ParseTypes(R, Types, TypeVec);
1373 if (R->getSuperClasses().size() < 2)
1374 throw TGError(R->getLoc(), "Builtin has no class kind");
1376 ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1378 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1379 std::string namestr, shiftstr, rangestr;
1381 // Builtins which are overloaded by type will need to have their upper
1382 // bound computed at Sema time based on the type constant.
1383 if (Proto.find('s') == std::string::npos) {
1385 if (R->getValueAsBit("isShift")) {
1386 shiftstr = ", true";
1388 // Right shifts have an 'r' in the name, left shifts do not.
1389 if (name.find('r') != std::string::npos)
1390 rangestr = "l = 1; ";
1392 rangestr += "u = RFT(TV" + shiftstr + ")";
1394 // The immediate generally refers to a lane in the preceding argument.
1395 assert(immPos > 0 && "unexpected immediate operand");
1396 rangestr = "u = " + utostr(RangeFromType(Proto[immPos-1], TypeVec[ti]));
1398 // Make sure cases appear only once by uniquing them in a string map.
1399 namestr = MangleName(name, TypeVec[ti], ck);
1400 if (EmittedMap.count(namestr))
1402 EmittedMap[namestr] = OpNone;
1404 // Calculate the index of the immediate that should be range checked.
1405 unsigned immidx = 0;
1407 // Builtins that return a struct of multiple vectors have an extra
1408 // leading arg for the struct return.
1409 if (Proto[0] >= '2' && Proto[0] <= '4')
1412 // Add one to the index for each argument until we reach the immediate
1413 // to be checked. Structs of vectors are passed as multiple arguments.
1414 for (unsigned ii = 1, ie = Proto.size(); ii != ie; ++ii) {
1415 switch (Proto[ii]) {
1416 default: immidx += 1; break;
1417 case '2': immidx += 2; break;
1418 case '3': immidx += 3; break;
1419 case '4': immidx += 4; break;
1420 case 'i': ie = ii + 1; break;
1423 OS << "case ARM::BI__builtin_neon_" << MangleName(name, TypeVec[ti], ck)
1424 << ": i = " << immidx << "; " << rangestr << "; break;\n";
1430 /// GenTest - Write out a test for the intrinsic specified by the name and
1431 /// type strings, including the embedded patterns for FileCheck to match.
1432 static std::string GenTest(const std::string &name,
1433 const std::string &proto,
1434 StringRef outTypeStr, StringRef inTypeStr,
1436 assert(!proto.empty() && "");
1439 // Function name with type suffix
1440 std::string mangledName = MangleName(name, outTypeStr, ClassS);
1441 if (outTypeStr != inTypeStr) {
1442 // If the input type is different (e.g., for vreinterpret), append a suffix
1443 // for the input type. String off a "Q" (quad) prefix so that MangleName
1444 // does not insert another "q" in the name.
1445 unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1446 StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1447 mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1450 // Emit the FileCheck patterns.
1451 s += "// CHECK: test_" + mangledName + "\n";
1452 // s += "// CHECK: \n"; // FIXME: + expected instruction opcode.
1454 // Emit the start of the test function.
1455 s += TypeString(proto[0], outTypeStr) + " test_" + mangledName + "(";
1458 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1459 // Do not create arguments for values that must be immediate constants.
1460 if (proto[i] == 'i')
1462 s += comma + TypeString(proto[i], inTypeStr) + " ";
1468 if (proto[0] != 'v')
1470 s += mangledName + "(";
1472 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1473 if (proto[i] == 'i') {
1474 // For immediate operands, test the maximum value.
1478 // The immediate generally refers to a lane in the preceding argument.
1479 s += utostr(RangeFromType(proto[i-1], inTypeStr));
1490 /// runTests - Write out a complete set of tests for all of the Neon
1492 void NeonEmitter::runTests(raw_ostream &OS) {
1494 "// RUN: %clang_cc1 -triple thumbv7-apple-darwin \\\n"
1495 "// RUN: -target-cpu cortex-a8 -ffreestanding -S -o - %s | FileCheck %s\n"
1497 "#include <arm_neon.h>\n"
1500 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1501 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1503 std::string name = R->getValueAsString("Name");
1504 std::string Proto = R->getValueAsString("Prototype");
1505 std::string Types = R->getValueAsString("Types");
1506 bool isShift = R->getValueAsBit("isShift");
1508 SmallVector<StringRef, 16> TypeVec;
1509 ParseTypes(R, Types, TypeVec);
1511 OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1512 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1513 if (kind == OpReinterpret) {
1514 bool outQuad = false;
1516 (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1517 for (unsigned srcti = 0, srcte = TypeVec.size();
1518 srcti != srcte; ++srcti) {
1519 bool inQuad = false;
1520 (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1521 if (srcti == ti || inQuad != outQuad)
1523 OS << GenTest(name, Proto, TypeVec[ti], TypeVec[srcti], isShift);
1526 OS << GenTest(name, Proto, TypeVec[ti], TypeVec[ti], isShift);