Add an OpReinterpret operation to TableGen's NeonEmitter.
[oota-llvm.git] / utils / TableGen / NeonEmitter.cpp
1 //===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // 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.
13 //
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
18 // CodeGen library.
19 //
20 // Additional validation code can be generated by this file when runHeader() is
21 // called, rather than the normal run() entry point.
22 //
23 //===----------------------------------------------------------------------===//
24
25 #include "NeonEmitter.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include <string>
30
31 using namespace llvm;
32
33 /// ParseTypes - break down a string such as "fQf" into a vector of StringRefs,
34 /// which each StringRef representing a single type declared in the string.
35 /// for "fQf" we would end up with 2 StringRefs, "f", and "Qf", representing
36 /// 2xfloat and 4xfloat respectively.
37 static void ParseTypes(Record *r, std::string &s,
38                        SmallVectorImpl<StringRef> &TV) {
39   const char *data = s.data();
40   int len = 0;
41
42   for (unsigned i = 0, e = s.size(); i != e; ++i, ++len) {
43     if (data[len] == 'P' || data[len] == 'Q' || data[len] == 'U')
44       continue;
45
46     switch (data[len]) {
47       case 'c':
48       case 's':
49       case 'i':
50       case 'l':
51       case 'h':
52       case 'f':
53         break;
54       default:
55         throw TGError(r->getLoc(),
56                       "Unexpected letter: " + std::string(data + len, 1));
57         break;
58     }
59     TV.push_back(StringRef(data, len + 1));
60     data += len + 1;
61     len = -1;
62   }
63 }
64
65 /// Widen - Convert a type code into the next wider type.  char -> short,
66 /// short -> int, etc.
67 static char Widen(const char t) {
68   switch (t) {
69     case 'c':
70       return 's';
71     case 's':
72       return 'i';
73     case 'i':
74       return 'l';
75     default: throw "unhandled type in widen!";
76   }
77   return '\0';
78 }
79
80 /// Narrow - Convert a type code into the next smaller type.  short -> char,
81 /// float -> half float, etc.
82 static char Narrow(const char t) {
83   switch (t) {
84     case 's':
85       return 'c';
86     case 'i':
87       return 's';
88     case 'l':
89       return 'i';
90     case 'f':
91       return 'h';
92     default: throw "unhandled type in narrow!";
93   }
94   return '\0';
95 }
96
97 /// For a particular StringRef, return the base type code, and whether it has
98 /// the quad-vector, polynomial, or unsigned modifiers set.
99 static char ClassifyType(StringRef ty, bool &quad, bool &poly, bool &usgn) {
100   unsigned off = 0;
101
102   // remember quad.
103   if (ty[off] == 'Q') {
104     quad = true;
105     ++off;
106   }
107
108   // remember poly.
109   if (ty[off] == 'P') {
110     poly = true;
111     ++off;
112   }
113
114   // remember unsigned.
115   if (ty[off] == 'U') {
116     usgn = true;
117     ++off;
118   }
119
120   // base type to get the type string for.
121   return ty[off];
122 }
123
124 /// ModType - Transform a type code and its modifiers based on a mod code. The
125 /// mod code definitions may be found at the top of arm_neon.td.
126 static char ModType(const char mod, char type, bool &quad, bool &poly,
127                     bool &usgn, bool &scal, bool &cnst, bool &pntr) {
128   switch (mod) {
129     case 't':
130       if (poly) {
131         poly = false;
132         usgn = true;
133       }
134       break;
135     case 'u':
136       usgn = true;
137       poly = false;
138       if (type == 'f')
139         type = 'i';
140       break;
141     case 'x':
142       usgn = false;
143       poly = false;
144       if (type == 'f')
145         type = 'i';
146       break;
147     case 'f':
148       if (type == 'h')
149         quad = true;
150       type = 'f';
151       usgn = false;
152       break;
153     case 'g':
154       quad = false;
155       break;
156     case 'w':
157       type = Widen(type);
158       quad = true;
159       break;
160     case 'n':
161       type = Widen(type);
162       break;
163     case 'i':
164       type = 'i';
165       scal = true;
166       break;
167     case 'l':
168       type = 'l';
169       scal = true;
170       usgn = true;
171       break;
172     case 's':
173     case 'a':
174       scal = true;
175       break;
176     case 'k':
177       quad = true;
178       break;
179     case 'c':
180       cnst = true;
181     case 'p':
182       pntr = true;
183       scal = true;
184       break;
185     case 'h':
186       type = Narrow(type);
187       if (type == 'h')
188         quad = false;
189       break;
190     case 'e':
191       type = Narrow(type);
192       usgn = true;
193       break;
194     default:
195       break;
196   }
197   return type;
198 }
199
200 /// TypeString - for a modifier and type, generate the name of the typedef for
201 /// that type.  QUc -> uint8x8_t.
202 static std::string TypeString(const char mod, StringRef typestr) {
203   bool quad = false;
204   bool poly = false;
205   bool usgn = false;
206   bool scal = false;
207   bool cnst = false;
208   bool pntr = false;
209
210   if (mod == 'v')
211     return "void";
212   if (mod == 'i')
213     return "int";
214
215   // base type to get the type string for.
216   char type = ClassifyType(typestr, quad, poly, usgn);
217
218   // Based on the modifying character, change the type and width if necessary.
219   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
220
221   SmallString<128> s;
222
223   if (usgn)
224     s.push_back('u');
225
226   switch (type) {
227     case 'c':
228       s += poly ? "poly8" : "int8";
229       if (scal)
230         break;
231       s += quad ? "x16" : "x8";
232       break;
233     case 's':
234       s += poly ? "poly16" : "int16";
235       if (scal)
236         break;
237       s += quad ? "x8" : "x4";
238       break;
239     case 'i':
240       s += "int32";
241       if (scal)
242         break;
243       s += quad ? "x4" : "x2";
244       break;
245     case 'l':
246       s += "int64";
247       if (scal)
248         break;
249       s += quad ? "x2" : "x1";
250       break;
251     case 'h':
252       s += "float16";
253       if (scal)
254         break;
255       s += quad ? "x8" : "x4";
256       break;
257     case 'f':
258       s += "float32";
259       if (scal)
260         break;
261       s += quad ? "x4" : "x2";
262       break;
263     default:
264       throw "unhandled type!";
265       break;
266   }
267
268   if (mod == '2')
269     s += "x2";
270   if (mod == '3')
271     s += "x3";
272   if (mod == '4')
273     s += "x4";
274
275   // Append _t, finishing the type string typedef type.
276   s += "_t";
277
278   if (cnst)
279     s += " const";
280
281   if (pntr)
282     s += " *";
283
284   return s.str();
285 }
286
287 /// BuiltinTypeString - for a modifier and type, generate the clang
288 /// BuiltinsARM.def prototype code for the function.  See the top of clang's
289 /// Builtins.def for a description of the type strings.
290 static std::string BuiltinTypeString(const char mod, StringRef typestr,
291                                      ClassKind ck, bool ret) {
292   bool quad = false;
293   bool poly = false;
294   bool usgn = false;
295   bool scal = false;
296   bool cnst = false;
297   bool pntr = false;
298
299   if (mod == 'v')
300     return "v"; // void
301   if (mod == 'i')
302     return "i"; // int
303
304   // base type to get the type string for.
305   char type = ClassifyType(typestr, quad, poly, usgn);
306
307   // Based on the modifying character, change the type and width if necessary.
308   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
309
310   // All pointers are void* pointers.  Change type to 'v' now.
311   if (pntr) {
312     usgn = false;
313     poly = false;
314     type = 'v';
315   }
316   // Treat half-float ('h') types as unsigned short ('s') types.
317   if (type == 'h') {
318     type = 's';
319     usgn = true;
320   }
321   usgn = usgn | poly | ((ck == ClassI || ck == ClassW) && scal && type != 'f');
322
323   if (scal) {
324     SmallString<128> s;
325
326     if (usgn)
327       s.push_back('U');
328     else if (type == 'c')
329       s.push_back('S'); // make chars explicitly signed
330
331     if (type == 'l') // 64-bit long
332       s += "LLi";
333     else
334       s.push_back(type);
335
336     if (cnst)
337       s.push_back('C');
338     if (pntr)
339       s.push_back('*');
340     return s.str();
341   }
342
343   // Since the return value must be one type, return a vector type of the
344   // appropriate width which we will bitcast.  An exception is made for
345   // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
346   // fashion, storing them to a pointer arg.
347   if (ret) {
348     if (mod >= '2' && mod <= '4')
349       return "vv*"; // void result with void* first argument
350     if (mod == 'f' || (ck != ClassB && type == 'f'))
351       return quad ? "V4f" : "V2f";
352     if (ck != ClassB && type == 's')
353       return quad ? "V8s" : "V4s";
354     if (ck != ClassB && type == 'i')
355       return quad ? "V4i" : "V2i";
356     if (ck != ClassB && type == 'l')
357       return quad ? "V2LLi" : "V1LLi";
358
359     return quad ? "V16Sc" : "V8Sc";
360   }
361
362   // Non-return array types are passed as individual vectors.
363   if (mod == '2')
364     return quad ? "V16ScV16Sc" : "V8ScV8Sc";
365   if (mod == '3')
366     return quad ? "V16ScV16ScV16Sc" : "V8ScV8ScV8Sc";
367   if (mod == '4')
368     return quad ? "V16ScV16ScV16ScV16Sc" : "V8ScV8ScV8ScV8Sc";
369
370   if (mod == 'f' || (ck != ClassB && type == 'f'))
371     return quad ? "V4f" : "V2f";
372   if (ck != ClassB && type == 's')
373     return quad ? "V8s" : "V4s";
374   if (ck != ClassB && type == 'i')
375     return quad ? "V4i" : "V2i";
376   if (ck != ClassB && type == 'l')
377     return quad ? "V2LLi" : "V1LLi";
378
379   return quad ? "V16Sc" : "V8Sc";
380 }
381
382 /// MangleName - Append a type or width suffix to a base neon function name,
383 /// and insert a 'q' in the appropriate location if the operation works on
384 /// 128b rather than 64b.   E.g. turn "vst2_lane" into "vst2q_lane_f32", etc.
385 static std::string MangleName(const std::string &name, StringRef typestr,
386                               ClassKind ck) {
387   if (name == "vcvt_f32_f16")
388     return name;
389
390   bool quad = false;
391   bool poly = false;
392   bool usgn = false;
393   char type = ClassifyType(typestr, quad, poly, usgn);
394
395   std::string s = name;
396
397   switch (type) {
398   case 'c':
399     switch (ck) {
400     case ClassS: s += poly ? "_p8" : usgn ? "_u8" : "_s8"; break;
401     case ClassI: s += "_i8"; break;
402     case ClassW: s += "_8"; break;
403     default: break;
404     }
405     break;
406   case 's':
407     switch (ck) {
408     case ClassS: s += poly ? "_p16" : usgn ? "_u16" : "_s16"; break;
409     case ClassI: s += "_i16"; break;
410     case ClassW: s += "_16"; break;
411     default: break;
412     }
413     break;
414   case 'i':
415     switch (ck) {
416     case ClassS: s += usgn ? "_u32" : "_s32"; break;
417     case ClassI: s += "_i32"; break;
418     case ClassW: s += "_32"; break;
419     default: break;
420     }
421     break;
422   case 'l':
423     switch (ck) {
424     case ClassS: s += usgn ? "_u64" : "_s64"; break;
425     case ClassI: s += "_i64"; break;
426     case ClassW: s += "_64"; break;
427     default: break;
428     }
429     break;
430   case 'h':
431     switch (ck) {
432     case ClassS:
433     case ClassI: s += "_f16"; break;
434     case ClassW: s += "_16"; break;
435     default: break;
436     }
437     break;
438   case 'f':
439     switch (ck) {
440     case ClassS:
441     case ClassI: s += "_f32"; break;
442     case ClassW: s += "_32"; break;
443     default: break;
444     }
445     break;
446   default:
447     throw "unhandled type!";
448     break;
449   }
450   if (ck == ClassB)
451     s += "_v";
452
453   // Insert a 'q' before the first '_' character so that it ends up before
454   // _lane or _n on vector-scalar operations.
455   if (quad) {
456     size_t pos = s.find('_');
457     s = s.insert(pos, "q");
458   }
459   return s;
460 }
461
462 // Generate the string "(argtype a, argtype b, ...)"
463 static std::string GenArgs(const std::string &proto, StringRef typestr) {
464   bool define = proto.find('i') != std::string::npos;
465   char arg = 'a';
466
467   std::string s;
468   s += "(";
469
470   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
471     if (define) {
472       // Immediate macro arguments are used directly instead of being assigned
473       // to local temporaries; prepend an underscore prefix to make their
474       // names consistent with the local temporaries.
475       if (proto[i] == 'i')
476         s += "__";
477     } else {
478       s += TypeString(proto[i], typestr) + " __";
479     }
480     s.push_back(arg);
481     if ((i + 1) < e)
482       s += ", ";
483   }
484
485   s += ")";
486   return s;
487 }
488
489 // Macro arguments are not type-checked like inline function arguments, so
490 // assign them to local temporaries to get the right type checking.
491 static std::string GenMacroLocals(const std::string &proto, StringRef typestr) {
492   char arg = 'a';
493   std::string s;
494
495   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
496     // Do not create a temporary for an immediate argument.
497     // That would defeat the whole point of using a macro!
498     if (proto[i] == 'i') continue;
499
500     s += TypeString(proto[i], typestr) + " __";
501     s.push_back(arg);
502     s += " = (";
503     s.push_back(arg);
504     s += "); ";
505   }
506
507   s += "\\\n  ";
508   return s;
509 }
510
511 static std::string Duplicate(unsigned nElts, StringRef typestr,
512                              const std::string &a) {
513   std::string s;
514
515   s = "(" + TypeString('d', typestr) + "){ ";
516   for (unsigned i = 0; i != nElts; ++i) {
517     s += a;
518     if ((i + 1) < nElts)
519       s += ", ";
520   }
521   s += " }";
522
523   return s;
524 }
525
526 static std::string SplatLane(unsigned nElts, const std::string &vec,
527                              const std::string &lane) {
528   std::string s = "__builtin_shufflevector(" + vec + ", " + vec;
529   for (unsigned i = 0; i < nElts; ++i)
530     s += ", " + lane;
531   s += ")";
532   return s;
533 }
534
535 static unsigned GetNumElements(StringRef typestr, bool &quad) {
536   quad = false;
537   bool dummy = false;
538   char type = ClassifyType(typestr, quad, dummy, dummy);
539   unsigned nElts = 0;
540   switch (type) {
541   case 'c': nElts = 8; break;
542   case 's': nElts = 4; break;
543   case 'i': nElts = 2; break;
544   case 'l': nElts = 1; break;
545   case 'h': nElts = 4; break;
546   case 'f': nElts = 2; break;
547   default:
548     throw "unhandled type!";
549     break;
550   }
551   if (quad) nElts <<= 1;
552   return nElts;
553 }
554
555 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
556 static std::string GenOpString(OpKind op, const std::string &proto,
557                                StringRef typestr) {
558   bool quad;
559   unsigned nElts = GetNumElements(typestr, quad);
560
561   // If this builtin takes an immediate argument, we need to #define it rather
562   // than use a standard declaration, so that SemaChecking can range check
563   // the immediate passed by the user.
564   bool define = proto.find('i') != std::string::npos;
565
566   std::string ts = TypeString(proto[0], typestr);
567   std::string s;
568   if (op == OpHi || op == OpLo) {
569     s = "union { " + ts + " r; double d; } u; u.d = ";
570   } else if (!define) {
571     s = "return ";
572   }
573
574   switch(op) {
575   case OpAdd:
576     s += "__a + __b;";
577     break;
578   case OpSub:
579     s += "__a - __b;";
580     break;
581   case OpMulN:
582     s += "__a * " + Duplicate(nElts, typestr, "__b") + ";";
583     break;
584   case OpMulLane:
585     s += "__a * " + SplatLane(nElts, "__b", "__c") + ";";
586     break;
587   case OpMul:
588     s += "__a * __b;";
589     break;
590   case OpMlaN:
591     s += "__a + (__b * " + Duplicate(nElts, typestr, "__c") + ");";
592     break;
593   case OpMlaLane:
594     s += "__a + (__b * " + SplatLane(nElts, "__c", "__d") + ");";
595     break;
596   case OpMla:
597     s += "__a + (__b * __c);";
598     break;
599   case OpMlsN:
600     s += "__a - (__b * " + Duplicate(nElts, typestr, "__c") + ");";
601     break;
602   case OpMlsLane:
603     s += "__a - (__b * " + SplatLane(nElts, "__c", "__d") + ");";
604     break;
605   case OpMls:
606     s += "__a - (__b * __c);";
607     break;
608   case OpEq:
609     s += "(" + ts + ")(__a == __b);";
610     break;
611   case OpGe:
612     s += "(" + ts + ")(__a >= __b);";
613     break;
614   case OpLe:
615     s += "(" + ts + ")(__a <= __b);";
616     break;
617   case OpGt:
618     s += "(" + ts + ")(__a > __b);";
619     break;
620   case OpLt:
621     s += "(" + ts + ")(__a < __b);";
622     break;
623   case OpNeg:
624     s += " -__a;";
625     break;
626   case OpNot:
627     s += " ~__a;";
628     break;
629   case OpAnd:
630     s += "__a & __b;";
631     break;
632   case OpOr:
633     s += "__a | __b;";
634     break;
635   case OpXor:
636     s += "__a ^ __b;";
637     break;
638   case OpAndNot:
639     s += "__a & ~__b;";
640     break;
641   case OpOrNot:
642     s += "__a | ~__b;";
643     break;
644   case OpCast:
645     s += "(" + ts + ")__a;";
646     break;
647   case OpConcat:
648     s += "(" + ts + ")__builtin_shufflevector((int64x1_t)__a";
649     s += ", (int64x1_t)__b, 0, 1);";
650     break;
651   case OpHi:
652     s += "(((float64x2_t)__a)[1]);";
653     break;
654   case OpLo:
655     s += "(((float64x2_t)__a)[0]);";
656     break;
657   case OpDup:
658     s += Duplicate(nElts, typestr, "__a") + ";";
659     break;
660   case OpSelect:
661     // ((0 & 1) | (~0 & 2))
662     s += "(" + ts + ")";
663     ts = TypeString(proto[1], typestr);
664     s += "((__a & (" + ts + ")__b) | ";
665     s += "(~__a & (" + ts + ")__c));";
666     break;
667   case OpRev16:
668     s += "__builtin_shufflevector(__a, __a";
669     for (unsigned i = 2; i <= nElts; i += 2)
670       for (unsigned j = 0; j != 2; ++j)
671         s += ", " + utostr(i - j - 1);
672     s += ");";
673     break;
674   case OpRev32: {
675     unsigned WordElts = nElts >> (1 + (int)quad);
676     s += "__builtin_shufflevector(__a, __a";
677     for (unsigned i = WordElts; i <= nElts; i += WordElts)
678       for (unsigned j = 0; j != WordElts; ++j)
679         s += ", " + utostr(i - j - 1);
680     s += ");";
681     break;
682   }
683   case OpRev64: {
684     unsigned DblWordElts = nElts >> (int)quad;
685     s += "__builtin_shufflevector(__a, __a";
686     for (unsigned i = DblWordElts; i <= nElts; i += DblWordElts)
687       for (unsigned j = 0; j != DblWordElts; ++j)
688         s += ", " + utostr(i - j - 1);
689     s += ");";
690     break;
691   }
692   default:
693     throw "unknown OpKind!";
694     break;
695   }
696   if (op == OpHi || op == OpLo) {
697     if (!define)
698       s += " return";
699     s += " u.r;";
700   }
701   return s;
702 }
703
704 static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
705   unsigned mod = proto[0];
706   unsigned ret = 0;
707
708   if (mod == 'v' || mod == 'f')
709     mod = proto[1];
710
711   bool quad = false;
712   bool poly = false;
713   bool usgn = false;
714   bool scal = false;
715   bool cnst = false;
716   bool pntr = false;
717
718   // Base type to get the type string for.
719   char type = ClassifyType(typestr, quad, poly, usgn);
720
721   // Based on the modifying character, change the type and width if necessary.
722   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
723
724   if (usgn)
725     ret |= 0x08;
726   if (quad && proto[1] != 'g')
727     ret |= 0x10;
728
729   switch (type) {
730     case 'c':
731       ret |= poly ? 5 : 0;
732       break;
733     case 's':
734       ret |= poly ? 6 : 1;
735       break;
736     case 'i':
737       ret |= 2;
738       break;
739     case 'l':
740       ret |= 3;
741       break;
742     case 'h':
743       ret |= 7;
744       break;
745     case 'f':
746       ret |= 4;
747       break;
748     default:
749       throw "unhandled type!";
750       break;
751   }
752   return ret;
753 }
754
755 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
756 static std::string GenBuiltin(const std::string &name, const std::string &proto,
757                               StringRef typestr, ClassKind ck) {
758   std::string s;
759
760   // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
761   // sret-like argument.
762   bool sret = (proto[0] >= '2' && proto[0] <= '4');
763
764   // If this builtin takes an immediate argument, we need to #define it rather
765   // than use a standard declaration, so that SemaChecking can range check
766   // the immediate passed by the user.
767   bool define = proto.find('i') != std::string::npos;
768
769   // Check if the prototype has a scalar operand with the type of the vector
770   // elements.  If not, bitcasting the args will take care of arg checking.
771   // The actual signedness etc. will be taken care of with special enums.
772   if (proto.find('s') == std::string::npos)
773     ck = ClassB;
774
775   if (proto[0] != 'v') {
776     std::string ts = TypeString(proto[0], typestr);
777
778     if (define) {
779       if (sret)
780         s += ts + " r; ";
781       else
782         s += "(" + ts + ")";
783     } else if (sret) {
784       s += ts + " r; ";
785     } else {
786       s += "return (" + ts + ")";
787     }
788   }
789
790   bool splat = proto.find('a') != std::string::npos;
791
792   s += "__builtin_neon_";
793   if (splat) {
794     // Call the non-splat builtin: chop off the "_n" suffix from the name.
795     std::string vname(name, 0, name.size()-2);
796     s += MangleName(vname, typestr, ck);
797   } else {
798     s += MangleName(name, typestr, ck);
799   }
800   s += "(";
801
802   // Pass the address of the return variable as the first argument to sret-like
803   // builtins.
804   if (sret)
805     s += "&r, ";
806
807   char arg = 'a';
808   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
809     std::string args = std::string(&arg, 1);
810
811     // Use the local temporaries instead of the macro arguments.
812     args = "__" + args;
813
814     bool argQuad = false;
815     bool argPoly = false;
816     bool argUsgn = false;
817     bool argScalar = false;
818     bool dummy = false;
819     char argType = ClassifyType(typestr, argQuad, argPoly, argUsgn);
820     argType = ModType(proto[i], argType, argQuad, argPoly, argUsgn, argScalar,
821                       dummy, dummy);
822
823     // Handle multiple-vector values specially, emitting each subvector as an
824     // argument to the __builtin.
825     if (proto[i] >= '2' && proto[i] <= '4') {
826       // Check if an explicit cast is needed.
827       if (argType != 'c' || argPoly || argUsgn)
828         args = (argQuad ? "(int8x16_t)" : "(int8x8_t)") + args;
829
830       for (unsigned vi = 0, ve = proto[i] - '0'; vi != ve; ++vi) {
831         s += args + ".val[" + utostr(vi) + "]";
832         if ((vi + 1) < ve)
833           s += ", ";
834       }
835       if ((i + 1) < e)
836         s += ", ";
837
838       continue;
839     }
840
841     if (splat && (i + 1) == e)
842       args = Duplicate(GetNumElements(typestr, argQuad), typestr, args);
843
844     // Check if an explicit cast is needed.
845     if ((splat || !argScalar) &&
846         ((ck == ClassB && argType != 'c') || argPoly || argUsgn)) {
847       std::string argTypeStr = "c";
848       if (ck != ClassB)
849         argTypeStr = argType;
850       if (argQuad)
851         argTypeStr = "Q" + argTypeStr;
852       args = "(" + TypeString('d', argTypeStr) + ")" + args;
853     }
854
855     s += args;
856     if ((i + 1) < e)
857       s += ", ";
858   }
859
860   // Extra constant integer to hold type class enum for this function, e.g. s8
861   if (ck == ClassB)
862     s += ", " + utostr(GetNeonEnum(proto, typestr));
863
864   s += ");";
865
866   if (proto[0] != 'v' && sret) {
867     if (define)
868       s += " r;";
869     else
870       s += " return r;";
871   }
872   return s;
873 }
874
875 static std::string GenBuiltinDef(const std::string &name,
876                                  const std::string &proto,
877                                  StringRef typestr, ClassKind ck) {
878   std::string s("BUILTIN(__builtin_neon_");
879
880   // If all types are the same size, bitcasting the args will take care
881   // of arg checking.  The actual signedness etc. will be taken care of with
882   // special enums.
883   if (proto.find('s') == std::string::npos)
884     ck = ClassB;
885
886   s += MangleName(name, typestr, ck);
887   s += ", \"";
888
889   for (unsigned i = 0, e = proto.size(); i != e; ++i)
890     s += BuiltinTypeString(proto[i], typestr, ck, i == 0);
891
892   // Extra constant integer to hold type class enum for this function, e.g. s8
893   if (ck == ClassB)
894     s += "i";
895
896   s += "\", \"n\")";
897   return s;
898 }
899
900 static std::string GenIntrinsic(const std::string &name,
901                                 const std::string &proto,
902                                 StringRef outTypeStr, StringRef inTypeStr,
903                                 OpKind kind, ClassKind classKind) {
904   assert(!proto.empty() && "");
905   bool define = proto.find('i') != std::string::npos;
906   std::string s;
907
908   // static always inline + return type
909   if (define)
910     s += "#define ";
911   else
912     s += "__ai " + TypeString(proto[0], outTypeStr) + " ";
913
914   // Function name with type suffix
915   std::string mangledName = MangleName(name, outTypeStr, ClassS);
916   if (outTypeStr != inTypeStr) {
917     // If the input type is different (e.g., for vreinterpret), append a suffix
918     // for the input type.  String off a "Q" (quad) prefix so that MangleName
919     // does not insert another "q" in the name.
920     unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
921     StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
922     mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
923   }
924   s += mangledName;
925
926   // Function arguments
927   s += GenArgs(proto, inTypeStr);
928
929   // Definition.
930   if (define) {
931     s += " __extension__ ({ \\\n  ";
932     s += GenMacroLocals(proto, inTypeStr);
933   } else {
934     s += " { \\\n  ";
935   }
936
937   if (kind != OpNone)
938     s += GenOpString(kind, proto, outTypeStr);
939   else
940     s += GenBuiltin(name, proto, outTypeStr, classKind);
941   if (define)
942     s += " })";
943   else
944     s += " }";
945   s += "\n";
946   return s;
947 }
948
949 /// run - Read the records in arm_neon.td and output arm_neon.h.  arm_neon.h
950 /// is comprised of type definitions and function declarations.
951 void NeonEmitter::run(raw_ostream &OS) {
952   EmitSourceFileHeader("ARM NEON Header", OS);
953
954   // FIXME: emit license into file?
955
956   OS << "#ifndef __ARM_NEON_H\n";
957   OS << "#define __ARM_NEON_H\n\n";
958
959   OS << "#ifndef __ARM_NEON__\n";
960   OS << "#error \"NEON support not enabled\"\n";
961   OS << "#endif\n\n";
962
963   OS << "#include <stdint.h>\n\n";
964
965   // Emit NEON-specific scalar typedefs.
966   OS << "typedef float float32_t;\n";
967   OS << "typedef int8_t poly8_t;\n";
968   OS << "typedef int16_t poly16_t;\n";
969   OS << "typedef uint16_t float16_t;\n";
970
971   // Emit Neon vector typedefs.
972   std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
973   SmallVector<StringRef, 24> TDTypeVec;
974   ParseTypes(0, TypedefTypes, TDTypeVec);
975
976   // Emit vector typedefs.
977   for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
978     bool dummy, quad = false, poly = false;
979     (void) ClassifyType(TDTypeVec[i], quad, poly, dummy);
980     if (poly)
981       OS << "typedef __attribute__((neon_polyvector_type(";
982     else
983       OS << "typedef __attribute__((neon_vector_type(";
984
985     unsigned nElts = GetNumElements(TDTypeVec[i], quad);
986     OS << utostr(nElts) << "))) ";
987     if (nElts < 10)
988       OS << " ";
989
990     OS << TypeString('s', TDTypeVec[i]);
991     OS << " " << TypeString('d', TDTypeVec[i]) << ";\n";
992   }
993   OS << "\n";
994   OS << "typedef __attribute__((__vector_size__(8)))  "
995     "double float64x1_t;\n";
996   OS << "typedef __attribute__((__vector_size__(16))) "
997     "double float64x2_t;\n";
998   OS << "\n";
999
1000   // Emit struct typedefs.
1001   for (unsigned vi = 2; vi != 5; ++vi) {
1002     for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1003       std::string ts = TypeString('d', TDTypeVec[i]);
1004       std::string vs = TypeString('0' + vi, TDTypeVec[i]);
1005       OS << "typedef struct " << vs << " {\n";
1006       OS << "  " << ts << " val";
1007       OS << "[" << utostr(vi) << "]";
1008       OS << ";\n} ";
1009       OS << vs << ";\n\n";
1010     }
1011   }
1012
1013   OS << "#define __ai static __attribute__((__always_inline__))\n\n";
1014
1015   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1016
1017   // Unique the return+pattern types, and assign them.
1018   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1019     Record *R = RV[i];
1020     std::string name = R->getValueAsString("Name");
1021     std::string Proto = R->getValueAsString("Prototype");
1022     std::string Types = R->getValueAsString("Types");
1023
1024     SmallVector<StringRef, 16> TypeVec;
1025     ParseTypes(R, Types, TypeVec);
1026
1027     OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1028
1029     ClassKind classKind = ClassNone;
1030     if (R->getSuperClasses().size() >= 2)
1031       classKind = ClassMap[R->getSuperClasses()[1]];
1032     if (classKind == ClassNone && kind == OpNone)
1033       throw TGError(R->getLoc(), "Builtin has no class kind");
1034
1035     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1036       if (kind == OpReinterpret) {
1037         bool outQuad = false;
1038         bool dummy = false;
1039         (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1040         for (unsigned srcti = 0, srcte = TypeVec.size();
1041              srcti != srcte; ++srcti) {
1042           bool inQuad = false;
1043           (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1044           if (srcti == ti || inQuad != outQuad)
1045             continue;
1046           OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[srcti],
1047                              OpCast, ClassS);
1048         }
1049       } else {
1050         OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[ti],
1051                            kind, classKind);
1052       }
1053     }
1054     OS << "\n";
1055   }
1056   OS << "#undef __ai\n\n";
1057   OS << "#endif /* __ARM_NEON_H */\n";
1058 }
1059
1060 static unsigned RangeFromType(StringRef typestr) {
1061   // base type to get the type string for.
1062   bool quad = false, dummy = false;
1063   char type = ClassifyType(typestr, quad, dummy, dummy);
1064
1065   switch (type) {
1066     case 'c':
1067       return (8 << (int)quad) - 1;
1068     case 'h':
1069     case 's':
1070       return (4 << (int)quad) - 1;
1071     case 'f':
1072     case 'i':
1073       return (2 << (int)quad) - 1;
1074     case 'l':
1075       return (1 << (int)quad) - 1;
1076     default:
1077       throw "unhandled type!";
1078       break;
1079   }
1080   assert(0 && "unreachable");
1081   return 0;
1082 }
1083
1084 /// runHeader - Emit a file with sections defining:
1085 /// 1. the NEON section of BuiltinsARM.def.
1086 /// 2. the SemaChecking code for the type overload checking.
1087 /// 3. the SemaChecking code for validation of intrinsic immedate arguments.
1088 void NeonEmitter::runHeader(raw_ostream &OS) {
1089   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1090
1091   StringMap<OpKind> EmittedMap;
1092
1093   // Generate BuiltinsARM.def for NEON
1094   OS << "#ifdef GET_NEON_BUILTINS\n";
1095   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1096     Record *R = RV[i];
1097     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1098     if (k != OpNone)
1099       continue;
1100
1101     std::string Proto = R->getValueAsString("Prototype");
1102
1103     // Functions with 'a' (the splat code) in the type prototype should not get
1104     // their own builtin as they use the non-splat variant.
1105     if (Proto.find('a') != std::string::npos)
1106       continue;
1107
1108     std::string Types = R->getValueAsString("Types");
1109     SmallVector<StringRef, 16> TypeVec;
1110     ParseTypes(R, Types, TypeVec);
1111
1112     if (R->getSuperClasses().size() < 2)
1113       throw TGError(R->getLoc(), "Builtin has no class kind");
1114
1115     std::string name = R->getValueAsString("Name");
1116     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1117
1118     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1119       // Generate the BuiltinsARM.def declaration for this builtin, ensuring
1120       // that each unique BUILTIN() macro appears only once in the output
1121       // stream.
1122       std::string bd = GenBuiltinDef(name, Proto, TypeVec[ti], ck);
1123       if (EmittedMap.count(bd))
1124         continue;
1125
1126       EmittedMap[bd] = OpNone;
1127       OS << bd << "\n";
1128     }
1129   }
1130   OS << "#endif\n\n";
1131
1132   // Generate the overloaded type checking code for SemaChecking.cpp
1133   OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1134   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1135     Record *R = RV[i];
1136     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1137     if (k != OpNone)
1138       continue;
1139
1140     std::string Proto = R->getValueAsString("Prototype");
1141     std::string Types = R->getValueAsString("Types");
1142     std::string name = R->getValueAsString("Name");
1143
1144     // Functions with 'a' (the splat code) in the type prototype should not get
1145     // their own builtin as they use the non-splat variant.
1146     if (Proto.find('a') != std::string::npos)
1147       continue;
1148
1149     // Functions which have a scalar argument cannot be overloaded, no need to
1150     // check them if we are emitting the type checking code.
1151     if (Proto.find('s') != std::string::npos)
1152       continue;
1153
1154     SmallVector<StringRef, 16> TypeVec;
1155     ParseTypes(R, Types, TypeVec);
1156
1157     if (R->getSuperClasses().size() < 2)
1158       throw TGError(R->getLoc(), "Builtin has no class kind");
1159
1160     int si = -1, qi = -1;
1161     unsigned mask = 0, qmask = 0;
1162     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1163       // Generate the switch case(s) for this builtin for the type validation.
1164       bool quad = false, poly = false, usgn = false;
1165       (void) ClassifyType(TypeVec[ti], quad, poly, usgn);
1166
1167       if (quad) {
1168         qi = ti;
1169         qmask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1170       } else {
1171         si = ti;
1172         mask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1173       }
1174     }
1175     if (mask)
1176       OS << "case ARM::BI__builtin_neon_"
1177          << MangleName(name, TypeVec[si], ClassB)
1178          << ": mask = " << "0x" << utohexstr(mask) << "; break;\n";
1179     if (qmask)
1180       OS << "case ARM::BI__builtin_neon_"
1181          << MangleName(name, TypeVec[qi], ClassB)
1182          << ": mask = " << "0x" << utohexstr(qmask) << "; break;\n";
1183   }
1184   OS << "#endif\n\n";
1185
1186   // Generate the intrinsic range checking code for shift/lane immediates.
1187   OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
1188   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1189     Record *R = RV[i];
1190
1191     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1192     if (k != OpNone)
1193       continue;
1194
1195     std::string name = R->getValueAsString("Name");
1196     std::string Proto = R->getValueAsString("Prototype");
1197     std::string Types = R->getValueAsString("Types");
1198
1199     // Functions with 'a' (the splat code) in the type prototype should not get
1200     // their own builtin as they use the non-splat variant.
1201     if (Proto.find('a') != std::string::npos)
1202       continue;
1203
1204     // Functions which do not have an immediate do not need to have range
1205     // checking code emitted.
1206     if (Proto.find('i') == std::string::npos)
1207       continue;
1208
1209     SmallVector<StringRef, 16> TypeVec;
1210     ParseTypes(R, Types, TypeVec);
1211
1212     if (R->getSuperClasses().size() < 2)
1213       throw TGError(R->getLoc(), "Builtin has no class kind");
1214
1215     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1216
1217     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1218       std::string namestr, shiftstr, rangestr;
1219
1220       // Builtins which are overloaded by type will need to have their upper
1221       // bound computed at Sema time based on the type constant.
1222       if (Proto.find('s') == std::string::npos) {
1223         ck = ClassB;
1224         if (R->getValueAsBit("isShift")) {
1225           shiftstr = ", true";
1226
1227           // Right shifts have an 'r' in the name, left shifts do not.
1228           if (name.find('r') != std::string::npos)
1229             rangestr = "l = 1; ";
1230         }
1231         rangestr += "u = RFT(TV" + shiftstr + ")";
1232       } else {
1233         rangestr = "u = " + utostr(RangeFromType(TypeVec[ti]));
1234       }
1235       // Make sure cases appear only once by uniquing them in a string map.
1236       namestr = MangleName(name, TypeVec[ti], ck);
1237       if (EmittedMap.count(namestr))
1238         continue;
1239       EmittedMap[namestr] = OpNone;
1240
1241       // Calculate the index of the immediate that should be range checked.
1242       unsigned immidx = 0;
1243
1244       // Builtins that return a struct of multiple vectors have an extra
1245       // leading arg for the struct return.
1246       if (Proto[0] >= '2' && Proto[0] <= '4')
1247         ++immidx;
1248
1249       // Add one to the index for each argument until we reach the immediate
1250       // to be checked.  Structs of vectors are passed as multiple arguments.
1251       for (unsigned ii = 1, ie = Proto.size(); ii != ie; ++ii) {
1252         switch (Proto[ii]) {
1253           default:  immidx += 1; break;
1254           case '2': immidx += 2; break;
1255           case '3': immidx += 3; break;
1256           case '4': immidx += 4; break;
1257           case 'i': ie = ii + 1; break;
1258         }
1259       }
1260       OS << "case ARM::BI__builtin_neon_" << MangleName(name, TypeVec[ti], ck)
1261          << ": i = " << immidx << "; " << rangestr << "; break;\n";
1262     }
1263   }
1264   OS << "#endif\n\n";
1265 }