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