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