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