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