Add operators for "_lane" variants of some saturating Neon multiply intrinsics
[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 // Use the vmovl builtin to sign-extend or zero-extend a vector.
512 static std::string Extend(StringRef typestr, const std::string &a) {
513   std::string s;
514   s = MangleName("vmovl", typestr, ClassS);
515   s += "(" + a + ")";
516   return s;
517 }
518
519 static std::string Duplicate(unsigned nElts, StringRef typestr,
520                              const std::string &a) {
521   std::string s;
522
523   s = "(" + TypeString('d', typestr) + "){ ";
524   for (unsigned i = 0; i != nElts; ++i) {
525     s += a;
526     if ((i + 1) < nElts)
527       s += ", ";
528   }
529   s += " }";
530
531   return s;
532 }
533
534 static std::string SplatLane(unsigned nElts, const std::string &vec,
535                              const std::string &lane) {
536   std::string s = "__builtin_shufflevector(" + vec + ", " + vec;
537   for (unsigned i = 0; i < nElts; ++i)
538     s += ", " + lane;
539   s += ")";
540   return s;
541 }
542
543 static unsigned GetNumElements(StringRef typestr, bool &quad) {
544   quad = false;
545   bool dummy = false;
546   char type = ClassifyType(typestr, quad, dummy, dummy);
547   unsigned nElts = 0;
548   switch (type) {
549   case 'c': nElts = 8; break;
550   case 's': nElts = 4; break;
551   case 'i': nElts = 2; break;
552   case 'l': nElts = 1; break;
553   case 'h': nElts = 4; break;
554   case 'f': nElts = 2; break;
555   default:
556     throw "unhandled type!";
557     break;
558   }
559   if (quad) nElts <<= 1;
560   return nElts;
561 }
562
563 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
564 static std::string GenOpString(OpKind op, const std::string &proto,
565                                StringRef typestr) {
566   bool quad;
567   unsigned nElts = GetNumElements(typestr, quad);
568
569   // If this builtin takes an immediate argument, we need to #define it rather
570   // than use a standard declaration, so that SemaChecking can range check
571   // the immediate passed by the user.
572   bool define = proto.find('i') != std::string::npos;
573
574   std::string ts = TypeString(proto[0], typestr);
575   std::string s;
576   if (op == OpHi || op == OpLo) {
577     s = "union { " + ts + " r; double d; } u; u.d = ";
578   } else if (!define) {
579     s = "return ";
580   }
581
582   switch(op) {
583   case OpAdd:
584     s += "__a + __b;";
585     break;
586   case OpAddl:
587     s += Extend(typestr, "__a") + " + " + Extend(typestr, "__b") + ";";
588     break;
589   case OpAddw:
590     s += "__a + " + Extend(typestr, "__b") + ";";
591     break;
592   case OpSub:
593     s += "__a - __b;";
594     break;
595   case OpSubl:
596     s += Extend(typestr, "__a") + " - " + Extend(typestr, "__b") + ";";
597     break;
598   case OpSubw:
599     s += "__a - " + Extend(typestr, "__b") + ";";
600     break;
601   case OpMulN:
602     s += "__a * " + Duplicate(nElts, typestr, "__b") + ";";
603     break;
604   case OpMulLane:
605     s += "__a * " + SplatLane(nElts, "__b", "__c") + ";";
606     break;
607   case OpMul:
608     s += "__a * __b;";
609     break;
610   case OpMullN:
611     s += Extend(typestr, "__a") + " * " +
612       Extend(typestr, Duplicate(nElts << (int)quad, typestr, "__b")) + ";";
613     break;
614   case OpMullLane:
615     s += Extend(typestr, "__a") + " * " +
616       Extend(typestr, SplatLane(nElts, "__b", "__c")) + ";";
617     break;
618   case OpMull:
619     s += Extend(typestr, "__a") + " * " + Extend(typestr, "__b") + ";";
620     break;
621   case OpMlaN:
622     s += "__a + (__b * " + Duplicate(nElts, typestr, "__c") + ");";
623     break;
624   case OpMlaLane:
625     s += "__a + (__b * " + SplatLane(nElts, "__c", "__d") + ");";
626     break;
627   case OpMla:
628     s += "__a + (__b * __c);";
629     break;
630   case OpMlalN:
631     s += "__a + (" + Extend(typestr, "__b") + " * " +
632       Extend(typestr, Duplicate(nElts, typestr, "__c")) + ");";
633     break;
634   case OpMlalLane:
635     s += "__a + (" + Extend(typestr, "__b") + " * " +
636       Extend(typestr, SplatLane(nElts, "__c", "__d")) + ");";
637     break;
638   case OpMlal:
639     s += "__a + (" + Extend(typestr, "__b") + " * " +
640       Extend(typestr, "__c") + ");";
641     break;
642   case OpMlsN:
643     s += "__a - (__b * " + Duplicate(nElts, typestr, "__c") + ");";
644     break;
645   case OpMlsLane:
646     s += "__a - (__b * " + SplatLane(nElts, "__c", "__d") + ");";
647     break;
648   case OpMls:
649     s += "__a - (__b * __c);";
650     break;
651   case OpMlslN:
652     s += "__a - (" + Extend(typestr, "__b") + " * " +
653       Extend(typestr, Duplicate(nElts, typestr, "__c")) + ");";
654     break;
655   case OpMlslLane:
656     s += "__a - (" + Extend(typestr, "__b") + " * " +
657       Extend(typestr, SplatLane(nElts, "__c", "__d")) + ");";
658     break;
659   case OpMlsl:
660     s += "__a - (" + Extend(typestr, "__b") + " * " +
661       Extend(typestr, "__c") + ");";
662     break;
663   case OpQDMullLane:
664     s += MangleName("vqdmull", typestr, ClassS) + "(__a, " +
665       SplatLane(nElts, "__b", "__c") + ");";
666     break;
667   case OpQDMlalLane:
668     s += MangleName("vqdmlal", typestr, ClassS) + "(__a, " +
669       SplatLane(nElts, "__b", "__c") + ");";
670     break;
671   case OpQDMlslLane:
672     s += MangleName("vqdmlsl", typestr, ClassS) + "(__a, " +
673       SplatLane(nElts, "__b", "__c") + ");";
674     break;
675   case OpQDMulhLane:
676     s += MangleName("vqdmulh", typestr, ClassS) + "(__a, " +
677       SplatLane(nElts, "__b", "__c") + ");";
678     break;
679   case OpQRDMulhLane:
680     s += MangleName("vqrdmulh", typestr, ClassS) + "(__a, " +
681       SplatLane(nElts, "__b", "__c") + ");";
682     break;
683   case OpEq:
684     s += "(" + ts + ")(__a == __b);";
685     break;
686   case OpGe:
687     s += "(" + ts + ")(__a >= __b);";
688     break;
689   case OpLe:
690     s += "(" + ts + ")(__a <= __b);";
691     break;
692   case OpGt:
693     s += "(" + ts + ")(__a > __b);";
694     break;
695   case OpLt:
696     s += "(" + ts + ")(__a < __b);";
697     break;
698   case OpNeg:
699     s += " -__a;";
700     break;
701   case OpNot:
702     s += " ~__a;";
703     break;
704   case OpAnd:
705     s += "__a & __b;";
706     break;
707   case OpOr:
708     s += "__a | __b;";
709     break;
710   case OpXor:
711     s += "__a ^ __b;";
712     break;
713   case OpAndNot:
714     s += "__a & ~__b;";
715     break;
716   case OpOrNot:
717     s += "__a | ~__b;";
718     break;
719   case OpCast:
720     s += "(" + ts + ")__a;";
721     break;
722   case OpConcat:
723     s += "(" + ts + ")__builtin_shufflevector((int64x1_t)__a";
724     s += ", (int64x1_t)__b, 0, 1);";
725     break;
726   case OpHi:
727     s += "(((float64x2_t)__a)[1]);";
728     break;
729   case OpLo:
730     s += "(((float64x2_t)__a)[0]);";
731     break;
732   case OpDup:
733     s += Duplicate(nElts, typestr, "__a") + ";";
734     break;
735   case OpDupLane:
736     s += SplatLane(nElts, "__a", "__b") + ";";
737     break;
738   case OpSelect:
739     // ((0 & 1) | (~0 & 2))
740     s += "(" + ts + ")";
741     ts = TypeString(proto[1], typestr);
742     s += "((__a & (" + ts + ")__b) | ";
743     s += "(~__a & (" + ts + ")__c));";
744     break;
745   case OpRev16:
746     s += "__builtin_shufflevector(__a, __a";
747     for (unsigned i = 2; i <= nElts; i += 2)
748       for (unsigned j = 0; j != 2; ++j)
749         s += ", " + utostr(i - j - 1);
750     s += ");";
751     break;
752   case OpRev32: {
753     unsigned WordElts = nElts >> (1 + (int)quad);
754     s += "__builtin_shufflevector(__a, __a";
755     for (unsigned i = WordElts; i <= nElts; i += WordElts)
756       for (unsigned j = 0; j != WordElts; ++j)
757         s += ", " + utostr(i - j - 1);
758     s += ");";
759     break;
760   }
761   case OpRev64: {
762     unsigned DblWordElts = nElts >> (int)quad;
763     s += "__builtin_shufflevector(__a, __a";
764     for (unsigned i = DblWordElts; i <= nElts; i += DblWordElts)
765       for (unsigned j = 0; j != DblWordElts; ++j)
766         s += ", " + utostr(i - j - 1);
767     s += ");";
768     break;
769   }
770   case OpAbdl: {
771     std::string abd = MangleName("vabd", typestr, ClassS) + "(__a, __b)";
772     if (typestr[0] != 'U') {
773       // vabd results are always unsigned and must be zero-extended.
774       std::string utype = "U" + typestr.str();
775       s += "(" + TypeString(proto[0], typestr) + ")";
776       abd = "(" + TypeString('d', utype) + ")" + abd;
777       s += Extend(utype, abd) + ";";
778     } else {
779       s += Extend(typestr, abd) + ";";
780     }
781     break;
782   }
783   case OpAba:
784     s += "__a + " + MangleName("vabd", typestr, ClassS) + "(__b, __c);";
785     break;
786   case OpAbal: {
787     s += "__a + ";
788     std::string abd = MangleName("vabd", typestr, ClassS) + "(__b, __c)";
789     if (typestr[0] != 'U') {
790       // vabd results are always unsigned and must be zero-extended.
791       std::string utype = "U" + typestr.str();
792       s += "(" + TypeString(proto[0], typestr) + ")";
793       abd = "(" + TypeString('d', utype) + ")" + abd;
794       s += Extend(utype, abd) + ";";
795     } else {
796       s += Extend(typestr, abd) + ";";
797     }
798     break;
799   }
800   default:
801     throw "unknown OpKind!";
802     break;
803   }
804   if (op == OpHi || op == OpLo) {
805     if (!define)
806       s += " return";
807     s += " u.r;";
808   }
809   return s;
810 }
811
812 static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
813   unsigned mod = proto[0];
814   unsigned ret = 0;
815
816   if (mod == 'v' || mod == 'f')
817     mod = proto[1];
818
819   bool quad = false;
820   bool poly = false;
821   bool usgn = false;
822   bool scal = false;
823   bool cnst = false;
824   bool pntr = false;
825
826   // Base type to get the type string for.
827   char type = ClassifyType(typestr, quad, poly, usgn);
828
829   // Based on the modifying character, change the type and width if necessary.
830   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
831
832   if (usgn)
833     ret |= 0x08;
834   if (quad && proto[1] != 'g')
835     ret |= 0x10;
836
837   switch (type) {
838     case 'c':
839       ret |= poly ? 5 : 0;
840       break;
841     case 's':
842       ret |= poly ? 6 : 1;
843       break;
844     case 'i':
845       ret |= 2;
846       break;
847     case 'l':
848       ret |= 3;
849       break;
850     case 'h':
851       ret |= 7;
852       break;
853     case 'f':
854       ret |= 4;
855       break;
856     default:
857       throw "unhandled type!";
858       break;
859   }
860   return ret;
861 }
862
863 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
864 static std::string GenBuiltin(const std::string &name, const std::string &proto,
865                               StringRef typestr, ClassKind ck) {
866   std::string s;
867
868   // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
869   // sret-like argument.
870   bool sret = (proto[0] >= '2' && proto[0] <= '4');
871
872   // If this builtin takes an immediate argument, we need to #define it rather
873   // than use a standard declaration, so that SemaChecking can range check
874   // the immediate passed by the user.
875   bool define = proto.find('i') != std::string::npos;
876
877   // Check if the prototype has a scalar operand with the type of the vector
878   // elements.  If not, bitcasting the args will take care of arg checking.
879   // The actual signedness etc. will be taken care of with special enums.
880   if (proto.find('s') == std::string::npos)
881     ck = ClassB;
882
883   if (proto[0] != 'v') {
884     std::string ts = TypeString(proto[0], typestr);
885
886     if (define) {
887       if (sret)
888         s += ts + " r; ";
889       else
890         s += "(" + ts + ")";
891     } else if (sret) {
892       s += ts + " r; ";
893     } else {
894       s += "return (" + ts + ")";
895     }
896   }
897
898   bool splat = proto.find('a') != std::string::npos;
899
900   s += "__builtin_neon_";
901   if (splat) {
902     // Call the non-splat builtin: chop off the "_n" suffix from the name.
903     std::string vname(name, 0, name.size()-2);
904     s += MangleName(vname, typestr, ck);
905   } else {
906     s += MangleName(name, typestr, ck);
907   }
908   s += "(";
909
910   // Pass the address of the return variable as the first argument to sret-like
911   // builtins.
912   if (sret)
913     s += "&r, ";
914
915   char arg = 'a';
916   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
917     std::string args = std::string(&arg, 1);
918
919     // Use the local temporaries instead of the macro arguments.
920     args = "__" + args;
921
922     bool argQuad = false;
923     bool argPoly = false;
924     bool argUsgn = false;
925     bool argScalar = false;
926     bool dummy = false;
927     char argType = ClassifyType(typestr, argQuad, argPoly, argUsgn);
928     argType = ModType(proto[i], argType, argQuad, argPoly, argUsgn, argScalar,
929                       dummy, dummy);
930
931     // Handle multiple-vector values specially, emitting each subvector as an
932     // argument to the __builtin.
933     if (proto[i] >= '2' && proto[i] <= '4') {
934       // Check if an explicit cast is needed.
935       if (argType != 'c' || argPoly || argUsgn)
936         args = (argQuad ? "(int8x16_t)" : "(int8x8_t)") + args;
937
938       for (unsigned vi = 0, ve = proto[i] - '0'; vi != ve; ++vi) {
939         s += args + ".val[" + utostr(vi) + "]";
940         if ((vi + 1) < ve)
941           s += ", ";
942       }
943       if ((i + 1) < e)
944         s += ", ";
945
946       continue;
947     }
948
949     if (splat && (i + 1) == e)
950       args = Duplicate(GetNumElements(typestr, argQuad), typestr, args);
951
952     // Check if an explicit cast is needed.
953     if ((splat || !argScalar) &&
954         ((ck == ClassB && argType != 'c') || argPoly || argUsgn)) {
955       std::string argTypeStr = "c";
956       if (ck != ClassB)
957         argTypeStr = argType;
958       if (argQuad)
959         argTypeStr = "Q" + argTypeStr;
960       args = "(" + TypeString('d', argTypeStr) + ")" + args;
961     }
962
963     s += args;
964     if ((i + 1) < e)
965       s += ", ";
966   }
967
968   // Extra constant integer to hold type class enum for this function, e.g. s8
969   if (ck == ClassB)
970     s += ", " + utostr(GetNeonEnum(proto, typestr));
971
972   s += ");";
973
974   if (proto[0] != 'v' && sret) {
975     if (define)
976       s += " r;";
977     else
978       s += " return r;";
979   }
980   return s;
981 }
982
983 static std::string GenBuiltinDef(const std::string &name,
984                                  const std::string &proto,
985                                  StringRef typestr, ClassKind ck) {
986   std::string s("BUILTIN(__builtin_neon_");
987
988   // If all types are the same size, bitcasting the args will take care
989   // of arg checking.  The actual signedness etc. will be taken care of with
990   // special enums.
991   if (proto.find('s') == std::string::npos)
992     ck = ClassB;
993
994   s += MangleName(name, typestr, ck);
995   s += ", \"";
996
997   for (unsigned i = 0, e = proto.size(); i != e; ++i)
998     s += BuiltinTypeString(proto[i], typestr, ck, i == 0);
999
1000   // Extra constant integer to hold type class enum for this function, e.g. s8
1001   if (ck == ClassB)
1002     s += "i";
1003
1004   s += "\", \"n\")";
1005   return s;
1006 }
1007
1008 static std::string GenIntrinsic(const std::string &name,
1009                                 const std::string &proto,
1010                                 StringRef outTypeStr, StringRef inTypeStr,
1011                                 OpKind kind, ClassKind classKind) {
1012   assert(!proto.empty() && "");
1013   bool define = proto.find('i') != std::string::npos;
1014   std::string s;
1015
1016   // static always inline + return type
1017   if (define)
1018     s += "#define ";
1019   else
1020     s += "__ai " + TypeString(proto[0], outTypeStr) + " ";
1021
1022   // Function name with type suffix
1023   std::string mangledName = MangleName(name, outTypeStr, ClassS);
1024   if (outTypeStr != inTypeStr) {
1025     // If the input type is different (e.g., for vreinterpret), append a suffix
1026     // for the input type.  String off a "Q" (quad) prefix so that MangleName
1027     // does not insert another "q" in the name.
1028     unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1029     StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1030     mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1031   }
1032   s += mangledName;
1033
1034   // Function arguments
1035   s += GenArgs(proto, inTypeStr);
1036
1037   // Definition.
1038   if (define) {
1039     s += " __extension__ ({ \\\n  ";
1040     s += GenMacroLocals(proto, inTypeStr);
1041   } else {
1042     s += " { \\\n  ";
1043   }
1044
1045   if (kind != OpNone)
1046     s += GenOpString(kind, proto, outTypeStr);
1047   else
1048     s += GenBuiltin(name, proto, outTypeStr, classKind);
1049   if (define)
1050     s += " })";
1051   else
1052     s += " }";
1053   s += "\n";
1054   return s;
1055 }
1056
1057 /// run - Read the records in arm_neon.td and output arm_neon.h.  arm_neon.h
1058 /// is comprised of type definitions and function declarations.
1059 void NeonEmitter::run(raw_ostream &OS) {
1060   EmitSourceFileHeader("ARM NEON Header", OS);
1061
1062   // FIXME: emit license into file?
1063
1064   OS << "#ifndef __ARM_NEON_H\n";
1065   OS << "#define __ARM_NEON_H\n\n";
1066
1067   OS << "#ifndef __ARM_NEON__\n";
1068   OS << "#error \"NEON support not enabled\"\n";
1069   OS << "#endif\n\n";
1070
1071   OS << "#include <stdint.h>\n\n";
1072
1073   // Emit NEON-specific scalar typedefs.
1074   OS << "typedef float float32_t;\n";
1075   OS << "typedef int8_t poly8_t;\n";
1076   OS << "typedef int16_t poly16_t;\n";
1077   OS << "typedef uint16_t float16_t;\n";
1078
1079   // Emit Neon vector typedefs.
1080   std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
1081   SmallVector<StringRef, 24> TDTypeVec;
1082   ParseTypes(0, TypedefTypes, TDTypeVec);
1083
1084   // Emit vector typedefs.
1085   for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1086     bool dummy, quad = false, poly = false;
1087     (void) ClassifyType(TDTypeVec[i], quad, poly, dummy);
1088     if (poly)
1089       OS << "typedef __attribute__((neon_polyvector_type(";
1090     else
1091       OS << "typedef __attribute__((neon_vector_type(";
1092
1093     unsigned nElts = GetNumElements(TDTypeVec[i], quad);
1094     OS << utostr(nElts) << "))) ";
1095     if (nElts < 10)
1096       OS << " ";
1097
1098     OS << TypeString('s', TDTypeVec[i]);
1099     OS << " " << TypeString('d', TDTypeVec[i]) << ";\n";
1100   }
1101   OS << "\n";
1102   OS << "typedef __attribute__((__vector_size__(8)))  "
1103     "double float64x1_t;\n";
1104   OS << "typedef __attribute__((__vector_size__(16))) "
1105     "double float64x2_t;\n";
1106   OS << "\n";
1107
1108   // Emit struct typedefs.
1109   for (unsigned vi = 2; vi != 5; ++vi) {
1110     for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1111       std::string ts = TypeString('d', TDTypeVec[i]);
1112       std::string vs = TypeString('0' + vi, TDTypeVec[i]);
1113       OS << "typedef struct " << vs << " {\n";
1114       OS << "  " << ts << " val";
1115       OS << "[" << utostr(vi) << "]";
1116       OS << ";\n} ";
1117       OS << vs << ";\n\n";
1118     }
1119   }
1120
1121   OS << "#define __ai static __attribute__((__always_inline__))\n\n";
1122
1123   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1124
1125   // Emit vmovl and vabd intrinsics first so they can be used by other
1126   // intrinsics.  (Some of the saturating multiply instructions are also
1127   // used to implement the corresponding "_lane" variants, but tablegen
1128   // sorts the records into alphabetical order so that the "_lane" variants
1129   // come after the intrinsics they use.)
1130   emitIntrinsic(OS, Records.getDef("VMOVL"));
1131   emitIntrinsic(OS, Records.getDef("VABD"));
1132
1133   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1134     Record *R = RV[i];
1135     if (R->getName() != "VMOVL" && R->getName() != "VABD")
1136       emitIntrinsic(OS, R);
1137   }
1138
1139   OS << "#undef __ai\n\n";
1140   OS << "#endif /* __ARM_NEON_H */\n";
1141 }
1142
1143 /// emitIntrinsic - Write out the arm_neon.h header file definitions for the
1144 /// intrinsics specified by record R.
1145 void NeonEmitter::emitIntrinsic(raw_ostream &OS, Record *R) {
1146   std::string name = R->getValueAsString("Name");
1147   std::string Proto = R->getValueAsString("Prototype");
1148   std::string Types = R->getValueAsString("Types");
1149
1150   SmallVector<StringRef, 16> TypeVec;
1151   ParseTypes(R, Types, TypeVec);
1152
1153   OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1154
1155   ClassKind classKind = ClassNone;
1156   if (R->getSuperClasses().size() >= 2)
1157     classKind = ClassMap[R->getSuperClasses()[1]];
1158   if (classKind == ClassNone && kind == OpNone)
1159     throw TGError(R->getLoc(), "Builtin has no class kind");
1160
1161   for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1162     if (kind == OpReinterpret) {
1163       bool outQuad = false;
1164       bool dummy = false;
1165       (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1166       for (unsigned srcti = 0, srcte = TypeVec.size();
1167            srcti != srcte; ++srcti) {
1168         bool inQuad = false;
1169         (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1170         if (srcti == ti || inQuad != outQuad)
1171           continue;
1172         OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[srcti],
1173                            OpCast, ClassS);
1174       }
1175     } else {
1176       OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[ti],
1177                          kind, classKind);
1178     }
1179   }
1180   OS << "\n";
1181 }
1182
1183 static unsigned RangeFromType(StringRef typestr) {
1184   // base type to get the type string for.
1185   bool quad = false, dummy = false;
1186   char type = ClassifyType(typestr, quad, dummy, dummy);
1187
1188   switch (type) {
1189     case 'c':
1190       return (8 << (int)quad) - 1;
1191     case 'h':
1192     case 's':
1193       return (4 << (int)quad) - 1;
1194     case 'f':
1195     case 'i':
1196       return (2 << (int)quad) - 1;
1197     case 'l':
1198       return (1 << (int)quad) - 1;
1199     default:
1200       throw "unhandled type!";
1201       break;
1202   }
1203   assert(0 && "unreachable");
1204   return 0;
1205 }
1206
1207 /// runHeader - Emit a file with sections defining:
1208 /// 1. the NEON section of BuiltinsARM.def.
1209 /// 2. the SemaChecking code for the type overload checking.
1210 /// 3. the SemaChecking code for validation of intrinsic immedate arguments.
1211 void NeonEmitter::runHeader(raw_ostream &OS) {
1212   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1213
1214   StringMap<OpKind> EmittedMap;
1215
1216   // Generate BuiltinsARM.def for NEON
1217   OS << "#ifdef GET_NEON_BUILTINS\n";
1218   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1219     Record *R = RV[i];
1220     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1221     if (k != OpNone)
1222       continue;
1223
1224     std::string Proto = R->getValueAsString("Prototype");
1225
1226     // Functions with 'a' (the splat code) in the type prototype should not get
1227     // their own builtin as they use the non-splat variant.
1228     if (Proto.find('a') != std::string::npos)
1229       continue;
1230
1231     std::string Types = R->getValueAsString("Types");
1232     SmallVector<StringRef, 16> TypeVec;
1233     ParseTypes(R, Types, TypeVec);
1234
1235     if (R->getSuperClasses().size() < 2)
1236       throw TGError(R->getLoc(), "Builtin has no class kind");
1237
1238     std::string name = R->getValueAsString("Name");
1239     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1240
1241     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1242       // Generate the BuiltinsARM.def declaration for this builtin, ensuring
1243       // that each unique BUILTIN() macro appears only once in the output
1244       // stream.
1245       std::string bd = GenBuiltinDef(name, Proto, TypeVec[ti], ck);
1246       if (EmittedMap.count(bd))
1247         continue;
1248
1249       EmittedMap[bd] = OpNone;
1250       OS << bd << "\n";
1251     }
1252   }
1253   OS << "#endif\n\n";
1254
1255   // Generate the overloaded type checking code for SemaChecking.cpp
1256   OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1257   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1258     Record *R = RV[i];
1259     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1260     if (k != OpNone)
1261       continue;
1262
1263     std::string Proto = R->getValueAsString("Prototype");
1264     std::string Types = R->getValueAsString("Types");
1265     std::string name = R->getValueAsString("Name");
1266
1267     // Functions with 'a' (the splat code) in the type prototype should not get
1268     // their own builtin as they use the non-splat variant.
1269     if (Proto.find('a') != std::string::npos)
1270       continue;
1271
1272     // Functions which have a scalar argument cannot be overloaded, no need to
1273     // check them if we are emitting the type checking code.
1274     if (Proto.find('s') != std::string::npos)
1275       continue;
1276
1277     SmallVector<StringRef, 16> TypeVec;
1278     ParseTypes(R, Types, TypeVec);
1279
1280     if (R->getSuperClasses().size() < 2)
1281       throw TGError(R->getLoc(), "Builtin has no class kind");
1282
1283     int si = -1, qi = -1;
1284     unsigned mask = 0, qmask = 0;
1285     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1286       // Generate the switch case(s) for this builtin for the type validation.
1287       bool quad = false, poly = false, usgn = false;
1288       (void) ClassifyType(TypeVec[ti], quad, poly, usgn);
1289
1290       if (quad) {
1291         qi = ti;
1292         qmask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1293       } else {
1294         si = ti;
1295         mask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1296       }
1297     }
1298     if (mask)
1299       OS << "case ARM::BI__builtin_neon_"
1300          << MangleName(name, TypeVec[si], ClassB)
1301          << ": mask = " << "0x" << utohexstr(mask) << "; break;\n";
1302     if (qmask)
1303       OS << "case ARM::BI__builtin_neon_"
1304          << MangleName(name, TypeVec[qi], ClassB)
1305          << ": mask = " << "0x" << utohexstr(qmask) << "; break;\n";
1306   }
1307   OS << "#endif\n\n";
1308
1309   // Generate the intrinsic range checking code for shift/lane immediates.
1310   OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
1311   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1312     Record *R = RV[i];
1313
1314     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1315     if (k != OpNone)
1316       continue;
1317
1318     std::string name = R->getValueAsString("Name");
1319     std::string Proto = R->getValueAsString("Prototype");
1320     std::string Types = R->getValueAsString("Types");
1321
1322     // Functions with 'a' (the splat code) in the type prototype should not get
1323     // their own builtin as they use the non-splat variant.
1324     if (Proto.find('a') != std::string::npos)
1325       continue;
1326
1327     // Functions which do not have an immediate do not need to have range
1328     // checking code emitted.
1329     if (Proto.find('i') == std::string::npos)
1330       continue;
1331
1332     SmallVector<StringRef, 16> TypeVec;
1333     ParseTypes(R, Types, TypeVec);
1334
1335     if (R->getSuperClasses().size() < 2)
1336       throw TGError(R->getLoc(), "Builtin has no class kind");
1337
1338     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1339
1340     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1341       std::string namestr, shiftstr, rangestr;
1342
1343       // Builtins which are overloaded by type will need to have their upper
1344       // bound computed at Sema time based on the type constant.
1345       if (Proto.find('s') == std::string::npos) {
1346         ck = ClassB;
1347         if (R->getValueAsBit("isShift")) {
1348           shiftstr = ", true";
1349
1350           // Right shifts have an 'r' in the name, left shifts do not.
1351           if (name.find('r') != std::string::npos)
1352             rangestr = "l = 1; ";
1353         }
1354         rangestr += "u = RFT(TV" + shiftstr + ")";
1355       } else {
1356         rangestr = "u = " + utostr(RangeFromType(TypeVec[ti]));
1357       }
1358       // Make sure cases appear only once by uniquing them in a string map.
1359       namestr = MangleName(name, TypeVec[ti], ck);
1360       if (EmittedMap.count(namestr))
1361         continue;
1362       EmittedMap[namestr] = OpNone;
1363
1364       // Calculate the index of the immediate that should be range checked.
1365       unsigned immidx = 0;
1366
1367       // Builtins that return a struct of multiple vectors have an extra
1368       // leading arg for the struct return.
1369       if (Proto[0] >= '2' && Proto[0] <= '4')
1370         ++immidx;
1371
1372       // Add one to the index for each argument until we reach the immediate
1373       // to be checked.  Structs of vectors are passed as multiple arguments.
1374       for (unsigned ii = 1, ie = Proto.size(); ii != ie; ++ii) {
1375         switch (Proto[ii]) {
1376           default:  immidx += 1; break;
1377           case '2': immidx += 2; break;
1378           case '3': immidx += 3; break;
1379           case '4': immidx += 4; break;
1380           case 'i': ie = ii + 1; break;
1381         }
1382       }
1383       OS << "case ARM::BI__builtin_neon_" << MangleName(name, TypeVec[ti], ck)
1384          << ": i = " << immidx << "; " << rangestr << "; break;\n";
1385     }
1386   }
1387   OS << "#endif\n\n";
1388 }