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