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