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