slang_rs_reflection.cpp revision 593a894650e81be54173106ec266f0311cebebd3
1/*
2 * Copyright 2010, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "slang_rs_reflection.h"
18
19#include <sys/stat.h>
20
21#include <cstdarg>
22#include <cctype>
23
24#include <algorithm>
25#include <string>
26#include <utility>
27
28#include "llvm/ADT/APFloat.h"
29#include "llvm/ADT/StringExtras.h"
30
31#include "os_sep.h"
32#include "slang_rs_context.h"
33#include "slang_rs_export_var.h"
34#include "slang_rs_export_foreach.h"
35#include "slang_rs_export_func.h"
36#include "slang_rs_reflect_utils.h"
37#include "slang_utils.h"
38
39#define RS_SCRIPT_CLASS_NAME_PREFIX      "ScriptC_"
40#define RS_SCRIPT_CLASS_SUPER_CLASS_NAME "ScriptC"
41
42#define RS_TYPE_CLASS_NAME_PREFIX        "ScriptField_"
43#define RS_TYPE_CLASS_SUPER_CLASS_NAME   "android.renderscript.Script.FieldBase"
44
45#define RS_TYPE_ITEM_CLASS_NAME          "Item"
46
47#define RS_TYPE_ITEM_BUFFER_NAME         "mItemArray"
48#define RS_TYPE_ITEM_BUFFER_PACKER_NAME  "mIOBuffer"
49
50#define RS_EXPORT_VAR_INDEX_PREFIX       "mExportVarIdx_"
51#define RS_EXPORT_VAR_PREFIX             "mExportVar_"
52
53#define RS_EXPORT_FUNC_INDEX_PREFIX      "mExportFuncIdx_"
54#define RS_EXPORT_FOREACH_INDEX_PREFIX   "mExportForEachIdx_"
55
56#define RS_EXPORT_VAR_ALLOCATION_PREFIX  "mAlloction_"
57#define RS_EXPORT_VAR_DATA_STORAGE_PREFIX "mData_"
58
59namespace slang {
60
61// Some utility function using internal in RSReflection
62static bool GetClassNameFromFileName(const std::string &FileName,
63                                     std::string &ClassName) {
64  ClassName.clear();
65
66  if (FileName.empty() || (FileName == "-"))
67    return true;
68
69  ClassName =
70      RSSlangReflectUtils::JavaClassNameFromRSFileName(FileName.c_str());
71
72  return true;
73}
74
75static const char *GetPrimitiveTypeName(const RSExportPrimitiveType *EPT) {
76  static const char *PrimitiveTypeJavaNameMap[] = {
77    "",         // RSExportPrimitiveType::DataTypeFloat16
78    "float",    // RSExportPrimitiveType::DataTypeFloat32
79    "double",   // RSExportPrimitiveType::DataTypeFloat64
80    "byte",     // RSExportPrimitiveType::DataTypeSigned8
81    "short",    // RSExportPrimitiveType::DataTypeSigned16
82    "int",      // RSExportPrimitiveType::DataTypeSigned32
83    "long",     // RSExportPrimitiveType::DataTypeSigned64
84    "short",    // RSExportPrimitiveType::DataTypeUnsigned8
85    "int",      // RSExportPrimitiveType::DataTypeUnsigned16
86    "long",     // RSExportPrimitiveType::DataTypeUnsigned32
87    "long",     // RSExportPrimitiveType::DataTypeUnsigned64
88    "boolean",  // RSExportPrimitiveType::DataTypeBoolean
89
90    "int",      // RSExportPrimitiveType::DataTypeUnsigned565
91    "int",      // RSExportPrimitiveType::DataTypeUnsigned5551
92    "int",      // RSExportPrimitiveType::DataTypeUnsigned4444
93
94    "",     // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix2x2
95    "",     // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix3x3
96    "",     // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix4x4
97
98    "Element",      // RSExportPrimitiveType::DataTypeRSElement
99    "Type",         // RSExportPrimitiveType::DataTypeRSType
100    "Allocation",   // RSExportPrimitiveType::DataTypeRSAllocation
101    "Sampler",      // RSExportPrimitiveType::DataTypeRSSampler
102    "Script",       // RSExportPrimitiveType::DataTypeRSScript
103    "Mesh",         // RSExportPrimitiveType::DataTypeRSMesh
104    "ProgramFragment",  // RSExportPrimitiveType::DataTypeRSProgramFragment
105    "ProgramVertex",    // RSExportPrimitiveType::DataTypeRSProgramVertex
106    "ProgramRaster",    // RSExportPrimitiveType::DataTypeRSProgramRaster
107    "ProgramStore",     // RSExportPrimitiveType::DataTypeRSProgramStore
108    "Font",     // RSExportPrimitiveType::DataTypeRSFont
109  };
110  unsigned TypeId = EPT->getType();
111
112  if (TypeId < (sizeof(PrimitiveTypeJavaNameMap) / sizeof(const char*))) {
113    return PrimitiveTypeJavaNameMap[ EPT->getType() ];
114  }
115
116  slangAssert(false && "GetPrimitiveTypeName : Unknown primitive data type");
117  return NULL;
118}
119
120static const char *GetVectorTypeName(const RSExportVectorType *EVT) {
121  static const char *VectorTypeJavaNameMap[][3] = {
122    /* 0 */ { "Byte2",  "Byte3",    "Byte4" },
123    /* 1 */ { "Short2", "Short3",   "Short4" },
124    /* 2 */ { "Int2",   "Int3",     "Int4" },
125    /* 3 */ { "Long2",  "Long3",    "Long4" },
126    /* 4 */ { "Float2", "Float3",   "Float4" },
127  };
128
129  const char **BaseElement = NULL;
130
131  switch (EVT->getType()) {
132    case RSExportPrimitiveType::DataTypeSigned8:
133    case RSExportPrimitiveType::DataTypeBoolean: {
134      BaseElement = VectorTypeJavaNameMap[0];
135      break;
136    }
137    case RSExportPrimitiveType::DataTypeSigned16:
138    case RSExportPrimitiveType::DataTypeUnsigned8: {
139      BaseElement = VectorTypeJavaNameMap[1];
140      break;
141    }
142    case RSExportPrimitiveType::DataTypeSigned32:
143    case RSExportPrimitiveType::DataTypeUnsigned16: {
144      BaseElement = VectorTypeJavaNameMap[2];
145      break;
146    }
147    case RSExportPrimitiveType::DataTypeSigned64:
148    case RSExportPrimitiveType::DataTypeUnsigned64:
149    case RSExportPrimitiveType::DataTypeUnsigned32: {
150      BaseElement = VectorTypeJavaNameMap[3];
151      break;
152    }
153    case RSExportPrimitiveType::DataTypeFloat32: {
154      BaseElement = VectorTypeJavaNameMap[4];
155      break;
156    }
157    default: {
158      slangAssert(false && "RSReflection::genElementTypeName : Unsupported "
159                           "vector element data type");
160      break;
161    }
162  }
163
164  slangAssert((EVT->getNumElement() > 1) &&
165              (EVT->getNumElement() <= 4) &&
166              "Number of element in vector type is invalid");
167
168  return BaseElement[EVT->getNumElement() - 2];
169}
170
171static const char *GetMatrixTypeName(const RSExportMatrixType *EMT) {
172  static const char *MatrixTypeJavaNameMap[] = {
173    /* 2x2 */ "Matrix2f",
174    /* 3x3 */ "Matrix3f",
175    /* 4x4 */ "Matrix4f",
176  };
177  unsigned Dim = EMT->getDim();
178
179  if ((Dim - 2) < (sizeof(MatrixTypeJavaNameMap) / sizeof(const char*)))
180    return MatrixTypeJavaNameMap[ EMT->getDim() - 2 ];
181
182  slangAssert(false && "GetMatrixTypeName : Unsupported matrix dimension");
183  return NULL;
184}
185
186static const char *GetVectorAccessor(unsigned Index) {
187  static const char *VectorAccessorMap[] = {
188    /* 0 */ "x",
189    /* 1 */ "y",
190    /* 2 */ "z",
191    /* 3 */ "w",
192  };
193
194  slangAssert((Index < (sizeof(VectorAccessorMap) / sizeof(const char*))) &&
195              "Out-of-bound index to access vector member");
196
197  return VectorAccessorMap[Index];
198}
199
200static const char *GetPackerAPIName(const RSExportPrimitiveType *EPT) {
201  static const char *PrimitiveTypePackerAPINameMap[] = {
202    "",         // RSExportPrimitiveType::DataTypeFloat16
203    "addF32",   // RSExportPrimitiveType::DataTypeFloat32
204    "addF64",   // RSExportPrimitiveType::DataTypeFloat64
205    "addI8",    // RSExportPrimitiveType::DataTypeSigned8
206    "addI16",   // RSExportPrimitiveType::DataTypeSigned16
207    "addI32",   // RSExportPrimitiveType::DataTypeSigned32
208    "addI64",   // RSExportPrimitiveType::DataTypeSigned64
209    "addU8",    // RSExportPrimitiveType::DataTypeUnsigned8
210    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned16
211    "addU32",   // RSExportPrimitiveType::DataTypeUnsigned32
212    "addU64",   // RSExportPrimitiveType::DataTypeUnsigned64
213    "addBoolean",  // RSExportPrimitiveType::DataTypeBoolean
214
215    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned565
216    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned5551
217    "addU16",   // RSExportPrimitiveType::DataTypeUnsigned4444
218
219    "addMatrix",   // RSExportPrimitiveType::DataTypeRSMatrix2x2
220    "addMatrix",   // RSExportPrimitiveType::DataTypeRSMatrix3x3
221    "addMatrix",   // RSExportPrimitiveType::DataTypeRSMatrix4x4
222
223    "addObj",   // RSExportPrimitiveType::DataTypeRSElement
224    "addObj",   // RSExportPrimitiveType::DataTypeRSType
225    "addObj",   // RSExportPrimitiveType::DataTypeRSAllocation
226    "addObj",   // RSExportPrimitiveType::DataTypeRSSampler
227    "addObj",   // RSExportPrimitiveType::DataTypeRSScript
228    "addObj",   // RSExportPrimitiveType::DataTypeRSMesh
229    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramFragment
230    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramVertex
231    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramRaster
232    "addObj",   // RSExportPrimitiveType::DataTypeRSProgramStore
233    "addObj",   // RSExportPrimitiveType::DataTypeRSFont
234  };
235  unsigned TypeId = EPT->getType();
236
237  if (TypeId < (sizeof(PrimitiveTypePackerAPINameMap) / sizeof(const char*)))
238    return PrimitiveTypePackerAPINameMap[ EPT->getType() ];
239
240  slangAssert(false && "GetPackerAPIName : Unknown primitive data type");
241  return NULL;
242}
243
244static std::string GetTypeName(const RSExportType *ET) {
245  switch (ET->getClass()) {
246    case RSExportType::ExportClassPrimitive: {
247      return GetPrimitiveTypeName(
248                static_cast<const RSExportPrimitiveType*>(ET));
249    }
250    case RSExportType::ExportClassPointer: {
251      const RSExportType *PointeeType =
252          static_cast<const RSExportPointerType*>(ET)->getPointeeType();
253
254      if (PointeeType->getClass() != RSExportType::ExportClassRecord)
255        return "Allocation";
256      else
257        return RS_TYPE_CLASS_NAME_PREFIX + PointeeType->getName();
258    }
259    case RSExportType::ExportClassVector: {
260      return GetVectorTypeName(static_cast<const RSExportVectorType*>(ET));
261    }
262    case RSExportType::ExportClassMatrix: {
263      return GetMatrixTypeName(static_cast<const RSExportMatrixType*>(ET));
264    }
265    case RSExportType::ExportClassConstantArray: {
266      const RSExportConstantArrayType* CAT =
267          static_cast<const RSExportConstantArrayType*>(ET);
268      std::string ElementTypeName = GetTypeName(CAT->getElementType());
269      ElementTypeName.append("[]");
270      return ElementTypeName;
271    }
272    case RSExportType::ExportClassRecord: {
273      return RS_TYPE_CLASS_NAME_PREFIX + ET->getName() +
274                 "."RS_TYPE_ITEM_CLASS_NAME;
275    }
276    default: {
277      slangAssert(false && "Unknown class of type");
278    }
279  }
280
281  return "";
282}
283
284static const char *GetTypeNullValue(const RSExportType *ET) {
285  switch (ET->getClass()) {
286    case RSExportType::ExportClassPrimitive: {
287      const RSExportPrimitiveType *EPT =
288          static_cast<const RSExportPrimitiveType*>(ET);
289      if (EPT->isRSObjectType())
290        return "null";
291      else if (EPT->getType() == RSExportPrimitiveType::DataTypeBoolean)
292        return "false";
293      else
294        return "0";
295      break;
296    }
297    case RSExportType::ExportClassPointer:
298    case RSExportType::ExportClassVector:
299    case RSExportType::ExportClassMatrix:
300    case RSExportType::ExportClassConstantArray:
301    case RSExportType::ExportClassRecord: {
302      return "null";
303      break;
304    }
305    default: {
306      slangAssert(false && "Unknown class of type");
307    }
308  }
309  return "";
310}
311
312static const char *GetBuiltinElementConstruct(const RSExportType *ET) {
313  if (ET->getClass() == RSExportType::ExportClassPrimitive) {
314    const RSExportPrimitiveType *EPT =
315        static_cast<const RSExportPrimitiveType*>(ET);
316    if (EPT->getKind() == RSExportPrimitiveType::DataKindUser) {
317      static const char *PrimitiveBuiltinElementConstructMap[] = {
318        NULL,               // RSExportPrimitiveType::DataTypeFloat16
319        "Element.F32",      // RSExportPrimitiveType::DataTypeFloat32
320        "Element.F64",      // RSExportPrimitiveType::DataTypeFloat64
321        "Element.I8",       // RSExportPrimitiveType::DataTypeSigned8
322        NULL,               // RSExportPrimitiveType::DataTypeSigned16
323        "Element.I32",      // RSExportPrimitiveType::DataTypeSigned32
324        "Element.I64",      // RSExportPrimitiveType::DataTypeSigned64
325        "Element.U8",       // RSExportPrimitiveType::DataTypeUnsigned8
326        NULL,               // RSExportPrimitiveType::DataTypeUnsigned16
327        "Element.U32",      // RSExportPrimitiveType::DataTypeUnsigned32
328        "Element.U64",      // RSExportPrimitiveType::DataTypeUnsigned64
329        "Element.BOOLEAN",  // RSExportPrimitiveType::DataTypeBoolean
330
331        NULL,   // RSExportPrimitiveType::DataTypeUnsigned565
332        NULL,   // RSExportPrimitiveType::DataTypeUnsigned5551
333        NULL,   // RSExportPrimitiveType::DataTypeUnsigned4444
334
335        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix2x2
336        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix3x3
337        NULL,   // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix4x4
338
339        "Element.ELEMENT",      // RSExportPrimitiveType::DataTypeRSElement
340        "Element.TYPE",         // RSExportPrimitiveType::DataTypeRSType
341        "Element.ALLOCATION",   // RSExportPrimitiveType::DataTypeRSAllocation
342        "Element.SAMPLER",      // RSExportPrimitiveType::DataTypeRSSampler
343        "Element.SCRIPT",       // RSExportPrimitiveType::DataTypeRSScript
344        "Element.MESH",         // RSExportPrimitiveType::DataTypeRSMesh
345        "Element.PROGRAM_FRAGMENT",
346          // RSExportPrimitiveType::DataTypeRSProgramFragment
347        "Element.PROGRAM_VERTEX",
348          // RSExportPrimitiveType::DataTypeRSProgramVertex
349        "Element.PROGRAM_RASTER",
350          // RSExportPrimitiveType::DataTypeRSProgramRaster
351        "Element.PROGRAM_STORE",
352          // RSExportPrimitiveType::DataTypeRSProgramStore
353        "Element.FONT",
354          // RSExportPrimitiveType::DataTypeRSFont
355      };
356      unsigned TypeId = EPT->getType();
357
358      if (TypeId <
359          (sizeof(PrimitiveBuiltinElementConstructMap) / sizeof(const char*)))
360        return PrimitiveBuiltinElementConstructMap[ EPT->getType() ];
361    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelA) {
362      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
363        return "Element.A_8";
364    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelRGB) {
365      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned565)
366        return "Element.RGB_565";
367      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
368        return "Element.RGB_888";
369    } else if (EPT->getKind() == RSExportPrimitiveType::DataKindPixelRGBA) {
370      if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned5551)
371        return "Element.RGBA_5551";
372      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned4444)
373        return "Element.RGBA_4444";
374      else if (EPT->getType() == RSExportPrimitiveType::DataTypeUnsigned8)
375        return "Element.RGBA_8888";
376    }
377  } else if (ET->getClass() == RSExportType::ExportClassVector) {
378    const RSExportVectorType *EVT = static_cast<const RSExportVectorType*>(ET);
379    if (EVT->getKind() == RSExportPrimitiveType::DataKindUser) {
380      if (EVT->getType() == RSExportPrimitiveType::DataTypeFloat32) {
381        if (EVT->getNumElement() == 2)
382          return "Element.F32_2";
383        else if (EVT->getNumElement() == 3)
384          return "Element.F32_3";
385        else if (EVT->getNumElement() == 4)
386          return "Element.F32_4";
387      } else if (EVT->getType() == RSExportPrimitiveType::DataTypeUnsigned8) {
388        if (EVT->getNumElement() == 4)
389          return "Element.U8_4";
390      }
391    }
392  } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
393    const RSExportMatrixType *EMT = static_cast<const RSExportMatrixType *>(ET);
394    switch (EMT->getDim()) {
395      case 2: return "Element.MATRIX_2X2";
396      case 3: return "Element.MATRIX_3X3";
397      case 4: return "Element.MATRIX_4X4";
398      default: slangAssert(false && "Unsupported dimension of matrix");
399    }
400  } else if (ET->getClass() == RSExportType::ExportClassPointer) {
401    // Treat pointer type variable as unsigned int
402    // TODO(zonr): this is target dependent
403    return "Element.USER_I32";
404  }
405
406  return NULL;
407}
408
409static const char *GetElementDataKindName(RSExportPrimitiveType::DataKind DK) {
410  static const char *ElementDataKindNameMap[] = {
411    "Element.DataKind.USER",        // RSExportPrimitiveType::DataKindUser
412    "Element.DataKind.PIXEL_L",     // RSExportPrimitiveType::DataKindPixelL
413    "Element.DataKind.PIXEL_A",     // RSExportPrimitiveType::DataKindPixelA
414    "Element.DataKind.PIXEL_LA",    // RSExportPrimitiveType::DataKindPixelLA
415    "Element.DataKind.PIXEL_RGB",   // RSExportPrimitiveType::DataKindPixelRGB
416    "Element.DataKind.PIXEL_RGBA",  // RSExportPrimitiveType::DataKindPixelRGBA
417  };
418
419  if (static_cast<unsigned>(DK) <
420      (sizeof(ElementDataKindNameMap) / sizeof(const char*)))
421    return ElementDataKindNameMap[ DK ];
422  else
423    return NULL;
424}
425
426static const char *GetElementDataTypeName(RSExportPrimitiveType::DataType DT) {
427  static const char *ElementDataTypeNameMap[] = {
428    NULL,                            // RSExportPrimitiveType::DataTypeFloat16
429    "Element.DataType.FLOAT_32",     // RSExportPrimitiveType::DataTypeFloat32
430    "Element.DataType.FLOAT_64",     // RSExportPrimitiveType::DataTypeFloat64
431    "Element.DataType.SIGNED_8",     // RSExportPrimitiveType::DataTypeSigned8
432    "Element.DataType.SIGNED_16",    // RSExportPrimitiveType::DataTypeSigned16
433    "Element.DataType.SIGNED_32",    // RSExportPrimitiveType::DataTypeSigned32
434    "Element.DataType.SIGNED_64",    // RSExportPrimitiveType::DataTypeSigned64
435    "Element.DataType.UNSIGNED_8",   // RSExportPrimitiveType::DataTypeUnsigned8
436    "Element.DataType.UNSIGNED_16",
437      // RSExportPrimitiveType::DataTypeUnsigned16
438    "Element.DataType.UNSIGNED_32",
439      // RSExportPrimitiveType::DataTypeUnsigned32
440    "Element.DataType.UNSIGNED_64",
441      // RSExportPrimitiveType::DataTypeUnsigned64
442    "Element.DataType.BOOLEAN",
443      // RSExportPrimitiveType::DataTypeBoolean
444
445    // RSExportPrimitiveType::DataTypeUnsigned565
446    "Element.DataType.UNSIGNED_5_6_5",
447    // RSExportPrimitiveType::DataTypeUnsigned5551
448    "Element.DataType.UNSIGNED_5_5_5_1",
449    // RSExportPrimitiveType::DataTypeUnsigned4444
450    "Element.DataType.UNSIGNED_4_4_4_4",
451
452    // DataTypeRSMatrix* must have been resolved in GetBuiltinElementConstruct()
453    NULL,  // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix2x2
454    NULL,  // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix3x3
455    NULL,  // (Dummy) RSExportPrimitiveType::DataTypeRSMatrix4x4
456
457    "Element.DataType.RS_ELEMENT",  // RSExportPrimitiveType::DataTypeRSElement
458    "Element.DataType.RS_TYPE",     // RSExportPrimitiveType::DataTypeRSType
459      // RSExportPrimitiveType::DataTypeRSAllocation
460    "Element.DataType.RS_ALLOCATION",
461      // RSExportPrimitiveType::DataTypeRSSampler
462    "Element.DataType.RS_SAMPLER",
463      // RSExportPrimitiveType::DataTypeRSScript
464    "Element.DataType.RS_SCRIPT",
465      // RSExportPrimitiveType::DataTypeRSMesh
466    "Element.DataType.RS_MESH",
467      // RSExportPrimitiveType::DataTypeRSProgramFragment
468    "Element.DataType.RS_PROGRAM_FRAGMENT",
469      // RSExportPrimitiveType::DataTypeRSProgramVertex
470    "Element.DataType.RS_PROGRAM_VERTEX",
471      // RSExportPrimitiveType::DataTypeRSProgramRaster
472    "Element.DataType.RS_PROGRAM_RASTER",
473      // RSExportPrimitiveType::DataTypeRSProgramStore
474    "Element.DataType.RS_PROGRAM_STORE",
475      // RSExportPrimitiveType::DataTypeRSFont
476    "Element.DataType.RS_FONT",
477  };
478
479  if (static_cast<unsigned>(DT) <
480      (sizeof(ElementDataTypeNameMap) / sizeof(const char*)))
481    return ElementDataTypeNameMap[ DT ];
482  else
483    return NULL;
484}
485
486/********************** Methods to generate script class **********************/
487bool RSReflection::genScriptClass(Context &C,
488                                  const std::string &ClassName,
489                                  std::string &ErrorMsg) {
490  if (!C.startClass(Context::AM_Public,
491                    false,
492                    ClassName,
493                    RS_SCRIPT_CLASS_SUPER_CLASS_NAME,
494                    ErrorMsg))
495    return false;
496
497  genScriptClassConstructor(C);
498
499  // Reflect export variable
500  for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(),
501           E = mRSContext->export_vars_end();
502       I != E;
503       I++)
504    genExportVariable(C, *I);
505
506  // Reflect export for each functions
507  for (RSContext::const_export_foreach_iterator
508           I = mRSContext->export_foreach_begin(),
509           E = mRSContext->export_foreach_end();
510       I != E; I++)
511    genExportForEach(C, *I);
512
513  // Reflect export function
514  for (RSContext::const_export_func_iterator
515           I = mRSContext->export_funcs_begin(),
516           E = mRSContext->export_funcs_end();
517       I != E; I++)
518    genExportFunction(C, *I);
519
520  C.endClass();
521
522  return true;
523}
524
525void RSReflection::genScriptClassConstructor(Context &C) {
526  C.indent() << "// Constructor" << std::endl;
527  C.startFunction(Context::AM_Public,
528                  false,
529                  NULL,
530                  C.getClassName(),
531                  3,
532                  "RenderScript", "rs",
533                  "Resources", "resources",
534                  "int", "id");
535  // Call constructor of super class
536  C.indent() << "super(rs, resources, id);" << std::endl;
537
538  // If an exported variable has initial value, reflect it
539
540  for (RSContext::const_export_var_iterator I = mRSContext->export_vars_begin(),
541           E = mRSContext->export_vars_end();
542       I != E;
543       I++) {
544    const RSExportVar *EV = *I;
545    if (!EV->getInit().isUninit())
546      genInitExportVariable(C, EV->getType(), EV->getName(), EV->getInit());
547  }
548
549  C.endFunction();
550
551  return;
552}
553
554void RSReflection::genInitBoolExportVariable(Context &C,
555                                             const std::string &VarName,
556                                             const clang::APValue &Val) {
557  slangAssert(!Val.isUninit() && "Not a valid initializer");
558
559  C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
560  slangAssert((Val.getKind() == clang::APValue::Int) &&
561              "Bool type has wrong initial APValue");
562
563  C.out() << ((Val.getInt().getSExtValue() == 0) ? "false" : "true")
564          << ";" << std::endl;
565
566  return;
567}
568
569void RSReflection::genInitPrimitiveExportVariable(
570      Context &C,
571      const std::string &VarName,
572      const clang::APValue &Val) {
573  slangAssert(!Val.isUninit() && "Not a valid initializer");
574
575  C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
576  switch (Val.getKind()) {
577    case clang::APValue::Int: {
578      llvm::APInt api = Val.getInt();
579      C.out() << api.getSExtValue();
580      if (api.getBitWidth() > 32) {
581        C.out() << "L";
582      }
583      break;
584    }
585    case clang::APValue::Float: {
586      llvm::APFloat apf = Val.getFloat();
587      if (&apf.getSemantics() == &llvm::APFloat::IEEEsingle) {
588        C.out() << apf.convertToFloat() << "f";
589      } else {
590        C.out() << apf.convertToDouble();
591      }
592      break;
593    }
594
595    case clang::APValue::ComplexInt:
596    case clang::APValue::ComplexFloat:
597    case clang::APValue::LValue:
598    case clang::APValue::Vector: {
599      slangAssert(false &&
600                  "Primitive type cannot have such kind of initializer");
601      break;
602    }
603    default: {
604      slangAssert(false && "Unknown kind of initializer");
605    }
606  }
607  C.out() << ";" << std::endl;
608
609  return;
610}
611
612void RSReflection::genInitExportVariable(Context &C,
613                                         const RSExportType *ET,
614                                         const std::string &VarName,
615                                         const clang::APValue &Val) {
616  slangAssert(!Val.isUninit() && "Not a valid initializer");
617
618  switch (ET->getClass()) {
619    case RSExportType::ExportClassPrimitive: {
620      const RSExportPrimitiveType *EPT =
621          static_cast<const RSExportPrimitiveType*>(ET);
622      if (EPT->getType() == RSExportPrimitiveType::DataTypeBoolean) {
623        genInitBoolExportVariable(C, VarName, Val);
624      } else {
625        genInitPrimitiveExportVariable(C, VarName, Val);
626      }
627      break;
628    }
629    case RSExportType::ExportClassPointer: {
630      if (!Val.isInt() || Val.getInt().getSExtValue() != 0)
631        std::cout << "Initializer which is non-NULL to pointer type variable "
632                     "will be ignored" << std::endl;
633      break;
634    }
635    case RSExportType::ExportClassVector: {
636      const RSExportVectorType *EVT =
637          static_cast<const RSExportVectorType*>(ET);
638      switch (Val.getKind()) {
639        case clang::APValue::Int:
640        case clang::APValue::Float: {
641          for (unsigned i = 0; i < EVT->getNumElement(); i++) {
642            std::string Name =  VarName + "." + GetVectorAccessor(i);
643            genInitPrimitiveExportVariable(C, Name, Val);
644          }
645          break;
646        }
647        case clang::APValue::Vector: {
648          C.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = new "
649                     << GetVectorTypeName(EVT) << "();" << std::endl;
650
651          unsigned NumElements =
652              std::min(static_cast<unsigned>(EVT->getNumElement()),
653                       Val.getVectorLength());
654          for (unsigned i = 0; i < NumElements; i++) {
655            const clang::APValue &ElementVal = Val.getVectorElt(i);
656            std::string Name = VarName + "." + GetVectorAccessor(i);
657            genInitPrimitiveExportVariable(C, Name, ElementVal);
658          }
659          break;
660        }
661        case clang::APValue::Uninitialized:
662        case clang::APValue::ComplexInt:
663        case clang::APValue::ComplexFloat:
664        case clang::APValue::LValue: {
665          slangAssert(false && "Unexpected type of value of initializer.");
666        }
667      }
668      break;
669    }
670    // TODO(zonr): Resolving initializer of a record (and matrix) type variable
671    // is complex. It cannot obtain by just simply evaluating the initializer
672    // expression.
673    case RSExportType::ExportClassMatrix:
674    case RSExportType::ExportClassConstantArray:
675    case RSExportType::ExportClassRecord: {
676#if 0
677      unsigned InitIndex = 0;
678      const RSExportRecordType *ERT =
679          static_cast<const RSExportRecordType*>(ET);
680
681      slangAssert((Val.getKind() == clang::APValue::Vector) &&
682          "Unexpected type of initializer for record type variable");
683
684      C.indent() << RS_EXPORT_VAR_PREFIX << VarName
685                 << " = new "RS_TYPE_CLASS_NAME_PREFIX << ERT->getName()
686                 <<  "."RS_TYPE_ITEM_CLASS_NAME"();" << std::endl;
687
688      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
689               E = ERT->fields_end();
690           I != E;
691           I++) {
692        const RSExportRecordType::Field *F = *I;
693        std::string FieldName = VarName + "." + F->getName();
694
695        if (InitIndex > Val.getVectorLength())
696          break;
697
698        genInitPrimitiveExportVariable(C,
699                                       FieldName,
700                                       Val.getVectorElt(InitIndex++));
701      }
702#endif
703      slangAssert(false && "Unsupported initializer for record/matrix/constant "
704                           "array type variable currently");
705      break;
706    }
707    default: {
708      slangAssert(false && "Unknown class of type");
709    }
710  }
711  return;
712}
713
714void RSReflection::genExportVariable(Context &C, const RSExportVar *EV) {
715  const RSExportType *ET = EV->getType();
716
717  C.indent() << "private final static int "RS_EXPORT_VAR_INDEX_PREFIX
718             << EV->getName() << " = " << C.getNextExportVarSlot() << ";"
719             << std::endl;
720
721  switch (ET->getClass()) {
722    case RSExportType::ExportClassPrimitive: {
723      genPrimitiveTypeExportVariable(C, EV);
724      break;
725    }
726    case RSExportType::ExportClassPointer: {
727      genPointerTypeExportVariable(C, EV);
728      break;
729    }
730    case RSExportType::ExportClassVector: {
731      genVectorTypeExportVariable(C, EV);
732      break;
733    }
734    case RSExportType::ExportClassMatrix: {
735      genMatrixTypeExportVariable(C, EV);
736      break;
737    }
738    case RSExportType::ExportClassConstantArray: {
739      genConstantArrayTypeExportVariable(C, EV);
740      break;
741    }
742    case RSExportType::ExportClassRecord: {
743      genRecordTypeExportVariable(C, EV);
744      break;
745    }
746    default: {
747      slangAssert(false && "Unknown class of type");
748    }
749  }
750
751  return;
752}
753
754void RSReflection::genExportFunction(Context &C, const RSExportFunc *EF) {
755  C.indent() << "private final static int "RS_EXPORT_FUNC_INDEX_PREFIX
756             << EF->getName() << " = " << C.getNextExportFuncSlot() << ";"
757             << std::endl;
758
759  // invoke_*()
760  Context::ArgTy Args;
761
762  if (EF->hasParam()) {
763    for (RSExportFunc::const_param_iterator I = EF->params_begin(),
764             E = EF->params_end();
765         I != E;
766         I++) {
767      Args.push_back(std::make_pair(GetTypeName((*I)->getType()),
768                                    (*I)->getName()));
769    }
770  }
771
772  C.startFunction(Context::AM_Public,
773                  false,
774                  "void",
775                  "invoke_" + EF->getName(/*Mangle=*/ false),
776                      // We are using un-mangled name since Java
777                      // supports method overloading.
778                  Args);
779
780  if (!EF->hasParam()) {
781    C.indent() << "invoke("RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << ");"
782               << std::endl;
783  } else {
784    const RSExportRecordType *ERT = EF->getParamPacketType();
785    std::string FieldPackerName = EF->getName() + "_fp";
786
787    if (genCreateFieldPacker(C, ERT, FieldPackerName.c_str()))
788      genPackVarOfType(C, ERT, NULL, FieldPackerName.c_str());
789
790    C.indent() << "invoke("RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName() << ", "
791               << FieldPackerName << ");" << std::endl;
792  }
793
794  C.endFunction();
795  return;
796}
797
798void RSReflection::genExportForEach(Context &C, const RSExportForEach *EF) {
799  C.indent() << "private final static int "RS_EXPORT_FOREACH_INDEX_PREFIX
800             << EF->getName() << " = " << C.getNextExportForEachSlot() << ";"
801             << std::endl;
802
803  // for_each_*()
804  Context::ArgTy Args;
805
806  std::string FieldPackerName = EF->getName() + "_fp";
807  size_t numParams = EF->getNumParameters();
808
809  slangAssert(numParams >= 1);
810  Args.push_back(std::make_pair("Allocation", "ain"));
811  //GetTypeName(RSExportPrimitiveType::DataTypeRSAllocation), "ain");
812  if (numParams >= 2) {
813    Args.push_back(std::make_pair("Allocation", "aout"));
814  }
815  if (numParams >= 3) {
816    for (RSExportFunc::const_param_iterator I = EF->params_begin(),
817             E = EF->params_end();
818         I != E;
819         I++) {
820      Args.push_back(std::make_pair(GetTypeName((*I)->getType()),
821                                    (*I)->getName()));
822    }
823  }
824
825  C.startFunction(Context::AM_Public,
826                  false,
827                  "void",
828                  "forEach_" + EF->getName(),
829                  Args);
830
831  if (numParams >= 3) {
832    const RSExportRecordType *ERT = EF->getParamPacketType();
833
834    if (genCreateFieldPacker(C, ERT, FieldPackerName.c_str()))
835      genPackVarOfType(C, ERT, NULL, FieldPackerName.c_str());
836  }
837  C.indent() << "forEach("RS_EXPORT_FOREACH_INDEX_PREFIX << EF->getName()
838             << ", ain";
839
840  switch (numParams) {
841    case 1:
842      C.out() << ", null, null);" << std::endl;
843      break;
844    case 2:
845      C.out() << ", aout, null);" << std::endl;
846      break;
847    case 3:
848    default:
849      C.out() << ", aout, " << FieldPackerName << ");" << std::endl;
850      break;
851  }
852
853  C.endFunction();
854  return;
855}
856
857void RSReflection::genPrimitiveTypeExportVariable(
858    Context &C,
859    const RSExportVar *EV) {
860  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassPrimitive)
861              && "Variable should be type of primitive here");
862
863  const RSExportPrimitiveType *EPT =
864      static_cast<const RSExportPrimitiveType*>(EV->getType());
865  const char *TypeName = GetPrimitiveTypeName(EPT);
866
867  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
868             << EV->getName() << ";" << std::endl;
869
870  // set_*()
871  if (!EV->isConst()) {
872    C.startFunction(Context::AM_Public,
873                    false,
874                    "void",
875                    "set_" + EV->getName(),
876                    1,
877                    TypeName, "v");
878    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
879
880    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName()
881               << ", v);" << std::endl;
882
883    C.endFunction();
884  }
885
886  genGetExportVariable(C, TypeName, EV->getName());
887
888  return;
889}
890
891void RSReflection::genPointerTypeExportVariable(Context &C,
892                                                const RSExportVar *EV) {
893  const RSExportType *ET = EV->getType();
894  const RSExportType *PointeeType;
895  std::string TypeName;
896
897  slangAssert((ET->getClass() == RSExportType::ExportClassPointer) &&
898              "Variable should be type of pointer here");
899
900  PointeeType = static_cast<const RSExportPointerType*>(ET)->getPointeeType();
901  TypeName = GetTypeName(ET);
902
903  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
904             << EV->getName() << ";" << std::endl;
905
906  // bind_*()
907  C.startFunction(Context::AM_Public,
908                  false,
909                  "void",
910                  "bind_" + EV->getName(),
911                  1,
912                  TypeName.c_str(), "v");
913
914  C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
915  C.indent() << "if (v == null) bindAllocation(null, "RS_EXPORT_VAR_INDEX_PREFIX
916             << EV->getName() << ");" << std::endl;
917
918  if (PointeeType->getClass() == RSExportType::ExportClassRecord)
919    C.indent() << "else bindAllocation(v.getAllocation(), "
920        RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ");"
921               << std::endl;
922  else
923    C.indent() << "else bindAllocation(v, "RS_EXPORT_VAR_INDEX_PREFIX
924               << EV->getName() << ");" << std::endl;
925
926  C.endFunction();
927
928  genGetExportVariable(C, TypeName, EV->getName());
929
930  return;
931}
932
933void RSReflection::genVectorTypeExportVariable(Context &C,
934                                               const RSExportVar *EV) {
935  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassVector) &&
936              "Variable should be type of vector here");
937
938  const RSExportVectorType *EVT =
939      static_cast<const RSExportVectorType*>(EV->getType());
940  const char *TypeName = GetVectorTypeName(EVT);
941  const char *FieldPackerName = "fp";
942
943  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
944             << EV->getName() << ";" << std::endl;
945
946  // set_*()
947  if (!EV->isConst()) {
948    C.startFunction(Context::AM_Public,
949                    false,
950                    "void",
951                    "set_" + EV->getName(),
952                    1,
953                    TypeName, "v");
954    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
955
956    if (genCreateFieldPacker(C, EVT, FieldPackerName))
957      genPackVarOfType(C, EVT, "v", FieldPackerName);
958    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
959               << FieldPackerName << ");" << std::endl;
960
961    C.endFunction();
962  }
963
964  genGetExportVariable(C, TypeName, EV->getName());
965  return;
966}
967
968void RSReflection::genMatrixTypeExportVariable(Context &C,
969                                               const RSExportVar *EV) {
970  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassMatrix) &&
971              "Variable should be type of matrix here");
972
973  const RSExportMatrixType *EMT =
974      static_cast<const RSExportMatrixType*>(EV->getType());
975  const char *TypeName = GetMatrixTypeName(EMT);
976  const char *FieldPackerName = "fp";
977
978  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
979             << EV->getName() << ";" << std::endl;
980
981  // set_*()
982  if (!EV->isConst()) {
983    C.startFunction(Context::AM_Public,
984                    false,
985                    "void",
986                    "set_" + EV->getName(),
987                    1,
988                    TypeName, "v");
989    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
990
991    if (genCreateFieldPacker(C, EMT, FieldPackerName))
992      genPackVarOfType(C, EMT, "v", FieldPackerName);
993    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
994               << FieldPackerName << ");" << std::endl;
995
996    C.endFunction();
997  }
998
999  genGetExportVariable(C, TypeName, EV->getName());
1000  return;
1001}
1002
1003void RSReflection::genConstantArrayTypeExportVariable(
1004    Context &C,
1005    const RSExportVar *EV) {
1006  slangAssert((EV->getType()->getClass() ==
1007               RSExportType::ExportClassConstantArray) &&
1008              "Variable should be type of constant array here");
1009
1010  const RSExportConstantArrayType *ECAT =
1011      static_cast<const RSExportConstantArrayType*>(EV->getType());
1012  std::string TypeName = GetTypeName(ECAT);
1013  const char *FieldPackerName = "fp";
1014
1015  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
1016             << EV->getName() << ";" << std::endl;
1017
1018  // set_*()
1019  if (!EV->isConst()) {
1020    C.startFunction(Context::AM_Public,
1021                    false,
1022                    "void",
1023                    "set_" + EV->getName(),
1024                    1,
1025                    TypeName.c_str(), "v");
1026    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
1027
1028    if (genCreateFieldPacker(C, ECAT, FieldPackerName))
1029      genPackVarOfType(C, ECAT, "v", FieldPackerName);
1030    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName() << ", "
1031               << FieldPackerName << ");" << std::endl;
1032
1033    C.endFunction();
1034  }
1035
1036  genGetExportVariable(C, TypeName, EV->getName());
1037  return;
1038}
1039
1040void RSReflection::genRecordTypeExportVariable(Context &C,
1041                                               const RSExportVar *EV) {
1042  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassRecord) &&
1043              "Variable should be type of struct here");
1044
1045  const RSExportRecordType *ERT =
1046      static_cast<const RSExportRecordType*>(EV->getType());
1047  std::string TypeName =
1048      RS_TYPE_CLASS_NAME_PREFIX + ERT->getName() + "."RS_TYPE_ITEM_CLASS_NAME;
1049  const char *FieldPackerName = "fp";
1050
1051  C.indent() << "private " << TypeName << " "RS_EXPORT_VAR_PREFIX
1052             << EV->getName() << ";" << std::endl;
1053
1054  // set_*()
1055  if (!EV->isConst()) {
1056    C.startFunction(Context::AM_Public,
1057                    false,
1058                    "void",
1059                    "set_" + EV->getName(),
1060                    1,
1061                    TypeName.c_str(), "v");
1062    C.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = v;" << std::endl;
1063
1064    if (genCreateFieldPacker(C, ERT, FieldPackerName))
1065      genPackVarOfType(C, ERT, "v", FieldPackerName);
1066    C.indent() << "setVar("RS_EXPORT_VAR_INDEX_PREFIX << EV->getName()
1067               << ", " << FieldPackerName << ");" << std::endl;
1068
1069    C.endFunction();
1070  }
1071
1072  genGetExportVariable(C, TypeName.c_str(), EV->getName());
1073  return;
1074}
1075
1076void RSReflection::genGetExportVariable(Context &C,
1077                                        const std::string &TypeName,
1078                                        const std::string &VarName) {
1079  C.startFunction(Context::AM_Public,
1080                  false,
1081                  TypeName.c_str(),
1082                  "get_" + VarName,
1083                  0);
1084
1085  C.indent() << "return "RS_EXPORT_VAR_PREFIX << VarName << ";" << std::endl;
1086
1087  C.endFunction();
1088  return;
1089}
1090
1091/******************* Methods to generate script class /end *******************/
1092
1093bool RSReflection::genCreateFieldPacker(Context &C,
1094                                        const RSExportType *ET,
1095                                        const char *FieldPackerName) {
1096  size_t AllocSize = RSExportType::GetTypeAllocSize(ET);
1097  if (AllocSize > 0)
1098    C.indent() << "FieldPacker " << FieldPackerName << " = new FieldPacker("
1099               << AllocSize << ");" << std::endl;
1100  else
1101    return false;
1102  return true;
1103}
1104
1105void RSReflection::genPackVarOfType(Context &C,
1106                                    const RSExportType *ET,
1107                                    const char *VarName,
1108                                    const char *FieldPackerName) {
1109  switch (ET->getClass()) {
1110    case RSExportType::ExportClassPrimitive:
1111    case RSExportType::ExportClassVector: {
1112      C.indent() << FieldPackerName << "."
1113                 << GetPackerAPIName(
1114                     static_cast<const RSExportPrimitiveType*>(ET))
1115                 << "(" << VarName << ");" << std::endl;
1116      break;
1117    }
1118    case RSExportType::ExportClassPointer: {
1119      // Must reflect as type Allocation in Java
1120      const RSExportType *PointeeType =
1121          static_cast<const RSExportPointerType*>(ET)->getPointeeType();
1122
1123      if (PointeeType->getClass() != RSExportType::ExportClassRecord)
1124        C.indent() << FieldPackerName << ".addI32(" << VarName
1125                   << ".getPtr());" << std::endl;
1126      else
1127        C.indent() << FieldPackerName << ".addI32(" << VarName
1128                   << ".getAllocation().getPtr());" << std::endl;
1129      break;
1130    }
1131    case RSExportType::ExportClassMatrix: {
1132      C.indent() << FieldPackerName << ".addMatrix(" << VarName << ");"
1133                 << std::endl;
1134      break;
1135    }
1136    case RSExportType::ExportClassConstantArray: {
1137      const RSExportConstantArrayType *ECAT =
1138          static_cast<const RSExportConstantArrayType *>(ET);
1139
1140      // TODO(zonr): more elegant way. Currently, we obtain the unique index
1141      //             variable (this method involves recursive call which means
1142      //             we may have more than one level loop, therefore we can't
1143      //             always use the same index variable name here) name given
1144      //             in the for-loop from counting the '.' in @VarName.
1145      unsigned Level = 0;
1146      size_t LastDotPos = 0;
1147      std::string ElementVarName(VarName);
1148
1149      while (LastDotPos != std::string::npos) {
1150        LastDotPos = ElementVarName.find_first_of('.', LastDotPos + 1);
1151        Level++;
1152      }
1153      std::string IndexVarName("ct");
1154      IndexVarName.append(llvm::utostr_32(Level));
1155
1156      C.indent() << "for (int " << IndexVarName << " = 0; " <<
1157                          IndexVarName << " < " << ECAT->getSize() << "; " <<
1158                          IndexVarName << "++)";
1159      C.startBlock();
1160
1161      ElementVarName.append("[" + IndexVarName + "]");
1162      genPackVarOfType(C, ECAT->getElementType(), ElementVarName.c_str(),
1163                       FieldPackerName);
1164
1165      C.endBlock();
1166      break;
1167    }
1168    case RSExportType::ExportClassRecord: {
1169      const RSExportRecordType *ERT =
1170          static_cast<const RSExportRecordType*>(ET);
1171      // Relative pos from now on in field packer
1172      unsigned Pos = 0;
1173
1174      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1175               E = ERT->fields_end();
1176           I != E;
1177           I++) {
1178        const RSExportRecordType::Field *F = *I;
1179        std::string FieldName;
1180        size_t FieldOffset = F->getOffsetInParent();
1181        size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1182        size_t FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1183
1184        if (VarName != NULL)
1185          FieldName = VarName + ("." + F->getName());
1186        else
1187          FieldName = F->getName();
1188
1189        if (FieldOffset > Pos)
1190          C.indent() << FieldPackerName << ".skip("
1191                     << (FieldOffset - Pos) << ");" << std::endl;
1192
1193        genPackVarOfType(C, F->getType(), FieldName.c_str(), FieldPackerName);
1194
1195        // There is padding in the field type
1196        if (FieldAllocSize > FieldStoreSize)
1197            C.indent() << FieldPackerName << ".skip("
1198                       << (FieldAllocSize - FieldStoreSize)
1199                       << ");" << std::endl;
1200
1201          Pos = FieldOffset + FieldAllocSize;
1202      }
1203
1204      // There maybe some padding after the struct
1205      size_t Padding = RSExportType::GetTypeAllocSize(ERT) - Pos;
1206      if (Padding > 0)
1207        C.indent() << FieldPackerName << ".skip(" << Padding << ");"
1208                   << std::endl;
1209      break;
1210    }
1211    default: {
1212      slangAssert(false && "Unknown class of type");
1213    }
1214  }
1215
1216  return;
1217}
1218
1219void RSReflection::genAllocateVarOfType(Context &C,
1220                                        const RSExportType *T,
1221                                        const std::string &VarName) {
1222  switch (T->getClass()) {
1223    case RSExportType::ExportClassPrimitive: {
1224      // Primitive type like int in Java has its own storage once it's declared.
1225      //
1226      // FIXME: Should we allocate storage for RS object?
1227      // if (static_cast<const RSExportPrimitiveType *>(T)->isRSObjectType())
1228      //  C.indent() << VarName << " = new " << GetTypeName(T) << "();"
1229      //             << std::endl;
1230      break;
1231    }
1232    case RSExportType::ExportClassPointer: {
1233      // Pointer type is an instance of Allocation or a TypeClass whose value is
1234      // expected to be assigned by programmer later in Java program. Therefore
1235      // we don't reflect things like [VarName] = new Allocation();
1236      C.indent() << VarName << " = null;" << std::endl;
1237      break;
1238    }
1239    case RSExportType::ExportClassConstantArray: {
1240      const RSExportConstantArrayType *ECAT =
1241          static_cast<const RSExportConstantArrayType *>(T);
1242      const RSExportType *ElementType = ECAT->getElementType();
1243
1244      C.indent() << VarName << " = new " << GetTypeName(ElementType)
1245                 << "[" << ECAT->getSize() << "];" << std::endl;
1246
1247      // Primitive type element doesn't need allocation code.
1248      if (ElementType->getClass() != RSExportType::ExportClassPrimitive) {
1249        C.indent() << "for (int $ct = 0; $ct < " << ECAT->getSize() << "; "
1250                            "$ct++)";
1251        C.startBlock();
1252
1253        std::string ElementVarName(VarName);
1254        ElementVarName.append("[$ct]");
1255        genAllocateVarOfType(C, ElementType, ElementVarName);
1256
1257        C.endBlock();
1258      }
1259      break;
1260    }
1261    case RSExportType::ExportClassVector:
1262    case RSExportType::ExportClassMatrix:
1263    case RSExportType::ExportClassRecord: {
1264      C.indent() << VarName << " = new " << GetTypeName(T) << "();"
1265                 << std::endl;
1266      break;
1267    }
1268  }
1269  return;
1270}
1271
1272void RSReflection::genNewItemBufferIfNull(Context &C,
1273                                          const char *Index) {
1274  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_NAME " == null) "
1275                  RS_TYPE_ITEM_BUFFER_NAME " = "
1276                    "new " RS_TYPE_ITEM_CLASS_NAME
1277                      "[getType().getX() /* count */];"
1278             << std::endl;
1279  if (Index != NULL)
1280    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] == null) "
1281                    RS_TYPE_ITEM_BUFFER_NAME"[" << Index << "] = "
1282                      "new "RS_TYPE_ITEM_CLASS_NAME"();" << std::endl;
1283  return;
1284}
1285
1286void RSReflection::genNewItemBufferPackerIfNull(Context &C) {
1287  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME " == null) "
1288                  RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
1289                    "new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1290                      ".sizeof * getType().getX()/* count */"
1291                        ");" << std::endl;
1292  return;
1293}
1294
1295/********************** Methods to generate type class  **********************/
1296bool RSReflection::genTypeClass(Context &C,
1297                                const RSExportRecordType *ERT,
1298                                std::string &ErrorMsg) {
1299  std::string ClassName = RS_TYPE_CLASS_NAME_PREFIX + ERT->getName();
1300
1301  if (!C.startClass(Context::AM_Public,
1302                    false,
1303                    ClassName,
1304                    RS_TYPE_CLASS_SUPER_CLASS_NAME,
1305                    ErrorMsg))
1306    return false;
1307
1308  mGeneratedFileNames->push_back(ClassName);
1309
1310  genTypeItemClass(C, ERT);
1311
1312  // Declare item buffer and item buffer packer
1313  C.indent() << "private "RS_TYPE_ITEM_CLASS_NAME" "RS_TYPE_ITEM_BUFFER_NAME"[]"
1314      ";" << std::endl;
1315  C.indent() << "private FieldPacker "RS_TYPE_ITEM_BUFFER_PACKER_NAME";"
1316             << std::endl;
1317
1318  genTypeClassConstructor(C, ERT);
1319  genTypeClassCopyToArray(C, ERT);
1320  genTypeClassItemSetter(C, ERT);
1321  genTypeClassItemGetter(C, ERT);
1322  genTypeClassComponentSetter(C, ERT);
1323  genTypeClassComponentGetter(C, ERT);
1324  genTypeClassCopyAll(C, ERT);
1325  genTypeClassResize(C);
1326
1327  C.endClass();
1328
1329  C.resetFieldIndex();
1330  C.clearFieldIndexMap();
1331
1332  return true;
1333}
1334
1335void RSReflection::genTypeItemClass(Context &C,
1336                                    const RSExportRecordType *ERT) {
1337  C.indent() << "static public class "RS_TYPE_ITEM_CLASS_NAME;
1338  C.startBlock();
1339
1340  C.indent() << "public static final int sizeof = "
1341             << RSExportType::GetTypeAllocSize(ERT) << ";" << std::endl;
1342
1343  // Member elements
1344  C.out() << std::endl;
1345  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1346           FE = ERT->fields_end();
1347       FI != FE;
1348       FI++) {
1349    C.indent() << GetTypeName((*FI)->getType()) << " " << (*FI)->getName()
1350               << ";" << std::endl;
1351  }
1352
1353  // Constructor
1354  C.out() << std::endl;
1355  C.indent() << RS_TYPE_ITEM_CLASS_NAME"()";
1356  C.startBlock();
1357
1358  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1359           FE = ERT->fields_end();
1360       FI != FE;
1361       FI++) {
1362    const RSExportRecordType::Field *F = *FI;
1363    genAllocateVarOfType(C, F->getType(), F->getName());
1364  }
1365
1366  // end Constructor
1367  C.endBlock();
1368
1369  // end Item class
1370  C.endBlock();
1371
1372  return;
1373}
1374
1375void RSReflection::genTypeClassConstructor(Context &C,
1376                                           const RSExportRecordType *ERT) {
1377  const char *RenderScriptVar = "rs";
1378
1379  C.startFunction(Context::AM_Public,
1380                  true,
1381                  "Element",
1382                  "createElement",
1383                  1,
1384                  "RenderScript", RenderScriptVar);
1385  genBuildElement(C, "eb", ERT, RenderScriptVar, /* IsInline = */false);
1386  C.endFunction();
1387
1388  C.startFunction(Context::AM_Public,
1389                  false,
1390                  NULL,
1391                  C.getClassName(),
1392                  2,
1393                  "RenderScript", RenderScriptVar,
1394                  "int", "count");
1395
1396  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1397  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1398  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1399             << std::endl;
1400  // Call init() in super class
1401  C.indent() << "init(" << RenderScriptVar << ", count);" << std::endl;
1402  C.endFunction();
1403
1404  C.startFunction(Context::AM_Public,
1405                  false,
1406                  NULL,
1407                  C.getClassName(),
1408                  3,
1409                  "RenderScript", RenderScriptVar,
1410                  "int", "count",
1411                  "int", "usages");
1412
1413  C.indent() << RS_TYPE_ITEM_BUFFER_NAME" = null;" << std::endl;
1414  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME" = null;" << std::endl;
1415  C.indent() << "mElement = createElement(" << RenderScriptVar << ");"
1416             << std::endl;
1417  // Call init() in super class
1418  C.indent() << "init(" << RenderScriptVar << ", count, usages);" << std::endl;
1419  C.endFunction();
1420
1421  return;
1422}
1423
1424void RSReflection::genTypeClassCopyToArray(Context &C,
1425                                           const RSExportRecordType *ERT) {
1426  C.startFunction(Context::AM_Private,
1427                  false,
1428                  "void",
1429                  "copyToArray",
1430                  2,
1431                  RS_TYPE_ITEM_CLASS_NAME, "i",
1432                  "int", "index");
1433
1434  genNewItemBufferPackerIfNull(C);
1435  C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1436                ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1437             << std::endl;
1438
1439  genPackVarOfType(C, ERT, "i", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1440
1441  C.endFunction();
1442  return;
1443}
1444
1445void RSReflection::genTypeClassItemSetter(Context &C,
1446                                          const RSExportRecordType *ERT) {
1447  C.startFunction(Context::AM_Public,
1448                  false,
1449                  "void",
1450                  "set",
1451                  3,
1452                  RS_TYPE_ITEM_CLASS_NAME, "i",
1453                  "int", "index",
1454                  "boolean", "copyNow");
1455  genNewItemBufferIfNull(C, NULL);
1456  C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index] = i;" << std::endl;
1457
1458  C.indent() << "if (copyNow) ";
1459  C.startBlock();
1460
1461  C.indent() << "copyToArray(i, index);" << std::endl;
1462  C.indent() << "mAllocation.setFromFieldPacker(index, "
1463                  RS_TYPE_ITEM_BUFFER_PACKER_NAME");" << std::endl;
1464
1465  // End of if (copyNow)
1466  C.endBlock();
1467
1468  C.endFunction();
1469  return;
1470}
1471
1472void RSReflection::genTypeClassItemGetter(Context &C,
1473                                          const RSExportRecordType *ERT) {
1474  C.startFunction(Context::AM_Public,
1475                  false,
1476                  RS_TYPE_ITEM_CLASS_NAME,
1477                  "get",
1478                  1,
1479                  "int", "index");
1480  C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return null;"
1481             << std::endl;
1482  C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index];" << std::endl;
1483  C.endFunction();
1484  return;
1485}
1486
1487void RSReflection::genTypeClassComponentSetter(Context &C,
1488                                               const RSExportRecordType *ERT) {
1489  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1490           FE = ERT->fields_end();
1491       FI != FE;
1492       FI++) {
1493    const RSExportRecordType::Field *F = *FI;
1494    size_t FieldOffset = F->getOffsetInParent();
1495    size_t FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1496    unsigned FieldIndex = C.getFieldIndex(F);
1497
1498    C.startFunction(Context::AM_Public,
1499                    false,
1500                    "void",
1501                    "set_" + F->getName(), 3,
1502                    "int", "index",
1503                    GetTypeName(F->getType()).c_str(), "v",
1504                    "boolean", "copyNow");
1505    genNewItemBufferPackerIfNull(C);
1506    genNewItemBufferIfNull(C, "index");
1507    C.indent() << RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1508               << " = v;" << std::endl;
1509
1510    C.indent() << "if (copyNow) ";
1511    C.startBlock();
1512
1513    if (FieldOffset > 0)
1514      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1515                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof + "
1516                 << FieldOffset << ");" << std::endl;
1517    else
1518      C.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME
1519                    ".reset(index * "RS_TYPE_ITEM_CLASS_NAME".sizeof);"
1520                 << std::endl;
1521    genPackVarOfType(C, F->getType(), "v", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
1522
1523    C.indent() << "FieldPacker fp = new FieldPacker(" << FieldStoreSize << ");"
1524               << std::endl;
1525    genPackVarOfType(C, F->getType(), "v", "fp");
1526    C.indent() << "mAllocation.setFromFieldPacker(index, " << FieldIndex
1527               << ", fp);"
1528               << std::endl;
1529
1530    // End of if (copyNow)
1531    C.endBlock();
1532
1533    C.endFunction();
1534  }
1535  return;
1536}
1537
1538void RSReflection::genTypeClassComponentGetter(Context &C,
1539                                               const RSExportRecordType *ERT) {
1540  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
1541           FE = ERT->fields_end();
1542       FI != FE;
1543       FI++) {
1544    const RSExportRecordType::Field *F = *FI;
1545    C.startFunction(Context::AM_Public,
1546                    false,
1547                    GetTypeName(F->getType()).c_str(),
1548                    "get_" + F->getName(),
1549                    1,
1550                    "int", "index");
1551    C.indent() << "if ("RS_TYPE_ITEM_BUFFER_NAME" == null) return "
1552               << GetTypeNullValue(F->getType()) << ";" << std::endl;
1553    C.indent() << "return "RS_TYPE_ITEM_BUFFER_NAME"[index]." << F->getName()
1554               << ";" << std::endl;
1555    C.endFunction();
1556  }
1557  return;
1558}
1559
1560void RSReflection::genTypeClassCopyAll(Context &C,
1561                                       const RSExportRecordType *ERT) {
1562  C.startFunction(Context::AM_Public, false, "void", "copyAll", 0);
1563
1564  C.indent() << "for (int ct = 0; ct < "RS_TYPE_ITEM_BUFFER_NAME".length; ct++)"
1565                  " copyToArray("RS_TYPE_ITEM_BUFFER_NAME"[ct], ct);"
1566             << std::endl;
1567  C.indent() << "mAllocation.setFromFieldPacker(0, "
1568                  RS_TYPE_ITEM_BUFFER_PACKER_NAME");"
1569             << std::endl;
1570
1571  C.endFunction();
1572  return;
1573}
1574
1575void RSReflection::genTypeClassResize(Context &C) {
1576  C.startFunction(Context::AM_Public,
1577                  false,
1578                  "void",
1579                  "resize",
1580                  1,
1581                  "int", "newSize");
1582
1583  C.indent() << "if (mItemArray != null) ";
1584  C.startBlock();
1585  C.indent() << "int oldSize = mItemArray.length;" << std::endl;
1586  C.indent() << "int copySize = Math.min(oldSize, newSize);" << std::endl;
1587  C.indent() << "if (newSize == oldSize) return;" << std::endl;
1588  C.indent() << "Item ni[] = new Item[newSize];" << std::endl;
1589  C.indent() << "System.arraycopy(mItemArray, 0, ni, 0, copySize);"
1590             << std::endl;
1591  C.indent() << "mItemArray = ni;" << std::endl;
1592  C.endBlock();
1593  C.indent() << "mAllocation.resize(newSize);" << std::endl;
1594
1595  C.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME " != null) "
1596                  RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
1597                    "new FieldPacker(" RS_TYPE_ITEM_CLASS_NAME
1598                      ".sizeof * getType().getX()/* count */"
1599                        ");" << std::endl;
1600
1601  C.endFunction();
1602  return;
1603}
1604
1605/******************** Methods to generate type class /end ********************/
1606
1607/********** Methods to create Element in Java of given record type ***********/
1608void RSReflection::genBuildElement(Context &C,
1609                                   const char *ElementBuilderName,
1610                                   const RSExportRecordType *ERT,
1611                                   const char *RenderScriptVar,
1612                                   bool IsInline) {
1613  C.indent() << "Element.Builder " << ElementBuilderName << " = "
1614      "new Element.Builder(" << RenderScriptVar << ");" << std::endl;
1615
1616  // eb.add(...)
1617  genAddElementToElementBuilder(C,
1618                                ERT,
1619                                "",
1620                                ElementBuilderName,
1621                                RenderScriptVar,
1622                                /* ArraySize = */0);
1623
1624  if (!IsInline)
1625    C.indent() << "return " << ElementBuilderName << ".create();" << std::endl;
1626  return;
1627}
1628
1629#define EB_ADD(x) do {                                              \
1630  C.indent() << ElementBuilderName                                  \
1631             << ".add(" << x << ", \"" << VarName << "\"";  \
1632  if (ArraySize > 0)                                                \
1633    C.out() << ", " << ArraySize;                                   \
1634  C.out() << ");" << std::endl;                                     \
1635  C.incFieldIndex();                                                \
1636} while (false)
1637
1638void RSReflection::genAddElementToElementBuilder(Context &C,
1639                                                 const RSExportType *ET,
1640                                                 const std::string &VarName,
1641                                                 const char *ElementBuilderName,
1642                                                 const char *RenderScriptVar,
1643                                                 unsigned ArraySize) {
1644  const char *ElementConstruct = GetBuiltinElementConstruct(ET);
1645
1646  if (ElementConstruct != NULL) {
1647    EB_ADD(ElementConstruct << "(" << RenderScriptVar << ")");
1648  } else {
1649    if ((ET->getClass() == RSExportType::ExportClassPrimitive) ||
1650        (ET->getClass() == RSExportType::ExportClassVector)) {
1651      const RSExportPrimitiveType *EPT =
1652          static_cast<const RSExportPrimitiveType*>(ET);
1653      const char *DataKindName = GetElementDataKindName(EPT->getKind());
1654      const char *DataTypeName = GetElementDataTypeName(EPT->getType());
1655      int Size = (ET->getClass() == RSExportType::ExportClassVector) ?
1656          static_cast<const RSExportVectorType*>(ET)->getNumElement() :
1657          1;
1658
1659      switch (EPT->getKind()) {
1660        case RSExportPrimitiveType::DataKindPixelL:
1661        case RSExportPrimitiveType::DataKindPixelA:
1662        case RSExportPrimitiveType::DataKindPixelLA:
1663        case RSExportPrimitiveType::DataKindPixelRGB:
1664        case RSExportPrimitiveType::DataKindPixelRGBA: {
1665          // Element.createPixel()
1666          EB_ADD("Element.createPixel(" << RenderScriptVar << ", "
1667                                        << DataTypeName << ", "
1668                                        << DataKindName << ")");
1669          break;
1670        }
1671        case RSExportPrimitiveType::DataKindUser:
1672        default: {
1673          if (EPT->getClass() == RSExportType::ExportClassPrimitive) {
1674            // Element.createUser()
1675            EB_ADD("Element.createUser(" << RenderScriptVar << ", "
1676                                         << DataTypeName << ")");
1677          } else {
1678            slangAssert((ET->getClass() == RSExportType::ExportClassVector) &&
1679                        "Unexpected type.");
1680            EB_ADD("Element.createVector(" << RenderScriptVar << ", "
1681                                           << DataTypeName << ", "
1682                                           << Size << ")");
1683          }
1684          break;
1685        }
1686      }
1687#ifndef NDEBUG
1688    } else if (ET->getClass() == RSExportType::ExportClassPointer) {
1689      // Pointer type variable should be resolved in
1690      // GetBuiltinElementConstruct()
1691      slangAssert(false && "??");
1692    } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
1693      // Matrix type variable should be resolved
1694      // in GetBuiltinElementConstruct()
1695      slangAssert(false && "??");
1696#endif
1697    } else if (ET->getClass() == RSExportType::ExportClassConstantArray) {
1698      const RSExportConstantArrayType *ECAT =
1699          static_cast<const RSExportConstantArrayType *>(ET);
1700
1701      const RSExportType *ElementType = ECAT->getElementType();
1702      if (ElementType->getClass() != RSExportType::ExportClassRecord) {
1703        genAddElementToElementBuilder(C,
1704                                      ECAT->getElementType(),
1705                                      VarName,
1706                                      ElementBuilderName,
1707                                      RenderScriptVar,
1708                                      ECAT->getSize());
1709      } else {
1710        std::string NewElementBuilderName(ElementBuilderName);
1711        NewElementBuilderName.append(1, '_');
1712
1713        genBuildElement(C,
1714                        NewElementBuilderName.c_str(),
1715                        static_cast<const RSExportRecordType*>(ElementType),
1716                        RenderScriptVar,
1717                        /* IsInline = */true);
1718        ArraySize = ECAT->getSize();
1719        EB_ADD(NewElementBuilderName << ".create()");
1720      }
1721    } else if (ET->getClass() == RSExportType::ExportClassRecord) {
1722      // Simalar to case of RSExportType::ExportClassRecord in genPackVarOfType.
1723      //
1724      // TODO(zonr): Generalize these two function such that there's no
1725      //             duplicated codes.
1726      const RSExportRecordType *ERT =
1727          static_cast<const RSExportRecordType*>(ET);
1728      int Pos = 0;    // relative pos from now on
1729
1730      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
1731               E = ERT->fields_end();
1732           I != E;
1733           I++) {
1734        const RSExportRecordType::Field *F = *I;
1735        std::string FieldName;
1736        int FieldOffset = F->getOffsetInParent();
1737        int FieldStoreSize = RSExportType::GetTypeStoreSize(F->getType());
1738        int FieldAllocSize = RSExportType::GetTypeAllocSize(F->getType());
1739
1740        if (!VarName.empty())
1741          FieldName = VarName + "." + F->getName();
1742        else
1743          FieldName = F->getName();
1744
1745        // Alignment
1746        genAddPaddingToElementBuiler(C,
1747                                     (FieldOffset - Pos),
1748                                     ElementBuilderName,
1749                                     RenderScriptVar);
1750
1751        // eb.add(...)
1752        C.addFieldIndexMapping(F);
1753        if (F->getType()->getClass() != RSExportType::ExportClassRecord) {
1754          genAddElementToElementBuilder(C,
1755                                        F->getType(),
1756                                        FieldName,
1757                                        ElementBuilderName,
1758                                        RenderScriptVar,
1759                                        0);
1760        } else {
1761          std::string NewElementBuilderName(ElementBuilderName);
1762          NewElementBuilderName.append(1, '_');
1763
1764          genBuildElement(C,
1765                          NewElementBuilderName.c_str(),
1766                          static_cast<const RSExportRecordType*>(F->getType()),
1767                          RenderScriptVar,
1768                          /* IsInline = */true);
1769
1770          const std::string &VarName = FieldName;  // Hack for EB_ADD macro
1771          EB_ADD(NewElementBuilderName << ".create()");
1772        }
1773
1774        // There is padding within the field type
1775        genAddPaddingToElementBuiler(C,
1776                                     (FieldAllocSize - FieldStoreSize),
1777                                     ElementBuilderName,
1778                                     RenderScriptVar);
1779
1780        Pos = FieldOffset + FieldAllocSize;
1781      }
1782
1783      // There maybe some padding after the struct
1784      size_t RecordStoreSize = RSExportType::GetTypeStoreSize(ERT);
1785
1786      genAddPaddingToElementBuiler(C,
1787                                   RecordStoreSize - Pos,
1788                                   ElementBuilderName,
1789                                   RenderScriptVar);
1790    } else {
1791      slangAssert(false && "Unknown class of type");
1792    }
1793  }
1794}
1795
1796void RSReflection::genAddPaddingToElementBuiler(Context &C,
1797                                                int PaddingSize,
1798                                                const char *ElementBuilderName,
1799                                                const char *RenderScriptVar) {
1800  unsigned ArraySize = 0;   // Hack the EB_ADD macro
1801  while (PaddingSize > 0) {
1802    const std::string &VarName = C.createPaddingField();
1803    if (PaddingSize >= 4) {
1804      EB_ADD("Element.U32(" << RenderScriptVar << ")");
1805      PaddingSize -= 4;
1806    } else if (PaddingSize >= 2) {
1807      EB_ADD("Element.U16(" << RenderScriptVar << ")");
1808      PaddingSize -= 2;
1809    } else if (PaddingSize >= 1) {
1810      EB_ADD("Element.U8(" << RenderScriptVar << ")");
1811      PaddingSize -= 1;
1812    }
1813  }
1814  return;
1815}
1816
1817#undef EB_ADD
1818/******** Methods to create Element in Java of given record type /end ********/
1819
1820bool RSReflection::reflect(const std::string &OutputPathBase,
1821                           const std::string &OutputPackageName,
1822                           const std::string &InputFileName,
1823                           const std::string &OutputBCFileName) {
1824  Context *C = NULL;
1825  std::string ResourceId = "";
1826
1827  if (!GetClassNameFromFileName(OutputBCFileName, ResourceId))
1828    return false;
1829
1830  if (ResourceId.empty())
1831    ResourceId = "<Resource ID>";
1832
1833  if (OutputPackageName.empty() || OutputPackageName == "-")
1834    C = new Context(OutputPathBase, InputFileName, "<Package Name>",
1835                    ResourceId, true);
1836  else
1837    C = new Context(OutputPathBase, InputFileName, OutputPackageName,
1838                    ResourceId, false);
1839
1840  if (C != NULL) {
1841    std::string ErrorMsg, ScriptClassName;
1842    // class ScriptC_<ScriptName>
1843    if (!GetClassNameFromFileName(InputFileName, ScriptClassName))
1844      return false;
1845
1846    if (ScriptClassName.empty())
1847      ScriptClassName = "<Input Script Name>";
1848
1849    ScriptClassName.insert(0, RS_SCRIPT_CLASS_NAME_PREFIX);
1850
1851    if (mRSContext->getLicenseNote() != NULL) {
1852      C->setLicenseNote(*(mRSContext->getLicenseNote()));
1853    }
1854
1855    if (!genScriptClass(*C, ScriptClassName, ErrorMsg)) {
1856      std::cerr << "Failed to generate class " << ScriptClassName << " ("
1857                << ErrorMsg << ")" << std::endl;
1858      return false;
1859    }
1860
1861    mGeneratedFileNames->push_back(ScriptClassName);
1862
1863    // class ScriptField_<TypeName>
1864    for (RSContext::const_export_type_iterator TI =
1865             mRSContext->export_types_begin(),
1866             TE = mRSContext->export_types_end();
1867         TI != TE;
1868         TI++) {
1869      const RSExportType *ET = TI->getValue();
1870
1871      if (ET->getClass() == RSExportType::ExportClassRecord) {
1872        const RSExportRecordType *ERT =
1873            static_cast<const RSExportRecordType*>(ET);
1874
1875        if (!ERT->isArtificial() && !genTypeClass(*C, ERT, ErrorMsg)) {
1876          std::cerr << "Failed to generate type class for struct '"
1877                    << ERT->getName() << "' (" << ErrorMsg << ")" << std::endl;
1878          return false;
1879        }
1880      }
1881    }
1882  }
1883
1884  return true;
1885}
1886
1887/************************** RSReflection::Context **************************/
1888const char *const RSReflection::Context::ApacheLicenseNote =
1889    "/*\n"
1890    " * Copyright (C) 2011 The Android Open Source Project\n"
1891    " *\n"
1892    " * Licensed under the Apache License, Version 2.0 (the \"License\");\n"
1893    " * you may not use this file except in compliance with the License.\n"
1894    " * You may obtain a copy of the License at\n"
1895    " *\n"
1896    " *      http://www.apache.org/licenses/LICENSE-2.0\n"
1897    " *\n"
1898    " * Unless required by applicable law or agreed to in writing, software\n"
1899    " * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
1900    " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or "
1901    "implied.\n"
1902    " * See the License for the specific language governing permissions and\n"
1903    " * limitations under the License.\n"
1904    " */\n"
1905    "\n";
1906
1907const char *const RSReflection::Context::Import[] = {
1908  // RenderScript java class
1909  "android.renderscript.*",
1910  // Import R
1911  "android.content.res.Resources",
1912  // Import for debugging
1913  // "android.util.Log",
1914};
1915
1916bool RSReflection::Context::openClassFile(const std::string &ClassName,
1917                                          std::string &ErrorMsg) {
1918  if (!mUseStdout) {
1919    mOF.clear();
1920    std::string Path =
1921        RSSlangReflectUtils::ComputePackagedPath(mOutputPathBase.c_str(),
1922                                                 mPackageName.c_str());
1923
1924    if (!SlangUtils::CreateDirectoryWithParents(Path, &ErrorMsg))
1925      return false;
1926
1927    std::string ClassFile = Path + OS_PATH_SEPARATOR_STR + ClassName + ".java";
1928
1929    mOF.open(ClassFile.c_str());
1930    if (!mOF.good()) {
1931      ErrorMsg = "failed to open file '" + ClassFile + "' for write";
1932      return false;
1933    }
1934  }
1935  return true;
1936}
1937
1938const char *RSReflection::Context::AccessModifierStr(AccessModifier AM) {
1939  switch (AM) {
1940    case AM_Public: return "public"; break;
1941    case AM_Protected: return "protected"; break;
1942    case AM_Private: return "private"; break;
1943    default: return ""; break;
1944  }
1945}
1946
1947bool RSReflection::Context::startClass(AccessModifier AM,
1948                                       bool IsStatic,
1949                                       const std::string &ClassName,
1950                                       const char *SuperClassName,
1951                                       std::string &ErrorMsg) {
1952  if (mVerbose)
1953    std::cout << "Generating " << ClassName << ".java ..." << std::endl;
1954
1955  // Open file for class
1956  if (!openClassFile(ClassName, ErrorMsg))
1957    return false;
1958
1959  // License
1960  out() << mLicenseNote;
1961
1962  // Notice of generated file
1963  out() << "/*" << std::endl;
1964  out() << " * This file is auto-generated. DO NOT MODIFY!" << std::endl;
1965  out() << " * The source RenderScript file: " << mInputRSFile << std::endl;
1966  out() << " */" << std::endl;
1967
1968  // Package
1969  if (!mPackageName.empty())
1970    out() << "package " << mPackageName << ";" << std::endl;
1971  out() << std::endl;
1972
1973  // Imports
1974  for (unsigned i = 0; i < (sizeof(Import) / sizeof(const char*)); i++)
1975    out() << "import " << Import[i] << ";" << std::endl;
1976  out() << std::endl;
1977
1978  // All reflected classes should be annotated as hidden, so that they won't
1979  // be exposed in SDK.
1980  out() << "/**" << std::endl;
1981  out() << " * @hide" << std::endl;
1982  out() << " */" << std::endl;
1983
1984  out() << AccessModifierStr(AM) << ((IsStatic) ? " static" : "") << " class "
1985        << ClassName;
1986  if (SuperClassName != NULL)
1987    out() << " extends " << SuperClassName;
1988
1989  startBlock();
1990
1991  mClassName = ClassName;
1992
1993  return true;
1994}
1995
1996void RSReflection::Context::endClass() {
1997  endBlock();
1998  if (!mUseStdout)
1999    mOF.close();
2000  clear();
2001  return;
2002}
2003
2004void RSReflection::Context::startBlock(bool ShouldIndent) {
2005  if (ShouldIndent)
2006    indent() << "{" << std::endl;
2007  else
2008    out() << " {" << std::endl;
2009  incIndentLevel();
2010  return;
2011}
2012
2013void RSReflection::Context::endBlock() {
2014  decIndentLevel();
2015  indent() << "}" << std::endl << std::endl;
2016  return;
2017}
2018
2019void RSReflection::Context::startTypeClass(const std::string &ClassName) {
2020  indent() << "public static class " << ClassName;
2021  startBlock();
2022  return;
2023}
2024
2025void RSReflection::Context::endTypeClass() {
2026  endBlock();
2027  return;
2028}
2029
2030void RSReflection::Context::startFunction(AccessModifier AM,
2031                                          bool IsStatic,
2032                                          const char *ReturnType,
2033                                          const std::string &FunctionName,
2034                                          int Argc, ...) {
2035  ArgTy Args;
2036  va_list vl;
2037  va_start(vl, Argc);
2038
2039  for (int i = 0; i < Argc; i++) {
2040    const char *ArgType = va_arg(vl, const char*);
2041    const char *ArgName = va_arg(vl, const char*);
2042
2043    Args.push_back(std::make_pair(ArgType, ArgName));
2044  }
2045  va_end(vl);
2046
2047  startFunction(AM, IsStatic, ReturnType, FunctionName, Args);
2048
2049  return;
2050}
2051
2052void RSReflection::Context::startFunction(AccessModifier AM,
2053                                          bool IsStatic,
2054                                          const char *ReturnType,
2055                                          const std::string &FunctionName,
2056                                          const ArgTy &Args) {
2057  indent() << AccessModifierStr(AM) << ((IsStatic) ? " static " : " ")
2058           << ((ReturnType) ? ReturnType : "") << " " << FunctionName << "(";
2059
2060  bool FirstArg = true;
2061  for (ArgTy::const_iterator I = Args.begin(), E = Args.end();
2062       I != E;
2063       I++) {
2064    if (!FirstArg)
2065      out() << ", ";
2066    else
2067      FirstArg = false;
2068
2069    out() << I->first << " " << I->second;
2070  }
2071
2072  out() << ")";
2073  startBlock();
2074
2075  return;
2076}
2077
2078void RSReflection::Context::endFunction() {
2079  endBlock();
2080  return;
2081}
2082
2083}  // namespace slang
2084