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