Add a Neon intrinsic test generator.
[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.  A complete set of tests
22 // for Neon intrinsics can be generated by calling the runTests() entry point.
23 //
24 //===----------------------------------------------------------------------===//
25
26 #include "NeonEmitter.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include <string>
31
32 using namespace llvm;
33
34 /// ParseTypes - break down a string such as "fQf" into a vector of StringRefs,
35 /// which each StringRef representing a single type declared in the string.
36 /// for "fQf" we would end up with 2 StringRefs, "f", and "Qf", representing
37 /// 2xfloat and 4xfloat respectively.
38 static void ParseTypes(Record *r, std::string &s,
39                        SmallVectorImpl<StringRef> &TV) {
40   const char *data = s.data();
41   int len = 0;
42
43   for (unsigned i = 0, e = s.size(); i != e; ++i, ++len) {
44     if (data[len] == 'P' || data[len] == 'Q' || data[len] == 'U')
45       continue;
46
47     switch (data[len]) {
48       case 'c':
49       case 's':
50       case 'i':
51       case 'l':
52       case 'h':
53       case 'f':
54         break;
55       default:
56         throw TGError(r->getLoc(),
57                       "Unexpected letter: " + std::string(data + len, 1));
58         break;
59     }
60     TV.push_back(StringRef(data, len + 1));
61     data += len + 1;
62     len = -1;
63   }
64 }
65
66 /// Widen - Convert a type code into the next wider type.  char -> short,
67 /// short -> int, etc.
68 static char Widen(const char t) {
69   switch (t) {
70     case 'c':
71       return 's';
72     case 's':
73       return 'i';
74     case 'i':
75       return 'l';
76     default: throw "unhandled type in widen!";
77   }
78   return '\0';
79 }
80
81 /// Narrow - Convert a type code into the next smaller type.  short -> char,
82 /// float -> half float, etc.
83 static char Narrow(const char t) {
84   switch (t) {
85     case 's':
86       return 'c';
87     case 'i':
88       return 's';
89     case 'l':
90       return 'i';
91     case 'f':
92       return 'h';
93     default: throw "unhandled type in narrow!";
94   }
95   return '\0';
96 }
97
98 /// For a particular StringRef, return the base type code, and whether it has
99 /// the quad-vector, polynomial, or unsigned modifiers set.
100 static char ClassifyType(StringRef ty, bool &quad, bool &poly, bool &usgn) {
101   unsigned off = 0;
102
103   // remember quad.
104   if (ty[off] == 'Q') {
105     quad = true;
106     ++off;
107   }
108
109   // remember poly.
110   if (ty[off] == 'P') {
111     poly = true;
112     ++off;
113   }
114
115   // remember unsigned.
116   if (ty[off] == 'U') {
117     usgn = true;
118     ++off;
119   }
120
121   // base type to get the type string for.
122   return ty[off];
123 }
124
125 /// ModType - Transform a type code and its modifiers based on a mod code. The
126 /// mod code definitions may be found at the top of arm_neon.td.
127 static char ModType(const char mod, char type, bool &quad, bool &poly,
128                     bool &usgn, bool &scal, bool &cnst, bool &pntr) {
129   switch (mod) {
130     case 't':
131       if (poly) {
132         poly = false;
133         usgn = true;
134       }
135       break;
136     case 'u':
137       usgn = true;
138       poly = false;
139       if (type == 'f')
140         type = 'i';
141       break;
142     case 'x':
143       usgn = false;
144       poly = false;
145       if (type == 'f')
146         type = 'i';
147       break;
148     case 'f':
149       if (type == 'h')
150         quad = true;
151       type = 'f';
152       usgn = false;
153       break;
154     case 'g':
155       quad = false;
156       break;
157     case 'w':
158       type = Widen(type);
159       quad = true;
160       break;
161     case 'n':
162       type = Widen(type);
163       break;
164     case 'i':
165       type = 'i';
166       scal = true;
167       break;
168     case 'l':
169       type = 'l';
170       scal = true;
171       usgn = true;
172       break;
173     case 's':
174     case 'a':
175       scal = true;
176       break;
177     case 'k':
178       quad = true;
179       break;
180     case 'c':
181       cnst = true;
182     case 'p':
183       pntr = true;
184       scal = true;
185       break;
186     case 'h':
187       type = Narrow(type);
188       if (type == 'h')
189         quad = false;
190       break;
191     case 'e':
192       type = Narrow(type);
193       usgn = true;
194       break;
195     default:
196       break;
197   }
198   return type;
199 }
200
201 /// TypeString - for a modifier and type, generate the name of the typedef for
202 /// that type.  QUc -> uint8x8_t.
203 static std::string TypeString(const char mod, StringRef typestr) {
204   bool quad = false;
205   bool poly = false;
206   bool usgn = false;
207   bool scal = false;
208   bool cnst = false;
209   bool pntr = false;
210
211   if (mod == 'v')
212     return "void";
213   if (mod == 'i')
214     return "int";
215
216   // base type to get the type string for.
217   char type = ClassifyType(typestr, quad, poly, usgn);
218
219   // Based on the modifying character, change the type and width if necessary.
220   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
221
222   SmallString<128> s;
223
224   if (usgn)
225     s.push_back('u');
226
227   switch (type) {
228     case 'c':
229       s += poly ? "poly8" : "int8";
230       if (scal)
231         break;
232       s += quad ? "x16" : "x8";
233       break;
234     case 's':
235       s += poly ? "poly16" : "int16";
236       if (scal)
237         break;
238       s += quad ? "x8" : "x4";
239       break;
240     case 'i':
241       s += "int32";
242       if (scal)
243         break;
244       s += quad ? "x4" : "x2";
245       break;
246     case 'l':
247       s += "int64";
248       if (scal)
249         break;
250       s += quad ? "x2" : "x1";
251       break;
252     case 'h':
253       s += "float16";
254       if (scal)
255         break;
256       s += quad ? "x8" : "x4";
257       break;
258     case 'f':
259       s += "float32";
260       if (scal)
261         break;
262       s += quad ? "x4" : "x2";
263       break;
264     default:
265       throw "unhandled type!";
266       break;
267   }
268
269   if (mod == '2')
270     s += "x2";
271   if (mod == '3')
272     s += "x3";
273   if (mod == '4')
274     s += "x4";
275
276   // Append _t, finishing the type string typedef type.
277   s += "_t";
278
279   if (cnst)
280     s += " const";
281
282   if (pntr)
283     s += " *";
284
285   return s.str();
286 }
287
288 /// BuiltinTypeString - for a modifier and type, generate the clang
289 /// BuiltinsARM.def prototype code for the function.  See the top of clang's
290 /// Builtins.def for a description of the type strings.
291 static std::string BuiltinTypeString(const char mod, StringRef typestr,
292                                      ClassKind ck, bool ret) {
293   bool quad = false;
294   bool poly = false;
295   bool usgn = false;
296   bool scal = false;
297   bool cnst = false;
298   bool pntr = false;
299
300   if (mod == 'v')
301     return "v"; // void
302   if (mod == 'i')
303     return "i"; // int
304
305   // base type to get the type string for.
306   char type = ClassifyType(typestr, quad, poly, usgn);
307
308   // Based on the modifying character, change the type and width if necessary.
309   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
310
311   // All pointers are void* pointers.  Change type to 'v' now.
312   if (pntr) {
313     usgn = false;
314     poly = false;
315     type = 'v';
316   }
317   // Treat half-float ('h') types as unsigned short ('s') types.
318   if (type == 'h') {
319     type = 's';
320     usgn = true;
321   }
322   usgn = usgn | poly | ((ck == ClassI || ck == ClassW) && scal && type != 'f');
323
324   if (scal) {
325     SmallString<128> s;
326
327     if (usgn)
328       s.push_back('U');
329     else if (type == 'c')
330       s.push_back('S'); // make chars explicitly signed
331
332     if (type == 'l') // 64-bit long
333       s += "LLi";
334     else
335       s.push_back(type);
336
337     if (cnst)
338       s.push_back('C');
339     if (pntr)
340       s.push_back('*');
341     return s.str();
342   }
343
344   // Since the return value must be one type, return a vector type of the
345   // appropriate width which we will bitcast.  An exception is made for
346   // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
347   // fashion, storing them to a pointer arg.
348   if (ret) {
349     if (mod >= '2' && mod <= '4')
350       return "vv*"; // void result with void* first argument
351     if (mod == 'f' || (ck != ClassB && type == 'f'))
352       return quad ? "V4f" : "V2f";
353     if (ck != ClassB && type == 's')
354       return quad ? "V8s" : "V4s";
355     if (ck != ClassB && type == 'i')
356       return quad ? "V4i" : "V2i";
357     if (ck != ClassB && type == 'l')
358       return quad ? "V2LLi" : "V1LLi";
359
360     return quad ? "V16Sc" : "V8Sc";
361   }
362
363   // Non-return array types are passed as individual vectors.
364   if (mod == '2')
365     return quad ? "V16ScV16Sc" : "V8ScV8Sc";
366   if (mod == '3')
367     return quad ? "V16ScV16ScV16Sc" : "V8ScV8ScV8Sc";
368   if (mod == '4')
369     return quad ? "V16ScV16ScV16ScV16Sc" : "V8ScV8ScV8ScV8Sc";
370
371   if (mod == 'f' || (ck != ClassB && type == 'f'))
372     return quad ? "V4f" : "V2f";
373   if (ck != ClassB && type == 's')
374     return quad ? "V8s" : "V4s";
375   if (ck != ClassB && type == 'i')
376     return quad ? "V4i" : "V2i";
377   if (ck != ClassB && type == 'l')
378     return quad ? "V2LLi" : "V1LLi";
379
380   return quad ? "V16Sc" : "V8Sc";
381 }
382
383 /// MangleName - Append a type or width suffix to a base neon function name,
384 /// and insert a 'q' in the appropriate location if the operation works on
385 /// 128b rather than 64b.   E.g. turn "vst2_lane" into "vst2q_lane_f32", etc.
386 static std::string MangleName(const std::string &name, StringRef typestr,
387                               ClassKind ck) {
388   if (name == "vcvt_f32_f16")
389     return name;
390
391   bool quad = false;
392   bool poly = false;
393   bool usgn = false;
394   char type = ClassifyType(typestr, quad, poly, usgn);
395
396   std::string s = name;
397
398   switch (type) {
399   case 'c':
400     switch (ck) {
401     case ClassS: s += poly ? "_p8" : usgn ? "_u8" : "_s8"; break;
402     case ClassI: s += "_i8"; break;
403     case ClassW: s += "_8"; break;
404     default: break;
405     }
406     break;
407   case 's':
408     switch (ck) {
409     case ClassS: s += poly ? "_p16" : usgn ? "_u16" : "_s16"; break;
410     case ClassI: s += "_i16"; break;
411     case ClassW: s += "_16"; break;
412     default: break;
413     }
414     break;
415   case 'i':
416     switch (ck) {
417     case ClassS: s += usgn ? "_u32" : "_s32"; break;
418     case ClassI: s += "_i32"; break;
419     case ClassW: s += "_32"; break;
420     default: break;
421     }
422     break;
423   case 'l':
424     switch (ck) {
425     case ClassS: s += usgn ? "_u64" : "_s64"; break;
426     case ClassI: s += "_i64"; break;
427     case ClassW: s += "_64"; break;
428     default: break;
429     }
430     break;
431   case 'h':
432     switch (ck) {
433     case ClassS:
434     case ClassI: s += "_f16"; break;
435     case ClassW: s += "_16"; break;
436     default: break;
437     }
438     break;
439   case 'f':
440     switch (ck) {
441     case ClassS:
442     case ClassI: s += "_f32"; break;
443     case ClassW: s += "_32"; break;
444     default: break;
445     }
446     break;
447   default:
448     throw "unhandled type!";
449     break;
450   }
451   if (ck == ClassB)
452     s += "_v";
453
454   // Insert a 'q' before the first '_' character so that it ends up before
455   // _lane or _n on vector-scalar operations.
456   if (quad) {
457     size_t pos = s.find('_');
458     s = s.insert(pos, "q");
459   }
460   return s;
461 }
462
463 // Generate the string "(argtype a, argtype b, ...)"
464 static std::string GenArgs(const std::string &proto, StringRef typestr) {
465   bool define = proto.find('i') != std::string::npos;
466   char arg = 'a';
467
468   std::string s;
469   s += "(";
470
471   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
472     if (define) {
473       // Immediate macro arguments are used directly instead of being assigned
474       // to local temporaries; prepend an underscore prefix to make their
475       // names consistent with the local temporaries.
476       if (proto[i] == 'i')
477         s += "__";
478     } else {
479       s += TypeString(proto[i], typestr) + " __";
480     }
481     s.push_back(arg);
482     if ((i + 1) < e)
483       s += ", ";
484   }
485
486   s += ")";
487   return s;
488 }
489
490 // Macro arguments are not type-checked like inline function arguments, so
491 // assign them to local temporaries to get the right type checking.
492 static std::string GenMacroLocals(const std::string &proto, StringRef typestr) {
493   char arg = 'a';
494   std::string s;
495
496   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
497     // Do not create a temporary for an immediate argument.
498     // That would defeat the whole point of using a macro!
499     if (proto[i] == 'i') continue;
500
501     s += TypeString(proto[i], typestr) + " __";
502     s.push_back(arg);
503     s += " = (";
504     s.push_back(arg);
505     s += "); ";
506   }
507
508   s += "\\\n  ";
509   return s;
510 }
511
512 // Use the vmovl builtin to sign-extend or zero-extend a vector.
513 static std::string Extend(StringRef typestr, const std::string &a) {
514   std::string s;
515   s = MangleName("vmovl", typestr, ClassS);
516   s += "(" + a + ")";
517   return s;
518 }
519
520 static std::string Duplicate(unsigned nElts, StringRef typestr,
521                              const std::string &a) {
522   std::string s;
523
524   s = "(" + TypeString('d', typestr) + "){ ";
525   for (unsigned i = 0; i != nElts; ++i) {
526     s += a;
527     if ((i + 1) < nElts)
528       s += ", ";
529   }
530   s += " }";
531
532   return s;
533 }
534
535 static std::string SplatLane(unsigned nElts, const std::string &vec,
536                              const std::string &lane) {
537   std::string s = "__builtin_shufflevector(" + vec + ", " + vec;
538   for (unsigned i = 0; i < nElts; ++i)
539     s += ", " + lane;
540   s += ")";
541   return s;
542 }
543
544 static unsigned GetNumElements(StringRef typestr, bool &quad) {
545   quad = false;
546   bool dummy = false;
547   char type = ClassifyType(typestr, quad, dummy, dummy);
548   unsigned nElts = 0;
549   switch (type) {
550   case 'c': nElts = 8; break;
551   case 's': nElts = 4; break;
552   case 'i': nElts = 2; break;
553   case 'l': nElts = 1; break;
554   case 'h': nElts = 4; break;
555   case 'f': nElts = 2; break;
556   default:
557     throw "unhandled type!";
558     break;
559   }
560   if (quad) nElts <<= 1;
561   return nElts;
562 }
563
564 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
565 static std::string GenOpString(OpKind op, const std::string &proto,
566                                StringRef typestr) {
567   bool quad;
568   unsigned nElts = GetNumElements(typestr, quad);
569
570   // If this builtin takes an immediate argument, we need to #define it rather
571   // than use a standard declaration, so that SemaChecking can range check
572   // the immediate passed by the user.
573   bool define = proto.find('i') != std::string::npos;
574
575   std::string ts = TypeString(proto[0], typestr);
576   std::string s;
577   if (op == OpHi || op == OpLo) {
578     s = "union { " + ts + " r; double d; } u; u.d = ";
579   } else if (!define) {
580     s = "return ";
581   }
582
583   switch(op) {
584   case OpAdd:
585     s += "__a + __b;";
586     break;
587   case OpAddl:
588     s += Extend(typestr, "__a") + " + " + Extend(typestr, "__b") + ";";
589     break;
590   case OpAddw:
591     s += "__a + " + Extend(typestr, "__b") + ";";
592     break;
593   case OpSub:
594     s += "__a - __b;";
595     break;
596   case OpSubl:
597     s += Extend(typestr, "__a") + " - " + Extend(typestr, "__b") + ";";
598     break;
599   case OpSubw:
600     s += "__a - " + Extend(typestr, "__b") + ";";
601     break;
602   case OpMulN:
603     s += "__a * " + Duplicate(nElts, typestr, "__b") + ";";
604     break;
605   case OpMulLane:
606     s += "__a * " + SplatLane(nElts, "__b", "__c") + ";";
607     break;
608   case OpMul:
609     s += "__a * __b;";
610     break;
611   case OpMullN:
612     s += Extend(typestr, "__a") + " * " +
613       Extend(typestr, Duplicate(nElts << (int)quad, typestr, "__b")) + ";";
614     break;
615   case OpMullLane:
616     s += Extend(typestr, "__a") + " * " +
617       Extend(typestr, SplatLane(nElts, "__b", "__c")) + ";";
618     break;
619   case OpMull:
620     s += Extend(typestr, "__a") + " * " + Extend(typestr, "__b") + ";";
621     break;
622   case OpMlaN:
623     s += "__a + (__b * " + Duplicate(nElts, typestr, "__c") + ");";
624     break;
625   case OpMlaLane:
626     s += "__a + (__b * " + SplatLane(nElts, "__c", "__d") + ");";
627     break;
628   case OpMla:
629     s += "__a + (__b * __c);";
630     break;
631   case OpMlalN:
632     s += "__a + (" + Extend(typestr, "__b") + " * " +
633       Extend(typestr, Duplicate(nElts, typestr, "__c")) + ");";
634     break;
635   case OpMlalLane:
636     s += "__a + (" + Extend(typestr, "__b") + " * " +
637       Extend(typestr, SplatLane(nElts, "__c", "__d")) + ");";
638     break;
639   case OpMlal:
640     s += "__a + (" + Extend(typestr, "__b") + " * " +
641       Extend(typestr, "__c") + ");";
642     break;
643   case OpMlsN:
644     s += "__a - (__b * " + Duplicate(nElts, typestr, "__c") + ");";
645     break;
646   case OpMlsLane:
647     s += "__a - (__b * " + SplatLane(nElts, "__c", "__d") + ");";
648     break;
649   case OpMls:
650     s += "__a - (__b * __c);";
651     break;
652   case OpMlslN:
653     s += "__a - (" + Extend(typestr, "__b") + " * " +
654       Extend(typestr, Duplicate(nElts, typestr, "__c")) + ");";
655     break;
656   case OpMlslLane:
657     s += "__a - (" + Extend(typestr, "__b") + " * " +
658       Extend(typestr, SplatLane(nElts, "__c", "__d")) + ");";
659     break;
660   case OpMlsl:
661     s += "__a - (" + Extend(typestr, "__b") + " * " +
662       Extend(typestr, "__c") + ");";
663     break;
664   case OpQDMullLane:
665     s += MangleName("vqdmull", typestr, ClassS) + "(__a, " +
666       SplatLane(nElts, "__b", "__c") + ");";
667     break;
668   case OpQDMlalLane:
669     s += MangleName("vqdmlal", typestr, ClassS) + "(__a, __b, " +
670       SplatLane(nElts, "__c", "__d") + ");";
671     break;
672   case OpQDMlslLane:
673     s += MangleName("vqdmlsl", typestr, ClassS) + "(__a, __b, " +
674       SplatLane(nElts, "__c", "__d") + ");";
675     break;
676   case OpQDMulhLane:
677     s += MangleName("vqdmulh", typestr, ClassS) + "(__a, " +
678       SplatLane(nElts, "__b", "__c") + ");";
679     break;
680   case OpQRDMulhLane:
681     s += MangleName("vqrdmulh", typestr, ClassS) + "(__a, " +
682       SplatLane(nElts, "__b", "__c") + ");";
683     break;
684   case OpEq:
685     s += "(" + ts + ")(__a == __b);";
686     break;
687   case OpGe:
688     s += "(" + ts + ")(__a >= __b);";
689     break;
690   case OpLe:
691     s += "(" + ts + ")(__a <= __b);";
692     break;
693   case OpGt:
694     s += "(" + ts + ")(__a > __b);";
695     break;
696   case OpLt:
697     s += "(" + ts + ")(__a < __b);";
698     break;
699   case OpNeg:
700     s += " -__a;";
701     break;
702   case OpNot:
703     s += " ~__a;";
704     break;
705   case OpAnd:
706     s += "__a & __b;";
707     break;
708   case OpOr:
709     s += "__a | __b;";
710     break;
711   case OpXor:
712     s += "__a ^ __b;";
713     break;
714   case OpAndNot:
715     s += "__a & ~__b;";
716     break;
717   case OpOrNot:
718     s += "__a | ~__b;";
719     break;
720   case OpCast:
721     s += "(" + ts + ")__a;";
722     break;
723   case OpConcat:
724     s += "(" + ts + ")__builtin_shufflevector((int64x1_t)__a";
725     s += ", (int64x1_t)__b, 0, 1);";
726     break;
727   case OpHi:
728     s += "(((float64x2_t)__a)[1]);";
729     break;
730   case OpLo:
731     s += "(((float64x2_t)__a)[0]);";
732     break;
733   case OpDup:
734     s += Duplicate(nElts, typestr, "__a") + ";";
735     break;
736   case OpDupLane:
737     s += SplatLane(nElts, "__a", "__b") + ";";
738     break;
739   case OpSelect:
740     // ((0 & 1) | (~0 & 2))
741     s += "(" + ts + ")";
742     ts = TypeString(proto[1], typestr);
743     s += "((__a & (" + ts + ")__b) | ";
744     s += "(~__a & (" + ts + ")__c));";
745     break;
746   case OpRev16:
747     s += "__builtin_shufflevector(__a, __a";
748     for (unsigned i = 2; i <= nElts; i += 2)
749       for (unsigned j = 0; j != 2; ++j)
750         s += ", " + utostr(i - j - 1);
751     s += ");";
752     break;
753   case OpRev32: {
754     unsigned WordElts = nElts >> (1 + (int)quad);
755     s += "__builtin_shufflevector(__a, __a";
756     for (unsigned i = WordElts; i <= nElts; i += WordElts)
757       for (unsigned j = 0; j != WordElts; ++j)
758         s += ", " + utostr(i - j - 1);
759     s += ");";
760     break;
761   }
762   case OpRev64: {
763     unsigned DblWordElts = nElts >> (int)quad;
764     s += "__builtin_shufflevector(__a, __a";
765     for (unsigned i = DblWordElts; i <= nElts; i += DblWordElts)
766       for (unsigned j = 0; j != DblWordElts; ++j)
767         s += ", " + utostr(i - j - 1);
768     s += ");";
769     break;
770   }
771   case OpAbdl: {
772     std::string abd = MangleName("vabd", typestr, ClassS) + "(__a, __b)";
773     if (typestr[0] != 'U') {
774       // vabd results are always unsigned and must be zero-extended.
775       std::string utype = "U" + typestr.str();
776       s += "(" + TypeString(proto[0], typestr) + ")";
777       abd = "(" + TypeString('d', utype) + ")" + abd;
778       s += Extend(utype, abd) + ";";
779     } else {
780       s += Extend(typestr, abd) + ";";
781     }
782     break;
783   }
784   case OpAba:
785     s += "__a + " + MangleName("vabd", typestr, ClassS) + "(__b, __c);";
786     break;
787   case OpAbal: {
788     s += "__a + ";
789     std::string abd = MangleName("vabd", typestr, ClassS) + "(__b, __c)";
790     if (typestr[0] != 'U') {
791       // vabd results are always unsigned and must be zero-extended.
792       std::string utype = "U" + typestr.str();
793       s += "(" + TypeString(proto[0], typestr) + ")";
794       abd = "(" + TypeString('d', utype) + ")" + abd;
795       s += Extend(utype, abd) + ";";
796     } else {
797       s += Extend(typestr, abd) + ";";
798     }
799     break;
800   }
801   default:
802     throw "unknown OpKind!";
803     break;
804   }
805   if (op == OpHi || op == OpLo) {
806     if (!define)
807       s += " return";
808     s += " u.r;";
809   }
810   return s;
811 }
812
813 static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
814   unsigned mod = proto[0];
815   unsigned ret = 0;
816
817   if (mod == 'v' || mod == 'f')
818     mod = proto[1];
819
820   bool quad = false;
821   bool poly = false;
822   bool usgn = false;
823   bool scal = false;
824   bool cnst = false;
825   bool pntr = false;
826
827   // Base type to get the type string for.
828   char type = ClassifyType(typestr, quad, poly, usgn);
829
830   // Based on the modifying character, change the type and width if necessary.
831   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
832
833   if (usgn)
834     ret |= 0x08;
835   if (quad && proto[1] != 'g')
836     ret |= 0x10;
837
838   switch (type) {
839     case 'c':
840       ret |= poly ? 5 : 0;
841       break;
842     case 's':
843       ret |= poly ? 6 : 1;
844       break;
845     case 'i':
846       ret |= 2;
847       break;
848     case 'l':
849       ret |= 3;
850       break;
851     case 'h':
852       ret |= 7;
853       break;
854     case 'f':
855       ret |= 4;
856       break;
857     default:
858       throw "unhandled type!";
859       break;
860   }
861   return ret;
862 }
863
864 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
865 static std::string GenBuiltin(const std::string &name, const std::string &proto,
866                               StringRef typestr, ClassKind ck) {
867   std::string s;
868
869   // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
870   // sret-like argument.
871   bool sret = (proto[0] >= '2' && proto[0] <= '4');
872
873   // If this builtin takes an immediate argument, we need to #define it rather
874   // than use a standard declaration, so that SemaChecking can range check
875   // the immediate passed by the user.
876   bool define = proto.find('i') != std::string::npos;
877
878   // Check if the prototype has a scalar operand with the type of the vector
879   // elements.  If not, bitcasting the args will take care of arg checking.
880   // The actual signedness etc. will be taken care of with special enums.
881   if (proto.find('s') == std::string::npos)
882     ck = ClassB;
883
884   if (proto[0] != 'v') {
885     std::string ts = TypeString(proto[0], typestr);
886
887     if (define) {
888       if (sret)
889         s += ts + " r; ";
890       else
891         s += "(" + ts + ")";
892     } else if (sret) {
893       s += ts + " r; ";
894     } else {
895       s += "return (" + ts + ")";
896     }
897   }
898
899   bool splat = proto.find('a') != std::string::npos;
900
901   s += "__builtin_neon_";
902   if (splat) {
903     // Call the non-splat builtin: chop off the "_n" suffix from the name.
904     std::string vname(name, 0, name.size()-2);
905     s += MangleName(vname, typestr, ck);
906   } else {
907     s += MangleName(name, typestr, ck);
908   }
909   s += "(";
910
911   // Pass the address of the return variable as the first argument to sret-like
912   // builtins.
913   if (sret)
914     s += "&r, ";
915
916   char arg = 'a';
917   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
918     std::string args = std::string(&arg, 1);
919
920     // Use the local temporaries instead of the macro arguments.
921     args = "__" + args;
922
923     bool argQuad = false;
924     bool argPoly = false;
925     bool argUsgn = false;
926     bool argScalar = false;
927     bool dummy = false;
928     char argType = ClassifyType(typestr, argQuad, argPoly, argUsgn);
929     argType = ModType(proto[i], argType, argQuad, argPoly, argUsgn, argScalar,
930                       dummy, dummy);
931
932     // Handle multiple-vector values specially, emitting each subvector as an
933     // argument to the __builtin.
934     if (proto[i] >= '2' && proto[i] <= '4') {
935       // Check if an explicit cast is needed.
936       if (argType != 'c' || argPoly || argUsgn)
937         args = (argQuad ? "(int8x16_t)" : "(int8x8_t)") + args;
938
939       for (unsigned vi = 0, ve = proto[i] - '0'; vi != ve; ++vi) {
940         s += args + ".val[" + utostr(vi) + "]";
941         if ((vi + 1) < ve)
942           s += ", ";
943       }
944       if ((i + 1) < e)
945         s += ", ";
946
947       continue;
948     }
949
950     if (splat && (i + 1) == e)
951       args = Duplicate(GetNumElements(typestr, argQuad), typestr, args);
952
953     // Check if an explicit cast is needed.
954     if ((splat || !argScalar) &&
955         ((ck == ClassB && argType != 'c') || argPoly || argUsgn)) {
956       std::string argTypeStr = "c";
957       if (ck != ClassB)
958         argTypeStr = argType;
959       if (argQuad)
960         argTypeStr = "Q" + argTypeStr;
961       args = "(" + TypeString('d', argTypeStr) + ")" + args;
962     }
963
964     s += args;
965     if ((i + 1) < e)
966       s += ", ";
967   }
968
969   // Extra constant integer to hold type class enum for this function, e.g. s8
970   if (ck == ClassB)
971     s += ", " + utostr(GetNeonEnum(proto, typestr));
972
973   s += ");";
974
975   if (proto[0] != 'v' && sret) {
976     if (define)
977       s += " r;";
978     else
979       s += " return r;";
980   }
981   return s;
982 }
983
984 static std::string GenBuiltinDef(const std::string &name,
985                                  const std::string &proto,
986                                  StringRef typestr, ClassKind ck) {
987   std::string s("BUILTIN(__builtin_neon_");
988
989   // If all types are the same size, bitcasting the args will take care
990   // of arg checking.  The actual signedness etc. will be taken care of with
991   // special enums.
992   if (proto.find('s') == std::string::npos)
993     ck = ClassB;
994
995   s += MangleName(name, typestr, ck);
996   s += ", \"";
997
998   for (unsigned i = 0, e = proto.size(); i != e; ++i)
999     s += BuiltinTypeString(proto[i], typestr, ck, i == 0);
1000
1001   // Extra constant integer to hold type class enum for this function, e.g. s8
1002   if (ck == ClassB)
1003     s += "i";
1004
1005   s += "\", \"n\")";
1006   return s;
1007 }
1008
1009 static std::string GenIntrinsic(const std::string &name,
1010                                 const std::string &proto,
1011                                 StringRef outTypeStr, StringRef inTypeStr,
1012                                 OpKind kind, ClassKind classKind) {
1013   assert(!proto.empty() && "");
1014   bool define = proto.find('i') != std::string::npos;
1015   std::string s;
1016
1017   // static always inline + return type
1018   if (define)
1019     s += "#define ";
1020   else
1021     s += "__ai " + TypeString(proto[0], outTypeStr) + " ";
1022
1023   // Function name with type suffix
1024   std::string mangledName = MangleName(name, outTypeStr, ClassS);
1025   if (outTypeStr != inTypeStr) {
1026     // If the input type is different (e.g., for vreinterpret), append a suffix
1027     // for the input type.  String off a "Q" (quad) prefix so that MangleName
1028     // does not insert another "q" in the name.
1029     unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1030     StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1031     mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1032   }
1033   s += mangledName;
1034
1035   // Function arguments
1036   s += GenArgs(proto, inTypeStr);
1037
1038   // Definition.
1039   if (define) {
1040     s += " __extension__ ({ \\\n  ";
1041     s += GenMacroLocals(proto, inTypeStr);
1042   } else {
1043     s += " { \\\n  ";
1044   }
1045
1046   if (kind != OpNone)
1047     s += GenOpString(kind, proto, outTypeStr);
1048   else
1049     s += GenBuiltin(name, proto, outTypeStr, classKind);
1050   if (define)
1051     s += " })";
1052   else
1053     s += " }";
1054   s += "\n";
1055   return s;
1056 }
1057
1058 /// run - Read the records in arm_neon.td and output arm_neon.h.  arm_neon.h
1059 /// is comprised of type definitions and function declarations.
1060 void NeonEmitter::run(raw_ostream &OS) {
1061   OS << 
1062     "/*===---- arm_neon.h - ARM Neon intrinsics ------------------------------"
1063     "---===\n"
1064     " *\n"
1065     " * Permission is hereby granted, free of charge, to any person obtaining "
1066     "a copy\n"
1067     " * of this software and associated documentation files (the \"Software\"),"
1068     " to deal\n"
1069     " * in the Software without restriction, including without limitation the "
1070     "rights\n"
1071     " * to use, copy, modify, merge, publish, distribute, sublicense, "
1072     "and/or sell\n"
1073     " * copies of the Software, and to permit persons to whom the Software is\n"
1074     " * furnished to do so, subject to the following conditions:\n"
1075     " *\n"
1076     " * The above copyright notice and this permission notice shall be "
1077     "included in\n"
1078     " * all copies or substantial portions of the Software.\n"
1079     " *\n"
1080     " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
1081     "EXPRESS OR\n"
1082     " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
1083     "MERCHANTABILITY,\n"
1084     " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
1085     "SHALL THE\n"
1086     " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
1087     "OTHER\n"
1088     " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
1089     "ARISING FROM,\n"
1090     " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
1091     "DEALINGS IN\n"
1092     " * THE SOFTWARE.\n"
1093     " *\n"
1094     " *===--------------------------------------------------------------------"
1095     "---===\n"
1096     " */\n\n";
1097
1098   OS << "#ifndef __ARM_NEON_H\n";
1099   OS << "#define __ARM_NEON_H\n\n";
1100
1101   OS << "#ifndef __ARM_NEON__\n";
1102   OS << "#error \"NEON support not enabled\"\n";
1103   OS << "#endif\n\n";
1104
1105   OS << "#include <stdint.h>\n\n";
1106
1107   // Emit NEON-specific scalar typedefs.
1108   OS << "typedef float float32_t;\n";
1109   OS << "typedef int8_t poly8_t;\n";
1110   OS << "typedef int16_t poly16_t;\n";
1111   OS << "typedef uint16_t float16_t;\n";
1112
1113   // Emit Neon vector typedefs.
1114   std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
1115   SmallVector<StringRef, 24> TDTypeVec;
1116   ParseTypes(0, TypedefTypes, TDTypeVec);
1117
1118   // Emit vector typedefs.
1119   for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1120     bool dummy, quad = false, poly = false;
1121     (void) ClassifyType(TDTypeVec[i], quad, poly, dummy);
1122     if (poly)
1123       OS << "typedef __attribute__((neon_polyvector_type(";
1124     else
1125       OS << "typedef __attribute__((neon_vector_type(";
1126
1127     unsigned nElts = GetNumElements(TDTypeVec[i], quad);
1128     OS << utostr(nElts) << "))) ";
1129     if (nElts < 10)
1130       OS << " ";
1131
1132     OS << TypeString('s', TDTypeVec[i]);
1133     OS << " " << TypeString('d', TDTypeVec[i]) << ";\n";
1134   }
1135   OS << "\n";
1136   OS << "typedef __attribute__((__vector_size__(8)))  "
1137     "double float64x1_t;\n";
1138   OS << "typedef __attribute__((__vector_size__(16))) "
1139     "double float64x2_t;\n";
1140   OS << "\n";
1141
1142   // Emit struct typedefs.
1143   for (unsigned vi = 2; vi != 5; ++vi) {
1144     for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1145       std::string ts = TypeString('d', TDTypeVec[i]);
1146       std::string vs = TypeString('0' + vi, TDTypeVec[i]);
1147       OS << "typedef struct " << vs << " {\n";
1148       OS << "  " << ts << " val";
1149       OS << "[" << utostr(vi) << "]";
1150       OS << ";\n} ";
1151       OS << vs << ";\n\n";
1152     }
1153   }
1154
1155   OS << "#define __ai static __attribute__((__always_inline__))\n\n";
1156
1157   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1158
1159   // Emit vmovl and vabd intrinsics first so they can be used by other
1160   // intrinsics.  (Some of the saturating multiply instructions are also
1161   // used to implement the corresponding "_lane" variants, but tablegen
1162   // sorts the records into alphabetical order so that the "_lane" variants
1163   // come after the intrinsics they use.)
1164   emitIntrinsic(OS, Records.getDef("VMOVL"));
1165   emitIntrinsic(OS, Records.getDef("VABD"));
1166
1167   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1168     Record *R = RV[i];
1169     if (R->getName() != "VMOVL" && R->getName() != "VABD")
1170       emitIntrinsic(OS, R);
1171   }
1172
1173   OS << "#undef __ai\n\n";
1174   OS << "#endif /* __ARM_NEON_H */\n";
1175 }
1176
1177 /// emitIntrinsic - Write out the arm_neon.h header file definitions for the
1178 /// intrinsics specified by record R.
1179 void NeonEmitter::emitIntrinsic(raw_ostream &OS, Record *R) {
1180   std::string name = R->getValueAsString("Name");
1181   std::string Proto = R->getValueAsString("Prototype");
1182   std::string Types = R->getValueAsString("Types");
1183
1184   SmallVector<StringRef, 16> TypeVec;
1185   ParseTypes(R, Types, TypeVec);
1186
1187   OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1188
1189   ClassKind classKind = ClassNone;
1190   if (R->getSuperClasses().size() >= 2)
1191     classKind = ClassMap[R->getSuperClasses()[1]];
1192   if (classKind == ClassNone && kind == OpNone)
1193     throw TGError(R->getLoc(), "Builtin has no class kind");
1194
1195   for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1196     if (kind == OpReinterpret) {
1197       bool outQuad = false;
1198       bool dummy = false;
1199       (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1200       for (unsigned srcti = 0, srcte = TypeVec.size();
1201            srcti != srcte; ++srcti) {
1202         bool inQuad = false;
1203         (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1204         if (srcti == ti || inQuad != outQuad)
1205           continue;
1206         OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[srcti],
1207                            OpCast, ClassS);
1208       }
1209     } else {
1210       OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[ti],
1211                          kind, classKind);
1212     }
1213   }
1214   OS << "\n";
1215 }
1216
1217 static unsigned RangeFromType(const char mod, StringRef typestr) {
1218   // base type to get the type string for.
1219   bool quad = false, dummy = false;
1220   char type = ClassifyType(typestr, quad, dummy, dummy);
1221   type = ModType(mod, type, quad, dummy, dummy, dummy, dummy, dummy);
1222
1223   switch (type) {
1224     case 'c':
1225       return (8 << (int)quad) - 1;
1226     case 'h':
1227     case 's':
1228       return (4 << (int)quad) - 1;
1229     case 'f':
1230     case 'i':
1231       return (2 << (int)quad) - 1;
1232     case 'l':
1233       return (1 << (int)quad) - 1;
1234     default:
1235       throw "unhandled type!";
1236       break;
1237   }
1238   assert(0 && "unreachable");
1239   return 0;
1240 }
1241
1242 /// runHeader - Emit a file with sections defining:
1243 /// 1. the NEON section of BuiltinsARM.def.
1244 /// 2. the SemaChecking code for the type overload checking.
1245 /// 3. the SemaChecking code for validation of intrinsic immedate arguments.
1246 void NeonEmitter::runHeader(raw_ostream &OS) {
1247   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1248
1249   StringMap<OpKind> EmittedMap;
1250
1251   // Generate BuiltinsARM.def for NEON
1252   OS << "#ifdef GET_NEON_BUILTINS\n";
1253   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1254     Record *R = RV[i];
1255     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1256     if (k != OpNone)
1257       continue;
1258
1259     std::string Proto = R->getValueAsString("Prototype");
1260
1261     // Functions with 'a' (the splat code) in the type prototype should not get
1262     // their own builtin as they use the non-splat variant.
1263     if (Proto.find('a') != std::string::npos)
1264       continue;
1265
1266     std::string Types = R->getValueAsString("Types");
1267     SmallVector<StringRef, 16> TypeVec;
1268     ParseTypes(R, Types, TypeVec);
1269
1270     if (R->getSuperClasses().size() < 2)
1271       throw TGError(R->getLoc(), "Builtin has no class kind");
1272
1273     std::string name = R->getValueAsString("Name");
1274     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1275
1276     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1277       // Generate the BuiltinsARM.def declaration for this builtin, ensuring
1278       // that each unique BUILTIN() macro appears only once in the output
1279       // stream.
1280       std::string bd = GenBuiltinDef(name, Proto, TypeVec[ti], ck);
1281       if (EmittedMap.count(bd))
1282         continue;
1283
1284       EmittedMap[bd] = OpNone;
1285       OS << bd << "\n";
1286     }
1287   }
1288   OS << "#endif\n\n";
1289
1290   // Generate the overloaded type checking code for SemaChecking.cpp
1291   OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1292   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1293     Record *R = RV[i];
1294     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1295     if (k != OpNone)
1296       continue;
1297
1298     std::string Proto = R->getValueAsString("Prototype");
1299     std::string Types = R->getValueAsString("Types");
1300     std::string name = R->getValueAsString("Name");
1301
1302     // Functions with 'a' (the splat code) in the type prototype should not get
1303     // their own builtin as they use the non-splat variant.
1304     if (Proto.find('a') != std::string::npos)
1305       continue;
1306
1307     // Functions which have a scalar argument cannot be overloaded, no need to
1308     // check them if we are emitting the type checking code.
1309     if (Proto.find('s') != std::string::npos)
1310       continue;
1311
1312     SmallVector<StringRef, 16> TypeVec;
1313     ParseTypes(R, Types, TypeVec);
1314
1315     if (R->getSuperClasses().size() < 2)
1316       throw TGError(R->getLoc(), "Builtin has no class kind");
1317
1318     int si = -1, qi = -1;
1319     unsigned mask = 0, qmask = 0;
1320     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1321       // Generate the switch case(s) for this builtin for the type validation.
1322       bool quad = false, poly = false, usgn = false;
1323       (void) ClassifyType(TypeVec[ti], quad, poly, usgn);
1324
1325       if (quad) {
1326         qi = ti;
1327         qmask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1328       } else {
1329         si = ti;
1330         mask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1331       }
1332     }
1333     if (mask)
1334       OS << "case ARM::BI__builtin_neon_"
1335          << MangleName(name, TypeVec[si], ClassB)
1336          << ": mask = " << "0x" << utohexstr(mask) << "; break;\n";
1337     if (qmask)
1338       OS << "case ARM::BI__builtin_neon_"
1339          << MangleName(name, TypeVec[qi], ClassB)
1340          << ": mask = " << "0x" << utohexstr(qmask) << "; break;\n";
1341   }
1342   OS << "#endif\n\n";
1343
1344   // Generate the intrinsic range checking code for shift/lane immediates.
1345   OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
1346   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1347     Record *R = RV[i];
1348
1349     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1350     if (k != OpNone)
1351       continue;
1352
1353     std::string name = R->getValueAsString("Name");
1354     std::string Proto = R->getValueAsString("Prototype");
1355     std::string Types = R->getValueAsString("Types");
1356
1357     // Functions with 'a' (the splat code) in the type prototype should not get
1358     // their own builtin as they use the non-splat variant.
1359     if (Proto.find('a') != std::string::npos)
1360       continue;
1361
1362     // Functions which do not have an immediate do not need to have range
1363     // checking code emitted.
1364     size_t immPos = Proto.find('i');
1365     if (immPos == std::string::npos)
1366       continue;
1367
1368     SmallVector<StringRef, 16> TypeVec;
1369     ParseTypes(R, Types, TypeVec);
1370
1371     if (R->getSuperClasses().size() < 2)
1372       throw TGError(R->getLoc(), "Builtin has no class kind");
1373
1374     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1375
1376     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1377       std::string namestr, shiftstr, rangestr;
1378
1379       // Builtins which are overloaded by type will need to have their upper
1380       // bound computed at Sema time based on the type constant.
1381       if (Proto.find('s') == std::string::npos) {
1382         ck = ClassB;
1383         if (R->getValueAsBit("isShift")) {
1384           shiftstr = ", true";
1385
1386           // Right shifts have an 'r' in the name, left shifts do not.
1387           if (name.find('r') != std::string::npos)
1388             rangestr = "l = 1; ";
1389         }
1390         rangestr += "u = RFT(TV" + shiftstr + ")";
1391       } else {
1392         // The immediate generally refers to a lane in the preceding argument.
1393         assert(immPos > 0 && "unexpected immediate operand");
1394         rangestr = "u = " + utostr(RangeFromType(Proto[immPos-1], TypeVec[ti]));
1395       }
1396       // Make sure cases appear only once by uniquing them in a string map.
1397       namestr = MangleName(name, TypeVec[ti], ck);
1398       if (EmittedMap.count(namestr))
1399         continue;
1400       EmittedMap[namestr] = OpNone;
1401
1402       // Calculate the index of the immediate that should be range checked.
1403       unsigned immidx = 0;
1404
1405       // Builtins that return a struct of multiple vectors have an extra
1406       // leading arg for the struct return.
1407       if (Proto[0] >= '2' && Proto[0] <= '4')
1408         ++immidx;
1409
1410       // Add one to the index for each argument until we reach the immediate
1411       // to be checked.  Structs of vectors are passed as multiple arguments.
1412       for (unsigned ii = 1, ie = Proto.size(); ii != ie; ++ii) {
1413         switch (Proto[ii]) {
1414           default:  immidx += 1; break;
1415           case '2': immidx += 2; break;
1416           case '3': immidx += 3; break;
1417           case '4': immidx += 4; break;
1418           case 'i': ie = ii + 1; break;
1419         }
1420       }
1421       OS << "case ARM::BI__builtin_neon_" << MangleName(name, TypeVec[ti], ck)
1422          << ": i = " << immidx << "; " << rangestr << "; break;\n";
1423     }
1424   }
1425   OS << "#endif\n\n";
1426 }
1427
1428 /// GenTest - Write out a test for the intrinsic specified by the name and
1429 /// type strings, including the embedded patterns for FileCheck to match.
1430 static std::string GenTest(const std::string &name,
1431                            const std::string &proto,
1432                            StringRef outTypeStr, StringRef inTypeStr,
1433                            bool isShift) {
1434   assert(!proto.empty() && "");
1435   std::string s;
1436
1437   // Function name with type suffix
1438   std::string mangledName = MangleName(name, outTypeStr, ClassS);
1439   if (outTypeStr != inTypeStr) {
1440     // If the input type is different (e.g., for vreinterpret), append a suffix
1441     // for the input type.  String off a "Q" (quad) prefix so that MangleName
1442     // does not insert another "q" in the name.
1443     unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1444     StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1445     mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1446   }
1447
1448   // Emit the FileCheck patterns.
1449   s += "// CHECK: test_" + mangledName + "\n";
1450   // s += "// CHECK: \n"; // FIXME: + expected instruction opcode.
1451
1452   // Emit the start of the test function.
1453   s += TypeString(proto[0], outTypeStr) + " test_" + mangledName + "(";
1454   char arg = 'a';
1455   std::string comma;
1456   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1457     // Do not create arguments for values that must be immediate constants.
1458     if (proto[i] == 'i')
1459       continue;
1460     s += comma + TypeString(proto[i], inTypeStr) + " ";
1461     s.push_back(arg);
1462     comma = ", ";
1463   }
1464   s += ") { \\\n  ";
1465
1466   if (proto[0] != 'v')
1467     s += "return ";
1468   s += mangledName + "(";
1469   arg = 'a';
1470   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1471     if (proto[i] == 'i') {
1472       // For immediate operands, test the maximum value.
1473       if (isShift)
1474         s += "1"; // FIXME
1475       else
1476         // The immediate generally refers to a lane in the preceding argument.
1477         s += utostr(RangeFromType(proto[i-1], inTypeStr));
1478     } else {
1479       s.push_back(arg);
1480     }
1481     if ((i + 1) < e)
1482       s += ", ";
1483   }
1484   s += ");\n}\n\n";
1485   return s;
1486 }
1487
1488 /// runTests - Write out a complete set of tests for all of the Neon
1489 /// intrinsics.
1490 void NeonEmitter::runTests(raw_ostream &OS) {
1491   OS <<
1492     "// RUN: %clang_cc1 -triple thumbv7-apple-darwin \\\n"
1493     "// RUN:  -target-cpu cortex-a8 -ffreestanding -S -o - %s | FileCheck %s\n"
1494     "\n"
1495     "#include <arm_neon.h>\n"
1496     "\n";
1497
1498   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1499   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1500     Record *R = RV[i];
1501     std::string name = R->getValueAsString("Name");
1502     std::string Proto = R->getValueAsString("Prototype");
1503     std::string Types = R->getValueAsString("Types");
1504     bool isShift = R->getValueAsBit("isShift");
1505
1506     SmallVector<StringRef, 16> TypeVec;
1507     ParseTypes(R, Types, TypeVec);
1508
1509     OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1510     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1511       if (kind == OpReinterpret) {
1512         bool outQuad = false;
1513         bool dummy = false;
1514         (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1515         for (unsigned srcti = 0, srcte = TypeVec.size();
1516              srcti != srcte; ++srcti) {
1517           bool inQuad = false;
1518           (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1519           if (srcti == ti || inQuad != outQuad)
1520             continue;
1521           OS << GenTest(name, Proto, TypeVec[ti], TypeVec[srcti], isShift);
1522         }
1523       } else {
1524         OS << GenTest(name, Proto, TypeVec[ti], TypeVec[ti], isShift);
1525       }
1526     }
1527     OS << "\n";
1528   }
1529 }
1530