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