slang_rs_reflection.cpp revision d204e65f7b46a3592a254d581e4b9f2af92b6eac
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_export_reduce.h"
38#include "slang_rs_reflect_utils.h"
39#include "slang_version.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_SIZEOF_LEGACY "Item.sizeof"
49#define RS_TYPE_ITEM_SIZEOF_CURRENT "mElement.getBytesSize()"
50
51#define RS_TYPE_ITEM_BUFFER_NAME "mItemArray"
52#define RS_TYPE_ITEM_BUFFER_PACKER_NAME "mIOBuffer"
53#define RS_TYPE_ELEMENT_REF_NAME "mElementCache"
54
55#define RS_EXPORT_VAR_INDEX_PREFIX "mExportVarIdx_"
56#define RS_EXPORT_VAR_PREFIX "mExportVar_"
57#define RS_EXPORT_VAR_ELEM_PREFIX "mExportVarElem_"
58#define RS_EXPORT_VAR_DIM_PREFIX "mExportVarDim_"
59#define RS_EXPORT_VAR_CONST_PREFIX "const_"
60
61#define RS_ELEM_PREFIX "__"
62
63#define RS_FP_PREFIX "__rs_fp_"
64
65#define RS_RESOURCE_NAME "__rs_resource_name"
66
67#define RS_EXPORT_FUNC_INDEX_PREFIX "mExportFuncIdx_"
68#define RS_EXPORT_FOREACH_INDEX_PREFIX "mExportForEachIdx_"
69#define RS_EXPORT_REDUCE_INDEX_PREFIX "mExportReduceIdx_"
70#define RS_EXPORT_REDUCE_NEW_INDEX_PREFIX "mExportReduceNewIdx_"
71
72#define RS_EXPORT_VAR_ALLOCATION_PREFIX "mAlloction_"
73#define RS_EXPORT_VAR_DATA_STORAGE_PREFIX "mData_"
74
75#define SAVED_RS_REFERENCE "mRSLocal"
76
77namespace slang {
78
79class RSReflectionJavaElementBuilder {
80public:
81  RSReflectionJavaElementBuilder(const char *ElementBuilderName,
82                                 const RSExportRecordType *ERT,
83                                 const char *RenderScriptVar,
84                                 GeneratedFile *Out, const RSContext *RSContext,
85                                 RSReflectionJava *Reflection);
86  void generate();
87
88private:
89  void genAddElement(const RSExportType *ET, const std::string &VarName,
90                     unsigned ArraySize);
91  void genAddStatementStart();
92  void genAddStatementEnd(const std::string &VarName, unsigned ArraySize);
93  void genAddPadding(int PaddingSize);
94  // TODO Will remove later due to field name information is not necessary for
95  // C-reflect-to-Java
96  std::string createPaddingField() {
97    return mPaddingPrefix + llvm::itostr(mPaddingFieldIndex++);
98  }
99
100  const char *mElementBuilderName;
101  const RSExportRecordType *mERT;
102  const char *mRenderScriptVar;
103  GeneratedFile *mOut;
104  std::string mPaddingPrefix;
105  int mPaddingFieldIndex;
106  const RSContext *mRSContext;
107  RSReflectionJava *mReflection;
108};
109
110static const char *GetMatrixTypeName(const RSExportMatrixType *EMT) {
111  static const char *MatrixTypeJavaNameMap[] = {/* 2x2 */ "Matrix2f",
112                                                /* 3x3 */ "Matrix3f",
113                                                /* 4x4 */ "Matrix4f",
114  };
115  unsigned Dim = EMT->getDim();
116
117  if ((Dim - 2) < (sizeof(MatrixTypeJavaNameMap) / sizeof(const char *)))
118    return MatrixTypeJavaNameMap[EMT->getDim() - 2];
119
120  slangAssert(false && "GetMatrixTypeName : Unsupported matrix dimension");
121  return nullptr;
122}
123
124static const char *GetVectorAccessor(unsigned Index) {
125  static const char *VectorAccessorMap[] = {/* 0 */ "x",
126                                            /* 1 */ "y",
127                                            /* 2 */ "z",
128                                            /* 3 */ "w",
129  };
130
131  slangAssert((Index < (sizeof(VectorAccessorMap) / sizeof(const char *))) &&
132              "Out-of-bound index to access vector member");
133
134  return VectorAccessorMap[Index];
135}
136
137static const char *GetPackerAPIName(const RSExportPrimitiveType *EPT) {
138  static const char *PrimitiveTypePackerAPINameMap[] = {
139      "addF16",     // DataTypeFloat16
140      "addF32",     // DataTypeFloat32
141      "addF64",     // DataTypeFloat64
142      "addI8",      // DataTypeSigned8
143      "addI16",     // DataTypeSigned16
144      "addI32",     // DataTypeSigned32
145      "addI64",     // DataTypeSigned64
146      "addU8",      // DataTypeUnsigned8
147      "addU16",     // DataTypeUnsigned16
148      "addU32",     // DataTypeUnsigned32
149      "addU64",     // DataTypeUnsigned64
150      "addBoolean", // DataTypeBoolean
151      "addU16",     // DataTypeUnsigned565
152      "addU16",     // DataTypeUnsigned5551
153      "addU16",     // DataTypeUnsigned4444
154      "addMatrix",  // DataTypeRSMatrix2x2
155      "addMatrix",  // DataTypeRSMatrix3x3
156      "addMatrix",  // DataTypeRSMatrix4x4
157      "addObj",     // DataTypeRSElement
158      "addObj",     // DataTypeRSType
159      "addObj",     // DataTypeRSAllocation
160      "addObj",     // DataTypeRSSampler
161      "addObj",     // DataTypeRSScript
162      "addObj",     // DataTypeRSMesh
163      "addObj",     // DataTypeRSPath
164      "addObj",     // DataTypeRSProgramFragment
165      "addObj",     // DataTypeRSProgramVertex
166      "addObj",     // DataTypeRSProgramRaster
167      "addObj",     // DataTypeRSProgramStore
168      "addObj",     // DataTypeRSFont
169  };
170  unsigned TypeId = EPT->getType();
171
172  if (TypeId < (sizeof(PrimitiveTypePackerAPINameMap) / sizeof(const char *)))
173    return PrimitiveTypePackerAPINameMap[EPT->getType()];
174
175  slangAssert(false && "GetPackerAPIName : Unknown primitive data type");
176  return nullptr;
177}
178
179namespace {
180
181enum {
182  TypeNameWithConstantArrayBrackets = 0x01,
183  TypeNameWithRecordElementName     = 0x02,
184  TypeNameC                         = 0x04, // else Java
185  TypeNameDefault                   = TypeNameWithConstantArrayBrackets|TypeNameWithRecordElementName
186};
187
188std::string GetTypeName(const RSExportType *ET, unsigned Style = TypeNameDefault) {
189  switch (ET->getClass()) {
190  case RSExportType::ExportClassPrimitive: {
191    const auto ReflectionType =
192        RSExportPrimitiveType::getRSReflectionType(static_cast<const RSExportPrimitiveType *>(ET));
193    return (Style & TypeNameC ? ReflectionType->s_name : ReflectionType->java_name);
194  }
195  case RSExportType::ExportClassPointer: {
196    slangAssert(!(Style & TypeNameC) &&
197                "No need to support C type names for pointer types yet");
198    const RSExportType *PointeeType =
199        static_cast<const RSExportPointerType *>(ET)->getPointeeType();
200
201    if (PointeeType->getClass() != RSExportType::ExportClassRecord)
202      return "Allocation";
203    else
204      return PointeeType->getElementName();
205  }
206  case RSExportType::ExportClassVector: {
207    const RSExportVectorType *EVT = static_cast<const RSExportVectorType *>(ET);
208    const auto ReflectionType = EVT->getRSReflectionType(EVT);
209    std::stringstream VecName;
210    VecName << (Style & TypeNameC ? ReflectionType->s_name : ReflectionType->rs_java_vector_prefix)
211            << EVT->getNumElement();
212    return VecName.str();
213  }
214  case RSExportType::ExportClassMatrix: {
215    slangAssert(!(Style & TypeNameC) &&
216                "No need to support C type names for matrix types yet");
217    return GetMatrixTypeName(static_cast<const RSExportMatrixType *>(ET));
218  }
219  case RSExportType::ExportClassConstantArray: {
220    const RSExportConstantArrayType *CAT =
221        static_cast<const RSExportConstantArrayType *>(ET);
222    std::string ElementTypeName = GetTypeName(CAT->getElementType(), Style);
223    if (Style & TypeNameWithConstantArrayBrackets) {
224      slangAssert(!(Style & TypeNameC) &&
225                  "No need to support C type names for array types with brackets yet");
226      ElementTypeName.append("[]");
227    }
228    return ElementTypeName;
229  }
230  case RSExportType::ExportClassRecord: {
231    slangAssert(!(Style & TypeNameC) &&
232                "No need to support C type names for record types yet");
233    if (Style & TypeNameWithRecordElementName)
234      return ET->getElementName() + "." RS_TYPE_ITEM_CLASS_NAME;
235    else
236      return ET->getName();
237  }
238  default: { slangAssert(false && "Unknown class of type"); }
239  }
240
241  return "";
242}
243
244std::string GetReduceNewResultTypeName(const RSExportType *ET) {
245  switch (ET->getClass()) {
246    case RSExportType::ExportClassConstantArray: {
247      const RSExportConstantArrayType *const CAT = static_cast<const RSExportConstantArrayType *>(ET);
248      return "resultArray" + std::to_string(CAT->getNumElement()) + "_" +
249          GetTypeName(CAT->getElementType(),
250                      (TypeNameDefault & ~TypeNameWithRecordElementName) | TypeNameC);
251    }
252    case RSExportType::ExportClassRecord:
253      return "resultStruct_" + GetTypeName(ET,
254                                           (TypeNameDefault & ~TypeNameWithRecordElementName) | TypeNameC);
255    default:
256      return "result_" + GetTypeName(ET, TypeNameDefault | TypeNameC);
257  }
258}
259
260std::string GetReduceNewResultTypeName(const RSExportReduceNew *ER) {
261  return GetReduceNewResultTypeName(ER->getResultType());
262}
263
264} // end anonymous namespace
265
266static const char *GetTypeNullValue(const RSExportType *ET) {
267  switch (ET->getClass()) {
268  case RSExportType::ExportClassPrimitive: {
269    const RSExportPrimitiveType *EPT =
270        static_cast<const RSExportPrimitiveType *>(ET);
271    if (EPT->isRSObjectType())
272      return "null";
273    else if (EPT->getType() == DataTypeBoolean)
274      return "false";
275    else
276      return "0";
277    break;
278  }
279  case RSExportType::ExportClassPointer:
280  case RSExportType::ExportClassVector:
281  case RSExportType::ExportClassMatrix:
282  case RSExportType::ExportClassConstantArray:
283  case RSExportType::ExportClassRecord: {
284    return "null";
285    break;
286  }
287  default: { slangAssert(false && "Unknown class of type"); }
288  }
289  return "";
290}
291
292static std::string GetBuiltinElementConstruct(const RSExportType *ET) {
293  if (ET->getClass() == RSExportType::ExportClassPrimitive) {
294    return std::string("Element.") + ET->getElementName();
295  } else if (ET->getClass() == RSExportType::ExportClassVector) {
296    const RSExportVectorType *EVT = static_cast<const RSExportVectorType *>(ET);
297    if (EVT->getType() == DataTypeFloat32) {
298      if (EVT->getNumElement() == 2) {
299        return "Element.F32_2";
300      } else if (EVT->getNumElement() == 3) {
301        return "Element.F32_3";
302      } else if (EVT->getNumElement() == 4) {
303        return "Element.F32_4";
304      } else {
305        slangAssert(false && "Vectors should be size 2, 3, 4");
306      }
307    } else if (EVT->getType() == DataTypeUnsigned8) {
308      if (EVT->getNumElement() == 4)
309        return "Element.U8_4";
310    }
311  } else if (ET->getClass() == RSExportType::ExportClassMatrix) {
312    const RSExportMatrixType *EMT = static_cast<const RSExportMatrixType *>(ET);
313    switch (EMT->getDim()) {
314    case 2:
315      return "Element.MATRIX_2X2";
316    case 3:
317      return "Element.MATRIX_3X3";
318    case 4:
319      return "Element.MATRIX_4X4";
320    default:
321      slangAssert(false && "Unsupported dimension of matrix");
322    }
323  }
324  // RSExportType::ExportClassPointer can't be generated in a struct.
325
326  return "";
327}
328
329// If FromIntegerType == DestIntegerType, then Value is returned.
330// Otherwise, return a Java expression that zero-extends the value
331// Value, assumed to be of type FromIntegerType, to the integer type
332// DestIntegerType.
333//
334// Intended operations:
335//  byte  -> {byte,int,short,long}
336//  short -> {short,int,long}
337//  int   -> {int,long}
338//  long  -> long
339static std::string ZeroExtendValue(const std::string &Value,
340                                   const std::string &FromIntegerType,
341                                   const std::string &DestIntegerType) {
342#ifndef __DISABLE_ASSERTS
343  // Integer types arranged in increasing order by width
344  const std::vector<std::string> ValidTypes{"byte", "short", "int", "long"};
345  auto FromTypeLoc = std::find(ValidTypes.begin(), ValidTypes.end(), FromIntegerType);
346  auto DestTypeLoc = std::find(ValidTypes.begin(), ValidTypes.end(), DestIntegerType);
347  // Check that both types are valid.
348  slangAssert(FromTypeLoc != ValidTypes.end());
349  slangAssert(DestTypeLoc != ValidTypes.end());
350  // Check that DestIntegerType is at least as wide as FromIntegerType.
351  slangAssert(FromTypeLoc - ValidTypes.begin() <= DestTypeLoc - ValidTypes.begin());
352#endif
353
354  if (FromIntegerType == DestIntegerType) {
355    return Value;
356  }
357
358  std::string Mask, MaskLiteralType;
359  if (FromIntegerType == "byte") {
360    Mask = "0xff";
361    MaskLiteralType = "int";
362  } else if (FromIntegerType == "short") {
363    Mask = "0xffff";
364    MaskLiteralType = "int";
365  } else if (FromIntegerType == "int") {
366    Mask = "0xffffffffL";
367    MaskLiteralType = "long";
368  } else {
369    // long -> long casts should have already been handled.
370    slangAssert(false && "Unknown integer type");
371  }
372
373  // Cast the mask to the appropriate type.
374  if (MaskLiteralType != DestIntegerType) {
375    Mask = "(" + DestIntegerType + ") " + Mask;
376  }
377  return "((" + DestIntegerType + ") ((" + Value + ") & " + Mask + "))";
378}
379
380/********************** Methods to generate script class **********************/
381RSReflectionJava::RSReflectionJava(const RSContext *Context,
382                                   std::vector<std::string> *GeneratedFileNames,
383                                   const std::string &OutputBaseDirectory,
384                                   const std::string &RSSourceFileName,
385                                   const std::string &BitCodeFileName,
386                                   bool EmbedBitcodeInJava)
387    : mRSContext(Context), mPackageName(Context->getReflectJavaPackageName()),
388      mRSPackageName(Context->getRSPackageName()),
389      mOutputBaseDirectory(OutputBaseDirectory),
390      mRSSourceFileName(RSSourceFileName), mBitCodeFileName(BitCodeFileName),
391      mResourceId(RSSlangReflectUtils::JavaClassNameFromRSFileName(
392          mBitCodeFileName.c_str())),
393      mScriptClassName(RS_SCRIPT_CLASS_NAME_PREFIX +
394                       RSSlangReflectUtils::JavaClassNameFromRSFileName(
395                           mRSSourceFileName.c_str())),
396      mEmbedBitcodeInJava(EmbedBitcodeInJava), mNextExportVarSlot(0),
397      mNextExportFuncSlot(0), mNextExportForEachSlot(0),
398      mNextExportReduceSlot(0), mNextExportReduceNewSlot(0), mLastError(""),
399      mGeneratedFileNames(GeneratedFileNames), mFieldIndex(0) {
400  slangAssert(mGeneratedFileNames && "Must supply GeneratedFileNames");
401  slangAssert(!mPackageName.empty() && mPackageName != "-");
402
403  mOutputDirectory = RSSlangReflectUtils::ComputePackagedPath(
404                         OutputBaseDirectory.c_str(), mPackageName.c_str()) +
405                     OS_PATH_SEPARATOR_STR;
406
407  // mElement.getBytesSize only exists on JB+
408  if (mRSContext->getTargetAPI() >= SLANG_JB_TARGET_API) {
409      mItemSizeof = RS_TYPE_ITEM_SIZEOF_CURRENT;
410  } else {
411      mItemSizeof = RS_TYPE_ITEM_SIZEOF_LEGACY;
412  }
413}
414
415bool RSReflectionJava::genScriptClass(const std::string &ClassName,
416                                      std::string &ErrorMsg) {
417  if (!startClass(AM_Public, false, ClassName, RS_SCRIPT_CLASS_SUPER_CLASS_NAME,
418                  ErrorMsg))
419    return false;
420
421  genScriptClassConstructor();
422
423  // Reflect exported variables
424  for (auto I = mRSContext->export_vars_begin(),
425            E = mRSContext->export_vars_end();
426       I != E; I++)
427    genExportVariable(*I);
428
429  // Reflect exported forEach functions (only available on ICS+)
430  if (mRSContext->getTargetAPI() >= SLANG_ICS_TARGET_API) {
431    for (auto I = mRSContext->export_foreach_begin(),
432              E = mRSContext->export_foreach_end();
433         I != E; I++) {
434      genExportForEach(*I);
435    }
436  }
437
438  // Reflect exported reduce functions
439  for (auto I = mRSContext->export_reduce_begin(),
440            E = mRSContext->export_reduce_end();
441       I != E; ++I)
442    genExportReduce(*I);
443
444  // Reflect exported new-style reduce functions
445  for (const RSExportType *ResultType : mRSContext->getReduceNewResultTypes(
446           // FilterIn
447           exportableReduceNew,
448
449           // Compare
450           [](const RSExportType *A, const RSExportType *B)
451           { return GetReduceNewResultTypeName(A) < GetReduceNewResultTypeName(B); }))
452    genExportReduceNewResultType(ResultType);
453  for (auto I = mRSContext->export_reduce_new_begin(),
454            E = mRSContext->export_reduce_new_end();
455       I != E; ++I)
456    genExportReduceNew(*I);
457
458  // Reflect exported functions (invokable)
459  for (auto I = mRSContext->export_funcs_begin(),
460            E = mRSContext->export_funcs_end();
461       I != E; ++I)
462    genExportFunction(*I);
463
464  endClass();
465
466  return true;
467}
468
469void RSReflectionJava::genScriptClassConstructor() {
470  std::string className(RSSlangReflectUtils::JavaBitcodeClassNameFromRSFileName(
471      mRSSourceFileName.c_str()));
472  // Provide a simple way to reference this object.
473  mOut.indent() << "private static final String " RS_RESOURCE_NAME " = \""
474                << getResourceId() << "\";\n";
475
476  // Generate a simple constructor with only a single parameter (the rest
477  // can be inferred from information we already have).
478  mOut.indent() << "// Constructor\n";
479  startFunction(AM_Public, false, nullptr, getClassName(), 1, "RenderScript",
480                "rs");
481
482  const bool haveReduceExportables =
483    mRSContext->export_reduce_begin()     != mRSContext->export_reduce_end() ||
484    mRSContext->export_reduce_new_begin() != mRSContext->export_reduce_new_end();
485
486  if (getEmbedBitcodeInJava()) {
487    // Call new single argument Java-only constructor
488    mOut.indent() << "super(rs,\n";
489    mOut.indent() << "      " << RS_RESOURCE_NAME ",\n";
490    mOut.indent() << "      " << className << ".getBitCode32(),\n";
491    mOut.indent() << "      " << className << ".getBitCode64());\n";
492  } else {
493    // Call alternate constructor with required parameters.
494    // Look up the proper raw bitcode resource id via the context.
495    mOut.indent() << "this(rs,\n";
496    mOut.indent() << "     rs.getApplicationContext().getResources(),\n";
497    mOut.indent() << "     rs.getApplicationContext().getResources()."
498                     "getIdentifier(\n";
499    mOut.indent() << "         " RS_RESOURCE_NAME ", \"raw\",\n";
500    mOut.indent()
501        << "         rs.getApplicationContext().getPackageName()));\n";
502    endFunction();
503
504    // Alternate constructor (legacy) with 3 original parameters.
505    startFunction(AM_Public, false, nullptr, getClassName(), 3, "RenderScript",
506                  "rs", "Resources", "resources", "int", "id");
507    // Call constructor of super class
508    mOut.indent() << "super(rs, resources, id);\n";
509  }
510
511  // If an exported variable has initial value, reflect it
512
513  for (auto I = mRSContext->export_vars_begin(),
514            E = mRSContext->export_vars_end();
515       I != E; I++) {
516    const RSExportVar *EV = *I;
517    if (!EV->getInit().isUninit()) {
518      genInitExportVariable(EV->getType(), EV->getName(), EV->getInit());
519    } else if (EV->getArraySize()) {
520      // Always create an initial zero-init array object.
521      mOut.indent() << RS_EXPORT_VAR_PREFIX << EV->getName() << " = new "
522                    << GetTypeName(EV->getType(), TypeNameDefault & ~TypeNameWithConstantArrayBrackets) << "["
523                    << EV->getArraySize() << "];\n";
524      size_t NumInits = EV->getNumInits();
525      const RSExportConstantArrayType *ECAT =
526          static_cast<const RSExportConstantArrayType *>(EV->getType());
527      const RSExportType *ET = ECAT->getElementType();
528      for (size_t i = 0; i < NumInits; i++) {
529        std::stringstream Name;
530        Name << EV->getName() << "[" << i << "]";
531        genInitExportVariable(ET, Name.str(), EV->getInitArray(i));
532      }
533    }
534    if (mRSContext->getTargetAPI() >= SLANG_JB_TARGET_API) {
535      genTypeInstance(EV->getType());
536    }
537    genFieldPackerInstance(EV->getType());
538  }
539
540  if (haveReduceExportables) {
541    mOut.indent() << SAVED_RS_REFERENCE << " = rs;\n";
542  }
543
544  // Reflect argument / return types in kernels
545
546  for (auto I = mRSContext->export_foreach_begin(),
547            E = mRSContext->export_foreach_end();
548       I != E; I++) {
549    const RSExportForEach *EF = *I;
550
551    const RSExportForEach::InTypeVec &InTypes = EF->getInTypes();
552    for (RSExportForEach::InTypeIter BI = InTypes.begin(), EI = InTypes.end();
553         BI != EI; BI++) {
554      if (*BI != nullptr) {
555        genTypeInstanceFromPointer(*BI);
556      }
557    }
558
559    const RSExportType *OET = EF->getOutType();
560    if (OET) {
561      genTypeInstanceFromPointer(OET);
562    }
563  }
564
565  for (auto I = mRSContext->export_reduce_begin(),
566            E = mRSContext->export_reduce_end();
567       I != E; I++) {
568    const RSExportReduce *ER = *I;
569    genTypeInstance(ER->getType());
570  }
571
572  for (auto I = mRSContext->export_reduce_new_begin(),
573            E = mRSContext->export_reduce_new_end();
574       I != E; I++) {
575    const RSExportReduceNew *ER = *I;
576
577    const RSExportType *RT = ER->getResultType();
578    slangAssert(RT != nullptr);
579    if (!exportableReduceNew(RT))
580      continue;
581
582    genTypeInstance(RT);
583
584    const RSExportReduceNew::InTypeVec &InTypes = ER->getAccumulatorInTypes();
585    for (RSExportReduceNew::InTypeIter BI = InTypes.begin(), EI = InTypes.end();
586         BI != EI; BI++) {
587      slangAssert(*BI != nullptr);
588      genTypeInstance(*BI);
589    }
590  }
591
592  endFunction();
593
594  for (std::set<std::string>::iterator I = mTypesToCheck.begin(),
595                                       E = mTypesToCheck.end();
596       I != E; I++) {
597    mOut.indent() << "private Element " RS_ELEM_PREFIX << *I << ";\n";
598  }
599
600  for (std::set<std::string>::iterator I = mFieldPackerTypes.begin(),
601                                       E = mFieldPackerTypes.end();
602       I != E; I++) {
603    mOut.indent() << "private FieldPacker " RS_FP_PREFIX << *I << ";\n";
604  }
605
606  if (haveReduceExportables) {
607    // We save a private copy of rs in order to create temporary
608    // allocations in the reduce_* entry points.
609    mOut.indent() << "private RenderScript " << SAVED_RS_REFERENCE << ";\n";
610  }
611}
612
613void RSReflectionJava::genInitBoolExportVariable(const std::string &VarName,
614                                                 const clang::APValue &Val) {
615  slangAssert(!Val.isUninit() && "Not a valid initializer");
616  slangAssert((Val.getKind() == clang::APValue::Int) &&
617              "Bool type has wrong initial APValue");
618
619  mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
620
621  mOut << ((Val.getInt().getSExtValue() == 0) ? "false" : "true") << ";\n";
622}
623
624void
625RSReflectionJava::genInitPrimitiveExportVariable(const std::string &VarName,
626                                                 const clang::APValue &Val) {
627  slangAssert(!Val.isUninit() && "Not a valid initializer");
628
629  mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = ";
630  genInitValue(Val, false);
631  mOut << ";\n";
632}
633
634void RSReflectionJava::genInitExportVariable(const RSExportType *ET,
635                                             const std::string &VarName,
636                                             const clang::APValue &Val) {
637  slangAssert(!Val.isUninit() && "Not a valid initializer");
638
639  switch (ET->getClass()) {
640  case RSExportType::ExportClassPrimitive: {
641    const RSExportPrimitiveType *EPT =
642        static_cast<const RSExportPrimitiveType *>(ET);
643    if (EPT->getType() == DataTypeBoolean) {
644      genInitBoolExportVariable(VarName, Val);
645    } else {
646      genInitPrimitiveExportVariable(VarName, Val);
647    }
648    break;
649  }
650  case RSExportType::ExportClassPointer: {
651    if (!Val.isInt() || Val.getInt().getSExtValue() != 0)
652      std::cout << "Initializer which is non-NULL to pointer type variable "
653                   "will be ignored\n";
654    break;
655  }
656  case RSExportType::ExportClassVector: {
657    const RSExportVectorType *EVT = static_cast<const RSExportVectorType *>(ET);
658    switch (Val.getKind()) {
659    case clang::APValue::Int:
660    case clang::APValue::Float: {
661      for (unsigned i = 0; i < EVT->getNumElement(); i++) {
662        std::string Name = VarName + "." + GetVectorAccessor(i);
663        genInitPrimitiveExportVariable(Name, Val);
664      }
665      break;
666    }
667    case clang::APValue::Vector: {
668      std::stringstream VecName;
669      VecName << EVT->getRSReflectionType(EVT)->rs_java_vector_prefix
670              << EVT->getNumElement();
671      mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = new "
672                    << VecName.str() << "();\n";
673
674      unsigned NumElements = std::min(
675          static_cast<unsigned>(EVT->getNumElement()), Val.getVectorLength());
676      for (unsigned i = 0; i < NumElements; i++) {
677        const clang::APValue &ElementVal = Val.getVectorElt(i);
678        std::string Name = VarName + "." + GetVectorAccessor(i);
679        genInitPrimitiveExportVariable(Name, ElementVal);
680      }
681      break;
682    }
683    case clang::APValue::MemberPointer:
684    case clang::APValue::Uninitialized:
685    case clang::APValue::ComplexInt:
686    case clang::APValue::ComplexFloat:
687    case clang::APValue::LValue:
688    case clang::APValue::Array:
689    case clang::APValue::Struct:
690    case clang::APValue::Union:
691    case clang::APValue::AddrLabelDiff: {
692      slangAssert(false && "Unexpected type of value of initializer.");
693    }
694    }
695    break;
696  }
697  // TODO(zonr): Resolving initializer of a record (and matrix) type variable
698  // is complex. It cannot obtain by just simply evaluating the initializer
699  // expression.
700  case RSExportType::ExportClassMatrix:
701  case RSExportType::ExportClassConstantArray:
702  case RSExportType::ExportClassRecord: {
703#if 0
704      unsigned InitIndex = 0;
705      const RSExportRecordType *ERT =
706          static_cast<const RSExportRecordType*>(ET);
707
708      slangAssert((Val.getKind() == clang::APValue::Vector) &&
709          "Unexpected type of initializer for record type variable");
710
711      mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName
712                 << " = new " << ERT->getElementName()
713                 <<  "." RS_TYPE_ITEM_CLASS_NAME"();\n";
714
715      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
716               E = ERT->fields_end();
717           I != E;
718           I++) {
719        const RSExportRecordType::Field *F = *I;
720        std::string FieldName = VarName + "." + F->getName();
721
722        if (InitIndex > Val.getVectorLength())
723          break;
724
725        genInitPrimitiveExportVariable(FieldName,
726                                       Val.getVectorElt(InitIndex++));
727      }
728#endif
729    slangAssert(false && "Unsupported initializer for record/matrix/constant "
730                         "array type variable currently");
731    break;
732  }
733  default: { slangAssert(false && "Unknown class of type"); }
734  }
735}
736
737void RSReflectionJava::genExportVariable(const RSExportVar *EV) {
738  const RSExportType *ET = EV->getType();
739
740  mOut.indent() << "private final static int " << RS_EXPORT_VAR_INDEX_PREFIX
741                << EV->getName() << " = " << getNextExportVarSlot() << ";\n";
742
743  switch (ET->getClass()) {
744  case RSExportType::ExportClassPrimitive: {
745    genPrimitiveTypeExportVariable(EV);
746    break;
747  }
748  case RSExportType::ExportClassPointer: {
749    genPointerTypeExportVariable(EV);
750    break;
751  }
752  case RSExportType::ExportClassVector: {
753    genVectorTypeExportVariable(EV);
754    break;
755  }
756  case RSExportType::ExportClassMatrix: {
757    genMatrixTypeExportVariable(EV);
758    break;
759  }
760  case RSExportType::ExportClassConstantArray: {
761    genConstantArrayTypeExportVariable(EV);
762    break;
763  }
764  case RSExportType::ExportClassRecord: {
765    genRecordTypeExportVariable(EV);
766    break;
767  }
768  default: { slangAssert(false && "Unknown class of type"); }
769  }
770}
771
772void RSReflectionJava::genExportFunction(const RSExportFunc *EF) {
773  mOut.indent() << "private final static int " << RS_EXPORT_FUNC_INDEX_PREFIX
774                << EF->getName() << " = " << getNextExportFuncSlot() << ";\n";
775
776  // invoke_*()
777  ArgTy Args;
778
779  if (EF->hasParam()) {
780    for (RSExportFunc::const_param_iterator I = EF->params_begin(),
781                                            E = EF->params_end();
782         I != E; I++) {
783      Args.push_back(
784          std::make_pair(GetTypeName((*I)->getType()), (*I)->getName()));
785    }
786  }
787
788  if (mRSContext->getTargetAPI() >= SLANG_M_TARGET_API) {
789    startFunction(AM_Public, false, "Script.InvokeID",
790                  "getInvokeID_" + EF->getName(), 0);
791
792    mOut.indent() << "return createInvokeID(" << RS_EXPORT_FUNC_INDEX_PREFIX
793                  << EF->getName() << ");\n";
794
795    endFunction();
796  }
797
798  startFunction(AM_Public, false, "void",
799                "invoke_" + EF->getName(/*Mangle=*/false),
800                // We are using un-mangled name since Java
801                // supports method overloading.
802                Args);
803
804  if (!EF->hasParam()) {
805    mOut.indent() << "invoke(" << RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName()
806                  << ");\n";
807  } else {
808    const RSExportRecordType *ERT = EF->getParamPacketType();
809    std::string FieldPackerName = EF->getName() + "_fp";
810
811    if (genCreateFieldPacker(ERT, FieldPackerName.c_str()))
812      genPackVarOfType(ERT, nullptr, FieldPackerName.c_str());
813
814    mOut.indent() << "invoke(" << RS_EXPORT_FUNC_INDEX_PREFIX << EF->getName()
815                  << ", " << FieldPackerName << ");\n";
816  }
817
818  endFunction();
819}
820
821void RSReflectionJava::genPairwiseDimCheck(std::string name0,
822                                           std::string name1) {
823
824  mOut.indent() << "// Verify dimensions\n";
825  mOut.indent() << "t0 = " << name0 << ".getType();\n";
826  mOut.indent() << "t1 = " << name1 << ".getType();\n";
827  mOut.indent() << "if ((t0.getCount() != t1.getCount()) ||\n";
828  mOut.indent() << "    (t0.getX() != t1.getX()) ||\n";
829  mOut.indent() << "    (t0.getY() != t1.getY()) ||\n";
830  mOut.indent() << "    (t0.getZ() != t1.getZ()) ||\n";
831  mOut.indent() << "    (t0.hasFaces()   != t1.hasFaces()) ||\n";
832  mOut.indent() << "    (t0.hasMipmaps() != t1.hasMipmaps())) {\n";
833  mOut.indent() << "    throw new RSRuntimeException(\"Dimension mismatch "
834                << "between parameters " << name0 << " and " << name1
835                << "!\");\n";
836  mOut.indent() << "}\n\n";
837}
838
839void RSReflectionJava::genNullArrayCheck(const std::string &ArrayName) {
840  mOut.indent() << "// Verify that \"" << ArrayName << "\" is non-null.\n";
841  mOut.indent() << "if (" << ArrayName << " == null) {\n";
842  mOut.indent() << "    throw new RSIllegalArgumentException(\"Array \\\""
843                << ArrayName << "\\\" is null!\");\n";
844  mOut.indent() << "}\n";
845}
846
847void RSReflectionJava::genNullOrEmptyArrayCheck(const std::string &ArrayName) {
848  genNullArrayCheck(ArrayName);
849  mOut.indent() << "// Verify that \"" << ArrayName << "\" is non-empty.\n";
850  mOut.indent() << "if (" << ArrayName << ".length == 0) {\n";
851  mOut.indent() << "    throw new RSIllegalArgumentException(\"Array \\\""
852                << ArrayName << "\\\" is zero-length!\");\n";
853  mOut.indent() << "}\n";
854}
855
856void RSReflectionJava::genVectorLengthCompatibilityCheck(const std::string &ArrayName,
857                                                         unsigned VecSize) {
858  mOut.indent() << "// Verify that the array length is a multiple of the vector size.\n";
859  mOut.indent() << "if (" << ArrayName << ".length % " << std::to_string(VecSize)
860                << " != 0) {\n";
861  mOut.indent() << "    throw new RSIllegalArgumentException(\"Array \\\"" << ArrayName
862                << "\\\" is not a multiple of " << std::to_string(VecSize)
863                << " in length!\");\n";
864  mOut.indent() << "}\n";
865}
866
867void RSReflectionJava::gen1DCheck(const std::string &Name) {
868  // TODO: Check that t0.getArrayCount() == 0, when / if this API is
869  // un-hidden.
870  mOut.indent() << "Type t0 = " << Name << ".getType();\n";
871  mOut.indent() << "// Verify " << Name << " is 1D\n";
872  mOut.indent() << "if (t0.getY() != 0  ||\n";
873  mOut.indent() << "    t0.hasFaces()   ||\n";
874  mOut.indent() << "    t0.hasMipmaps()) {\n";
875  mOut.indent() << "    throw new RSIllegalArgumentException(\"Parameter "
876                << Name << " is not 1D!\");\n";
877  mOut.indent() << "}\n\n";
878}
879
880void RSReflectionJava::genExportForEach(const RSExportForEach *EF) {
881  if (EF->isDummyRoot()) {
882    // Skip reflection for dummy root() kernels. Note that we have to
883    // advance the next slot number for ForEach, however.
884    mOut.indent() << "//private final static int "
885                  << RS_EXPORT_FOREACH_INDEX_PREFIX << EF->getName() << " = "
886                  << getNextExportForEachSlot() << ";\n";
887    return;
888  }
889
890  mOut.indent() << "private final static int " << RS_EXPORT_FOREACH_INDEX_PREFIX
891                << EF->getName() << " = " << getNextExportForEachSlot()
892                << ";\n";
893
894  // forEach_*()
895  ArgTy Args;
896  bool HasAllocation = false; // at least one in/out allocation?
897
898  const RSExportForEach::InVec     &Ins     = EF->getIns();
899  const RSExportForEach::InTypeVec &InTypes = EF->getInTypes();
900  const RSExportType               *OET     = EF->getOutType();
901
902  if (Ins.size() == 1) {
903    HasAllocation = true;
904    Args.push_back(std::make_pair("Allocation", "ain"));
905
906  } else if (Ins.size() > 1) {
907    HasAllocation = true;
908    for (RSExportForEach::InIter BI = Ins.begin(), EI = Ins.end(); BI != EI;
909         BI++) {
910
911      Args.push_back(std::make_pair("Allocation",
912                                    "ain_" + (*BI)->getName().str()));
913    }
914  }
915
916  if (EF->hasOut() || EF->hasReturn()) {
917    HasAllocation = true;
918    Args.push_back(std::make_pair("Allocation", "aout"));
919  }
920
921  const RSExportRecordType *ERT = EF->getParamPacketType();
922  if (ERT) {
923    for (RSExportForEach::const_param_iterator I = EF->params_begin(),
924                                               E = EF->params_end();
925         I != E; I++) {
926      Args.push_back(
927          std::make_pair(GetTypeName((*I)->getType()), (*I)->getName()));
928    }
929  }
930
931  if (mRSContext->getTargetAPI() >= SLANG_JB_MR1_TARGET_API) {
932    startFunction(AM_Public, false, "Script.KernelID",
933                  "getKernelID_" + EF->getName(), 0);
934
935    // TODO: add element checking
936    mOut.indent() << "return createKernelID(" << RS_EXPORT_FOREACH_INDEX_PREFIX
937                  << EF->getName() << ", " << EF->getSignatureMetadata()
938                  << ", null, null);\n";
939
940    endFunction();
941  }
942
943  if (mRSContext->getTargetAPI() >= SLANG_JB_MR2_TARGET_API) {
944    if (HasAllocation) {
945      startFunction(AM_Public, false, "void", "forEach_" + EF->getName(), Args);
946
947      mOut.indent() << "forEach_" << EF->getName();
948      mOut << "(";
949
950      if (Ins.size() == 1) {
951        mOut << "ain, ";
952
953      } else if (Ins.size() > 1) {
954        for (RSExportForEach::InIter BI = Ins.begin(), EI = Ins.end(); BI != EI;
955             BI++) {
956
957          mOut << "ain_" << (*BI)->getName().str() << ", ";
958        }
959      }
960
961      if (EF->hasOut() || EF->hasReturn()) {
962        mOut << "aout, ";
963      }
964
965      if (EF->hasUsrData()) {
966        mOut << Args.back().second << ", ";
967      }
968
969      // No clipped bounds to pass in.
970      mOut << "null);\n";
971
972      endFunction();
973    }
974
975    // Add the clipped kernel parameters to the Args list.
976    Args.push_back(std::make_pair("Script.LaunchOptions", "sc"));
977  }
978
979  startFunction(AM_Public, false, "void", "forEach_" + EF->getName(), Args);
980
981  if (InTypes.size() == 1) {
982    if (InTypes.front() != nullptr) {
983      genTypeCheck(InTypes.front(), "ain");
984    }
985
986  } else if (InTypes.size() > 1) {
987    size_t Index = 0;
988    for (RSExportForEach::InTypeIter BI = InTypes.begin(), EI = InTypes.end();
989         BI != EI; BI++, ++Index) {
990
991      if (*BI != nullptr) {
992        genTypeCheck(*BI, ("ain_" + Ins[Index]->getName()).str().c_str());
993      }
994    }
995  }
996
997  if (OET) {
998    genTypeCheck(OET, "aout");
999  }
1000
1001  if (Ins.size() == 1 && (EF->hasOut() || EF->hasReturn())) {
1002    mOut.indent() << "Type t0, t1;";
1003    genPairwiseDimCheck("ain", "aout");
1004
1005  } else if (Ins.size() > 1) {
1006    mOut.indent() << "Type t0, t1;";
1007
1008    std::string In0Name = "ain_" + Ins[0]->getName().str();
1009
1010    for (size_t index = 1; index < Ins.size(); ++index) {
1011      genPairwiseDimCheck(In0Name, "ain_" + Ins[index]->getName().str());
1012    }
1013
1014    if (EF->hasOut() || EF->hasReturn()) {
1015      genPairwiseDimCheck(In0Name, "aout");
1016    }
1017  }
1018
1019  std::string FieldPackerName = EF->getName() + "_fp";
1020  if (ERT) {
1021    if (genCreateFieldPacker(ERT, FieldPackerName.c_str())) {
1022      genPackVarOfType(ERT, nullptr, FieldPackerName.c_str());
1023    }
1024  }
1025  mOut.indent() << "forEach(" << RS_EXPORT_FOREACH_INDEX_PREFIX
1026                << EF->getName();
1027
1028  if (Ins.size() == 1) {
1029    mOut << ", ain";
1030  } else if (Ins.size() > 1) {
1031    mOut << ", new Allocation[]{ain_" << Ins[0]->getName().str();
1032
1033    for (size_t index = 1; index < Ins.size(); ++index) {
1034      mOut << ", ain_" << Ins[index]->getName().str();
1035    }
1036
1037    mOut << "}";
1038
1039  } else {
1040    mOut << ", (Allocation) null";
1041  }
1042
1043  if (EF->hasOut() || EF->hasReturn())
1044    mOut << ", aout";
1045  else
1046    mOut << ", null";
1047
1048  if (EF->hasUsrData())
1049    mOut << ", " << FieldPackerName;
1050  else
1051    mOut << ", null";
1052
1053  if (mRSContext->getTargetAPI() >= SLANG_JB_MR2_TARGET_API) {
1054    mOut << ", sc);\n";
1055  } else {
1056    mOut << ");\n";
1057  }
1058
1059  endFunction();
1060}
1061
1062void RSReflectionJava::genExportReduce(const RSExportReduce *ER) {
1063  // Generate the reflected function index.
1064  mOut.indent() << "private final static int " << RS_EXPORT_REDUCE_INDEX_PREFIX
1065                << ER->getName() << " = " << getNextExportReduceSlot()
1066                << ";\n";
1067
1068  // Two variants of reduce_* entry points get generated:
1069  // Array variant:
1070  //   ty' reduce_foo(ty[] input)
1071  //   ty' reduce_foo(ty[] input, int x1, int x2)
1072  // Allocation variant:
1073  //   void reduce_foo(Allocation ain, Allocation aout)
1074  //   void reduce_foo(Allocation ain, Allocation aout, Script.LaunchOptions sc)
1075
1076  const RSExportType *Type = ER->getType();
1077  const std::string Name = ER->getName();
1078
1079  genExportReduceArrayVariant(Type, Name);
1080  genExportReduceAllocationVariant(Type, Name);
1081}
1082
1083void RSReflectionJava::genExportReduceAllocationVariant(const RSExportType *Type,
1084                                                        const std::string &KernelName) {
1085  const std::string FuncName = "reduce_" + KernelName;
1086
1087  // void reduce_foo(Allocation ain, Allocation aout)
1088  startFunction(AM_Public, false, "void", FuncName, 2,
1089                "Allocation", "ain",
1090                "Allocation", "aout");
1091  mOut.indent() << FuncName << "(ain, aout, null);\n";
1092  endFunction();
1093
1094  // void reduce_foo(Allocation ain, Allocation aout, Script.LaunchOptions sc)
1095  startFunction(AM_Public, false, "void", FuncName, 3,
1096                "Allocation", "ain",
1097                "Allocation", "aout",
1098                "Script.LaunchOptions", "sc");
1099
1100  // Type checking
1101  genTypeCheck(Type, "ain");
1102  genTypeCheck(Type, "aout");
1103
1104  // Check that the input is 1D
1105  gen1DCheck("ain");
1106
1107  // Call backend
1108
1109  // Script.reduce has the signature
1110  //
1111  // protected void
1112  // reduce(int slot, Allocation ain, Allocation aout, Script.LaunchOptions sc)
1113  mOut.indent() << "reduce("
1114                << RS_EXPORT_REDUCE_INDEX_PREFIX << KernelName
1115                << ", ain, aout, sc);\n";
1116
1117  endFunction();
1118}
1119
1120void RSReflectionJava::genExportReduceArrayVariant(const RSExportType *Type,
1121                                                   const std::string &KernelName) {
1122  // Determine if the array variant can be generated. Some type
1123  // classes cannot be reflected in Java.
1124  auto Class = Type->getClass();
1125  if (Class != RSExportType::ExportClassPrimitive &&
1126      Class != RSExportType::ExportClassVector) {
1127    return;
1128  }
1129
1130  RSReflectionTypeData TypeData;
1131  Type->convertToRTD(&TypeData);
1132
1133  // Check if the type supports reading back from an Allocation and
1134  // returning as a first class Java type. If not, the helper cannot
1135  // be generated.
1136  if (!TypeData.type->java_name || !TypeData.type->java_array_element_name ||
1137      (TypeData.vecSize > 1 && !TypeData.type->rs_java_vector_prefix)) {
1138    return;
1139  }
1140
1141  const std::string FuncName = "reduce_" + KernelName;
1142  const std::string TypeName = GetTypeName(Type);
1143  const std::string ReflectedScalarType = TypeData.type->java_name;
1144  const std::string ArrayElementType = TypeData.type->java_array_element_name;
1145  const std::string ArrayType = ArrayElementType + "[]";
1146  const std::string ElementName = Type->getElementName();
1147
1148  const uint32_t VecSize = TypeData.vecSize;
1149
1150  std::string InLength = "in.length";
1151  // Adjust the length so that it corresponds to the number of
1152  // elements in the allocation.
1153  if (VecSize > 1) {
1154    InLength += " / " + std::to_string(VecSize);
1155  }
1156
1157  // TypeName reduce_foo(ArrayElementType[] in)
1158  startFunction(AM_Public, false, TypeName.c_str(), FuncName, 1,
1159                ArrayType.c_str(), "in");
1160  genNullOrEmptyArrayCheck("in");
1161  if (VecSize > 1) {
1162    genVectorLengthCompatibilityCheck("in", VecSize);
1163  }
1164  mOut.indent() << "return " << FuncName << "(in, 0, "
1165                << InLength << ");\n";
1166  endFunction();
1167
1168  // TypeName reduce_foo(ArrayElementType[] in, int x1, int x2)
1169
1170  startFunction(AM_Public, false, TypeName.c_str(), FuncName, 3,
1171                ArrayType.c_str(), "in",
1172                "int", "x1",
1173                "int", "x2");
1174
1175  genNullOrEmptyArrayCheck("in");
1176  if (VecSize > 1) {
1177    genVectorLengthCompatibilityCheck("in", VecSize);
1178  }
1179  // Check that 0 <= x1 and x1 < x2 and x2 <= InLength
1180  mOut.indent() << "// Bounds check passed x1 and x2\n";
1181  mOut.indent() << "if (x1 < 0 || x1 >= x2 || x2 > " << InLength << ") {\n";
1182  mOut.indent() << "    throw new RSRuntimeException("
1183                << "\"Input bounds are invalid!\");\n";
1184  mOut.indent() << "}\n";
1185
1186  // Create a temporary input allocation.
1187  mOut.indent() << "Allocation ain = Allocation.createSized("
1188                << SAVED_RS_REFERENCE << ", "
1189                << RS_ELEM_PREFIX << ElementName << ", "
1190                << "x2 - x1);\n";
1191  mOut.indent() << "ain.setAutoPadding(true);\n";
1192  mOut.indent() << "ain.copy1DRangeFrom(x1, x2 - x1, in);\n";
1193
1194  // Create a temporary output allocation.
1195  mOut.indent() << "Allocation aout = Allocation.createSized("
1196                << SAVED_RS_REFERENCE << ", "
1197                << RS_ELEM_PREFIX << ElementName << ", "
1198                << "1);\n";
1199  mOut.indent() << "aout.setAutoPadding(true);\n";
1200
1201  mOut.indent() << FuncName << "(ain, aout, null);\n";
1202
1203  if (VecSize > 1) {
1204    // An allocation with vector elements is represented as an array
1205    // of primitives, so we have to extract the output from the
1206    // element array and rebuild the vector.
1207    //
1208    // E.g. for int2
1209    //
1210    // Allocation outArray = new int[2];
1211    // aout.copyTo(outArray);
1212    // int elem0 = outArray[0];
1213    // int elem1 = outArray[1];
1214    // return new Int2(elem0, elem1);
1215
1216    mOut.indent() << ArrayType << " outArray = new "
1217                  << ArrayElementType << "[" << VecSize << "];\n";
1218
1219    mOut.indent() << "aout.copy1DRangeTo(0, 1, outArray);\n";
1220
1221    for (unsigned Elem = 0; Elem < VecSize; ++Elem) {
1222      mOut.indent() << ReflectedScalarType << " elem" << Elem << " = ";
1223      std::string Index = "outArray[" + std::to_string(Elem) + "]";
1224
1225      if (ReflectedScalarType == ArrayElementType) {
1226        mOut << Index << ";\n";
1227      } else {
1228        mOut << ZeroExtendValue(Index, ArrayElementType, ReflectedScalarType) << ";\n";
1229      }
1230    }
1231
1232    mOut.indent() << "return new " << TypeName << "(";
1233    for (unsigned Elem = 0; Elem < VecSize; ++Elem) {
1234      if (Elem > 0) mOut << ", ";
1235      mOut << "elem" << Elem;
1236    }
1237    mOut << ");\n";
1238  } else {
1239    // Scalar handling.
1240    //
1241    // E.g. for int
1242    // Allocation outArray = new int[1];
1243    // aout.copyTo(outArray);
1244    // return outArray[0];
1245    mOut.indent() << ArrayType << " outArray = new " << ArrayElementType
1246                  << "[1];\n";
1247    mOut.indent() << "aout.copyTo(outArray);\n";
1248
1249    if (ReflectedScalarType == "boolean") {
1250      mOut.indent() << "return outArray[0] != 0;\n";
1251    } else if (ReflectedScalarType == ArrayElementType) {
1252      mOut.indent() << "return outArray[0];\n";
1253    } else {
1254      mOut.indent() << "return "
1255                    << ZeroExtendValue("outArray[0]",
1256                                       ArrayElementType,
1257                                       ReflectedScalarType)
1258                    << ";\n";
1259    }
1260  }
1261
1262  endFunction();
1263}
1264
1265//////////////////////////////////////////////////////////////////////////////////////////////////////
1266
1267// Reductions with certain legal result types can only be reflected for NDK, not for Java.
1268bool RSReflectionJava::exportableReduceNew(const RSExportType *ResultType) {
1269  const RSExportType *CheckType = ResultType;
1270  if (ResultType->getClass() == RSExportType::ExportClassConstantArray)
1271    CheckType = static_cast<const RSExportConstantArrayType *>(ResultType)->getElementType();
1272  if (CheckType->getClass() == RSExportType::ExportClassRecord) {
1273    // No Java reflection for struct until http://b/22236498 is resolved.
1274    return false;
1275  }
1276
1277  return true;
1278}
1279
1280namespace {
1281enum MappingComment { MappingCommentWithoutType, MappingCommentWithCType };
1282
1283// OUTPUTS
1284//   InputParamName      = name to use for input parameter
1285//   InputMappingComment = text showing the mapping from InputParamName to the corresponding
1286//                           accumulator function parameter name (and possibly type)
1287// INPUTS
1288//   NamePrefix          = beginning of parameter name (e.g., "in")
1289//   MappingComment      = whether or not InputMappingComment should contain type
1290//   ER                  = description of the reduction
1291//   InIdx               = which input (numbered from zero)
1292void getReduceNewInputStrings(std::string &InputParamName, std::string &InputMappingComment,
1293                              const std::string &NamePrefix, MappingComment Mapping,
1294                              const RSExportReduceNew *ER, size_t InIdx) {
1295  InputParamName = NamePrefix + std::to_string(InIdx+1);
1296  std::string TypeString;
1297  if (Mapping == MappingCommentWithCType) {
1298    const RSExportType *InType = ER->getAccumulatorInTypes()[InIdx];
1299    if (InType->getClass() == RSExportType::ExportClassRecord) {
1300      // convertToRTD doesn't understand this type
1301      TypeString = "/* struct <> */ ";
1302    } else {
1303      RSReflectionTypeData InTypeData;
1304      ER->getAccumulatorInTypes()[InIdx]->convertToRTD(&InTypeData);
1305      slangAssert(InTypeData.type->s_name != nullptr);
1306      if (InTypeData.vecSize > 1) {
1307        TypeString = InTypeData.type->s_name + std::to_string(InTypeData.vecSize) + " ";
1308      } else {
1309        TypeString = InTypeData.type->s_name + std::string(" ");
1310      }
1311    }
1312  }
1313  InputMappingComment = InputParamName + " = \"" + TypeString + std::string(ER->getAccumulatorIns()[InIdx]->getName()) + "\"";
1314}
1315
1316} // end anonymous namespace
1317
1318void RSReflectionJava::genExportReduceNew(const RSExportReduceNew *ER) {
1319  if (!exportableReduceNew(ER->getResultType()))
1320    return;
1321
1322  // Generate the reflected function index.
1323  mOut.indent() << "private final static int " << RS_EXPORT_REDUCE_NEW_INDEX_PREFIX
1324                << ER->getNameReduce() << " = " << getNextExportReduceNewSlot()
1325                << ";\n";
1326
1327  /****** remember resultSvType generation **********************************************************/
1328
1329  // Two variants of reduce_* entry points get generated.
1330  // Array variant:
1331  //   result_<resultSvType> reduce_<name>(<devecSiIn1Type>[] in1, ..., <devecSiInNType>[] inN)
1332  // Allocation variant:
1333  //   result_<resultSvType> reduce_<name>(Allocation in1, ..., Allocation inN)
1334  //   result_<resultSvType> reduce_<name>(Allocation in1, ..., Allocation inN, Script.LaunchOptions sc)
1335
1336  genExportReduceNewArrayVariant(ER);
1337  genExportReduceNewAllocationVariant(ER);
1338}
1339
1340void RSReflectionJava::genExportReduceNewArrayVariant(const RSExportReduceNew *ER) {
1341  // Analysis of result type.  Returns early if result type is not
1342  // suitable for array method reflection.
1343  const RSExportType *const ResultType = ER->getResultType();
1344  auto ResultTypeClass = ResultType->getClass();
1345  switch (ResultTypeClass) {
1346      case RSExportType::ExportClassConstantArray:
1347      case RSExportType::ExportClassMatrix:
1348      case RSExportType::ExportClassPrimitive:
1349      case RSExportType::ExportClassVector:
1350        // Ok
1351        break;
1352
1353      case RSExportType::ExportClassPointer:
1354        slangAssert(!"Should not get here with pointer type");
1355        return;
1356
1357      case RSExportType::ExportClassRecord:
1358        // TODO: convertToRTD() cannot handle this.  Why not?
1359        return;
1360
1361      default:
1362        slangAssert(!"Unknown export class");
1363        return;
1364  }
1365  RSReflectionTypeData ResultTypeData;
1366  ResultType->convertToRTD(&ResultTypeData);
1367  if (!ResultTypeData.type->java_name || !ResultTypeData.type->java_array_element_name ||
1368      (ResultTypeData.vecSize > 1 && !ResultTypeData.type->rs_java_vector_prefix)) {
1369    slangAssert(false);
1370    return;
1371  }
1372  const std::string ResultTypeName = GetReduceNewResultTypeName(ER);
1373
1374  // Analysis of inputs.  Returns early if some input type is not
1375  // suitable for array method reflection.
1376  llvm::SmallVector<RSReflectionTypeData, 1> InsTypeData;
1377  ArgTy Args;
1378  const auto &Ins = ER->getAccumulatorIns();
1379  const auto &InTypes = ER->getAccumulatorInTypes();
1380  slangAssert(Ins.size() == InTypes.size());
1381  InsTypeData.resize(Ins.size());
1382  llvm::SmallVector<std::string, 1> InComments;
1383  for (size_t InIdx = 0, InEnd = Ins.size(); InIdx < InEnd; ++InIdx) {
1384    const RSExportType *const InType = InTypes[InIdx];
1385    switch (InType->getClass()) {
1386      case RSExportType::ExportClassMatrix:
1387      case RSExportType::ExportClassPrimitive:
1388      case RSExportType::ExportClassVector:
1389        // Ok
1390        break;
1391
1392      case RSExportType::ExportClassConstantArray:
1393        // No
1394        return;
1395
1396      case RSExportType::ExportClassPointer:
1397        slangAssert(!"Should not get here with pointer type");
1398        return;
1399
1400      case RSExportType::ExportClassRecord:
1401        // TODO: convertToRTD() cannot handle this.  Why not?
1402        return;
1403
1404      default:
1405        slangAssert(!"Unknown export class");
1406        return;
1407    }
1408
1409    RSReflectionTypeData &InTypeData = InsTypeData[InIdx];
1410    InType->convertToRTD(&InTypeData);
1411    if (!InTypeData.type->java_name || !InTypeData.type->java_array_element_name ||
1412        (InTypeData.vecSize > 1 && !InTypeData.type->rs_java_vector_prefix)) {
1413      return;
1414    }
1415
1416    std::string InputParamName, InputComment;
1417    getReduceNewInputStrings(InputParamName, InputComment, "in", MappingCommentWithoutType, ER, InIdx);
1418    if (InTypeData.vecSize > 1)
1419      InputComment += (", flattened " + std::to_string(InTypeData.vecSize) + "-vectors");
1420    InComments.push_back(InputComment);
1421
1422    const std::string InputTypeName = std::string(InTypeData.type->java_array_element_name) + "[]";
1423    Args.push_back(std::make_pair(InputTypeName, InputParamName));
1424  }
1425
1426  const std::string MethodName = "reduce_" + ER->getNameReduce();
1427
1428  // result_<resultSvType> reduce_<name>(<devecSiIn1Type>[] in1, ..., <devecSiInNType>[] inN)
1429
1430  for (const std::string &InComment : InComments)
1431    mOut.indent() << "// " << InComment << "\n";
1432  startFunction(AM_Public, false, ResultTypeName.c_str(), MethodName, Args);
1433  slangAssert(Ins.size() == InTypes.size());
1434  slangAssert(Ins.size() == InsTypeData.size());
1435  slangAssert(Ins.size() == Args.size());
1436  std::string In1Length;
1437  std::string InputAllocationOutgoingArgumentList;
1438  std::vector<std::string> InputAllocationNames;
1439  for (size_t InIdx = 0, InEnd = Ins.size(); InIdx < InEnd; ++InIdx) {
1440    const std::string &ArgName = Args[InIdx].second;
1441    genNullArrayCheck(ArgName);
1442    std::string InLength = ArgName + ".length";
1443    const uint32_t VecSize = InsTypeData[InIdx].vecSize;
1444    if (VecSize > 1) {
1445      InLength += " / " + std::to_string(VecSize);
1446      genVectorLengthCompatibilityCheck(ArgName, VecSize);
1447    }
1448    if (InIdx == 0) {
1449      In1Length = InLength;
1450    } else {
1451      mOut.indent() << "// Verify that input array lengths are the same.\n";
1452      mOut.indent() << "if (" << In1Length << " != " << InLength << ") {\n";
1453      mOut.indent() << "    throw new RSRuntimeException(\"Array length mismatch "
1454                    << "between parameters \\\"" << Args[0].second << "\\\" and \\\"" << ArgName
1455                    << "\\\"!\");\n";
1456      mOut.indent() << "}\n";
1457    }
1458    // Create a temporary input allocation
1459    const std::string TempName = "a" + ArgName;
1460    mOut.indent() << "Allocation " << TempName << " = Allocation.createSized("
1461                  << SAVED_RS_REFERENCE << ", "
1462                  << RS_ELEM_PREFIX << InTypes[InIdx]->getElementName() << ", "
1463                  << InLength << ");\n";
1464    mOut.indent() << TempName << ".setAutoPadding(true);\n";
1465    mOut.indent() << TempName << ".copyFrom(" << ArgName << ");\n";
1466    // ... and put that input allocation on the outgoing argument list
1467    if (!InputAllocationOutgoingArgumentList.empty())
1468      InputAllocationOutgoingArgumentList += ", ";
1469    InputAllocationOutgoingArgumentList += TempName;
1470    // ... and keep track of it for setting result.mTempIns
1471    InputAllocationNames.push_back(TempName);
1472  }
1473
1474  mOut << "\n";
1475  mOut.indent() << ResultTypeName << " result = " << MethodName << "(" << InputAllocationOutgoingArgumentList << ", null);\n";
1476  if (!InputAllocationNames.empty()) {
1477    mOut.indent() << "result.mTempIns = new Allocation[]{";
1478    bool EmittedFirst = false;
1479    for (const std::string &InputAllocationName : InputAllocationNames) {
1480      if (!EmittedFirst) {
1481        EmittedFirst = true;
1482      } else {
1483        mOut << ", ";
1484      }
1485      mOut << InputAllocationName;
1486    }
1487    mOut << "};\n";
1488  }
1489  mOut.indent() << "return result;\n";
1490  endFunction();
1491}
1492
1493void RSReflectionJava::genExportReduceNewAllocationVariant(const RSExportReduceNew *ER) {
1494  const auto &Ins = ER->getAccumulatorIns();
1495  const auto &InTypes = ER->getAccumulatorInTypes();
1496  const RSExportType *ResultType = ER->getResultType();
1497
1498  llvm::SmallVector<std::string, 1> InComments;
1499  ArgTy Args;
1500  for (size_t InIdx = 0, InEnd = Ins.size(); InIdx < InEnd; ++InIdx) {
1501    std::string InputParamName, InputComment;
1502    getReduceNewInputStrings(InputParamName, InputComment, "ain", MappingCommentWithCType, ER, InIdx);
1503    InComments.push_back(InputComment);
1504    Args.push_back(std::make_pair("Allocation", InputParamName));
1505  }
1506
1507  const std::string MethodName = "reduce_" + ER->getNameReduce();
1508  const std::string ResultTypeName = GetReduceNewResultTypeName(ER);
1509
1510  // result_<resultSvType> reduce_<name>(Allocation in1, ..., Allocation inN)
1511
1512  for (const std::string &InComment : InComments)
1513    mOut.indent() << "// " << InComment << "\n";
1514  startFunction(AM_Public, false, ResultTypeName.c_str(), MethodName, Args);
1515  mOut.indent() << "return " << MethodName << "(";
1516  bool EmittedFirstArg = false;
1517  for (const auto &Arg : Args) {
1518    if (!EmittedFirstArg) {
1519      EmittedFirstArg = true;
1520    } else {
1521      mOut << ", ";
1522    }
1523    mOut << Arg.second;
1524  }
1525  mOut << ", null);\n";
1526  endFunction();
1527
1528  // result_<resultSvType> reduce_<name>(Allocation in1, ..., Allocation inN, Script.LaunchOptions sc)
1529
1530  static const char FormalOptionsName[] = "sc";
1531  Args.push_back(std::make_pair("Script.LaunchOptions", FormalOptionsName));
1532  for (const std::string &InComment : InComments)
1533    mOut.indent() << "// " << InComment << "\n";
1534  startFunction(AM_Public, false, ResultTypeName.c_str(), MethodName, Args);
1535  const std::string &In0Name = Args[0].second;
1536  // Sanity-check inputs
1537  if (Ins.size() > 1)
1538    mOut.indent() << "Type t0, t1;\n";
1539  for (size_t InIdx = 0, InEnd = Ins.size(); InIdx < InEnd; ++InIdx) {
1540    const std::string &InName = Args[InIdx].second;
1541    genTypeCheck(InTypes[InIdx], InName.c_str());
1542    if (InIdx > 0)
1543      genPairwiseDimCheck(In0Name.c_str(), InName.c_str());
1544  }
1545  // Create a temporary output allocation
1546  const char OutputAllocName[] = "aout";
1547  const size_t OutputAllocLength =
1548      ResultType->getClass() == RSExportType::ExportClassConstantArray
1549      ? static_cast<const RSExportConstantArrayType *>(ResultType)->getNumElement()
1550      : 1;
1551  mOut.indent() << "Allocation " << OutputAllocName << " = Allocation.createSized("
1552                << SAVED_RS_REFERENCE << ", "
1553                << RS_ELEM_PREFIX << ResultType->getElementName() << ", "
1554                << OutputAllocLength << ");\n";
1555  mOut.indent() << OutputAllocName << ".setAutoPadding(true);\n";
1556  // Call the underlying reduce entry point
1557  mOut.indent() << "reduce(" << RS_EXPORT_REDUCE_NEW_INDEX_PREFIX << ER->getNameReduce()
1558                << ", new Allocation[]{" << In0Name;
1559  for (size_t InIdx = 1, InEnd = Ins.size(); InIdx < InEnd; ++InIdx)
1560    mOut << ", " << Args[InIdx].second;
1561  mOut << "}, " << OutputAllocName << ", " << FormalOptionsName << ");\n";
1562  mOut.indent() << "return new " << ResultTypeName << "(" << OutputAllocName << ");\n";
1563  endFunction();
1564}
1565
1566namespace {
1567
1568// When we've copied the Allocation to a Java array, how do we
1569// further process the elements of that array?
1570enum MapFromAllocation {
1571  MapFromAllocationTrivial,  // no further processing
1572  MapFromAllocationPositive, // need to ensure elements are positive (range check)
1573  MapFromAllocationBoolean,  // need to convert elements from byte to boolean
1574  MapFromAllocationPromote   // need to zero extend elements
1575};
1576
1577// Return Java expression that maps from an Allocation element to a Java non-vector result.
1578//
1579// MFA                     = mapping kind
1580// ArrayElementTypeName    = type of InVal (having been copied out of Allocation to Java array)
1581// ReflectedScalarTypeName = type of mapped value
1582// InVal                   = input value that must be mapped
1583//
1584std::string genReduceNewResultMapping(MapFromAllocation MFA,
1585                                      const std::string &ArrayElementTypeName,
1586                                      const std::string &ReflectedScalarTypeName,
1587                                      const char *InVal) {
1588  switch (MFA) {
1589    default:
1590      slangAssert(!"Unknown MapFromAllocation");
1591      // and fall through
1592    case MapFromAllocationPositive: // range checking must be done separately
1593    case MapFromAllocationTrivial:
1594      return InVal;
1595    case MapFromAllocationBoolean:
1596      return std::string(InVal) + std::string(" != 0");
1597    case MapFromAllocationPromote:
1598      return ZeroExtendValue(InVal,
1599                             ArrayElementTypeName,
1600                             ReflectedScalarTypeName);
1601  }
1602}
1603
1604// Return Java expression that maps from an Allocation element to a Java vector result.
1605//
1606// MFA                     = mapping kind
1607// ArrayElementTypeName    = type of InVal (having been copied out of Allocation to Java array)
1608// ReflectedScalarTypeName = type of mapped value
1609// VectorTypeName          = type of vector
1610// VectorElementCount      = number of elements in the vector
1611// InArray                 = input array containing vector elements
1612// InIdx                   = index of first vector element within InArray (or nullptr, if 0)
1613//
1614std::string genReduceNewResultVectorMapping(MapFromAllocation MFA,
1615                                            const std::string &ArrayElementTypeName,
1616                                            const std::string &ReflectedScalarTypeName,
1617                                            const std::string &VectorTypeName,
1618                                            unsigned VectorElementCount,
1619                                            const char *InArray, const char *InIdx = nullptr) {
1620  std::string result = "new " + VectorTypeName + "(";
1621  for (unsigned VectorElementIdx = 0; VectorElementIdx < VectorElementCount; ++VectorElementIdx) {
1622    if (VectorElementIdx)
1623     result += ", ";
1624
1625    std::string ArrayElementName = std::string(InArray) + "[";
1626    if (InIdx)
1627      ArrayElementName += std::string(InIdx) + "+";
1628    ArrayElementName += std::to_string(VectorElementIdx) + "]";
1629
1630    result += genReduceNewResultMapping(MFA, ArrayElementTypeName, ReflectedScalarTypeName,
1631                                        ArrayElementName.c_str());
1632  }
1633  result += ")";
1634  return result;
1635}
1636
1637void genReduceNewResultRangeCheck(GeneratedFile &Out, const char *InVal) {
1638  Out.indent() << "if (" << InVal << " < 0)\n";
1639  Out.indent() << "    throw new RSRuntimeException(\"Result is not representible in Java\");\n";
1640}
1641
1642} // end anonymous namespace
1643
1644void RSReflectionJava::genExportReduceNewResultType(const RSExportType *ResultType) {
1645  if (!exportableReduceNew(ResultType))
1646    return;
1647
1648  const std::string ClassName = GetReduceNewResultTypeName(ResultType);
1649  const std::string GetMethodReturnTypeName = GetTypeName(ResultType);
1650  mOut.indent() << "// To obtain the result, invoke get(), which blocks\n";
1651  mOut.indent() << "// until the asynchronously-launched operation has completed.\n";
1652  mOut.indent() << "public static class " << ClassName;
1653  mOut.startBlock();
1654  startFunction(AM_Public, false, GetMethodReturnTypeName.c_str(), "get", 0);
1655
1656  RSReflectionTypeData TypeData;
1657  ResultType->convertToRTD(&TypeData);
1658
1659  const std::string UnbracketedResultTypeName =
1660      GetTypeName(ResultType, TypeNameDefault & ~TypeNameWithConstantArrayBrackets);
1661  const std::string ReflectedScalarTypeName = TypeData.type->java_name;
1662  // Note: MATRIX* types do not have a java_array_element_name
1663  const std::string ArrayElementTypeName =
1664      TypeData.type->java_array_element_name
1665      ? std::string(TypeData.type->java_array_element_name)
1666      : ReflectedScalarTypeName;
1667
1668  MapFromAllocation MFA = MapFromAllocationTrivial;
1669  if (std::string(TypeData.type->rs_type) == "UNSIGNED_64")
1670    MFA = MapFromAllocationPositive;
1671  else if (ReflectedScalarTypeName == "boolean")
1672    MFA = MapFromAllocationBoolean;
1673  else if (ReflectedScalarTypeName != ArrayElementTypeName)
1674    MFA = MapFromAllocationPromote;
1675
1676  mOut.indent() << "if (!mGotResult)";
1677  mOut.startBlock();
1678
1679  if (TypeData.vecSize == 1) { // result type is non-vector
1680    // <ArrayElementType>[] outArray = new <ArrayElementType>[1];
1681    // mOut.copyTo(outArray);
1682    mOut.indent() << ArrayElementTypeName << "[] outArray = new " << ArrayElementTypeName
1683                  << "[" << std::max(TypeData.arraySize, 1U) << "];\n";
1684    mOut.indent() << "mOut.copyTo(outArray);\n";
1685    if (TypeData.arraySize == 0) { // result type is non-array non-vector
1686      // mResult = outArray[0]; // but there are several special cases
1687      if (MFA == MapFromAllocationPositive)
1688        genReduceNewResultRangeCheck(mOut, "outArray[0]");
1689      mOut.indent() << "mResult = "
1690                    << genReduceNewResultMapping(MFA, ArrayElementTypeName, ReflectedScalarTypeName,
1691                                                 "outArray[0]")
1692                    << ";\n";
1693    } else { // result type is array of non-vector
1694      if (MFA == MapFromAllocationTrivial) {
1695        // mResult = outArray;
1696        mOut.indent() << "mResult = outArray;\n";
1697      } else {
1698        // <ResultType> result = new <UnbracketedResultType>[<ArrayElementCount>];
1699        // for (unsigned Idx = 0; Idx < <ArrayElementCount>; ++Idx)
1700        //   result[Idx] = <Transform>(outArray[Idx]);
1701        // mResult = result; // but there are several special cases
1702        if (MFA != MapFromAllocationPositive) {
1703          mOut.indent() << GetTypeName(ResultType) << " result = new "
1704                        << UnbracketedResultTypeName
1705                        << "[" << TypeData.arraySize << "];\n";
1706        }
1707        mOut.indent() << "for (int Idx = 0; Idx < " << TypeData.arraySize << "; ++Idx)";
1708        mOut.startBlock();
1709        if (MFA == MapFromAllocationPositive) {
1710          genReduceNewResultRangeCheck(mOut, "outArray[Idx]");
1711        } else {
1712          mOut.indent() << "result[Idx] = "
1713                        << genReduceNewResultMapping(MFA, ArrayElementTypeName, ReflectedScalarTypeName,
1714                                                     "outArray[Idx]")
1715                        << ";\n";
1716        }
1717        mOut.endBlock();
1718        mOut.indent() << "mResult = " << (MFA == MapFromAllocationPositive ? "outArray" : "result") << ";\n";
1719      }
1720    }
1721  } else { // result type is vector or array of vector
1722    // <ArrayElementType>[] outArray = new <ArrayElementType>[<VectorElementCount> * <ArrayElementCount>];
1723    // mOut.copyTo(outArray);
1724    const unsigned VectorElementCount = TypeData.vecSize;
1725    const unsigned OutArrayElementCount = VectorElementCount * std::max(TypeData.arraySize, 1U);
1726    mOut.indent() << ArrayElementTypeName << "[] outArray = new " << ArrayElementTypeName
1727                  << "[" << OutArrayElementCount << "];\n";
1728    mOut.indent() << "mOut.copyTo(outArray);\n";
1729    if (MFA == MapFromAllocationPositive) {
1730      mOut.indent() << "for (int Idx = 0; Idx < " << OutArrayElementCount << "; ++Idx)";
1731      mOut.startBlock();
1732      genReduceNewResultRangeCheck(mOut, "outArray[Idx]");
1733      mOut.endBlock();
1734    }
1735    if (TypeData.arraySize == 0) { // result type is vector
1736      // mResult = new <ResultType>(outArray[0], outArray[1] ...); // but there are several special cases
1737      mOut.indent() << "mResult = "
1738                    << genReduceNewResultVectorMapping(MFA,
1739                                                       ArrayElementTypeName, ReflectedScalarTypeName,
1740                                                       GetTypeName(ResultType), VectorElementCount,
1741                                                       "outArray")
1742                    << ";\n";
1743    } else { // result type is array of vector
1744      // <ResultType> result = new <UnbracketedResultType>[<ArrayElementCount>];
1745      // for (unsigned Idx = 0; Idx < <ArrayElementCount>; ++Idx)
1746      //   result[Idx] = new <UnbracketedResultType>(outArray[<ArrayElementCount>*Idx+0],
1747      //                                             outArray[<ArrayElementCount>*Idx+1]...);
1748      // mResult = result; // but there are several special cases
1749      mOut.indent() << GetTypeName(ResultType) << " result = new "
1750                    << UnbracketedResultTypeName
1751                    << "[" << TypeData.arraySize << "];\n";
1752      mOut.indent() << "for (int Idx = 0; Idx < " << TypeData.arraySize << "; ++Idx)";
1753      mOut.startBlock();
1754      mOut.indent() << "result[Idx] = "
1755                    << genReduceNewResultVectorMapping(MFA,
1756                                                       ArrayElementTypeName, ReflectedScalarTypeName,
1757                                                       UnbracketedResultTypeName, VectorElementCount,
1758                                                       "outArray", (std::to_string(VectorElementCount) + "*Idx").c_str())
1759                    << ";\n";
1760      mOut.endBlock();
1761      mOut.indent() << "mResult = result;\n";
1762    }
1763  }
1764
1765  mOut.indent() << "mOut.destroy();\n";
1766  mOut.indent() << "mOut = null;  // make Java object eligible for garbage collection\n";
1767  mOut.indent() << "if (mTempIns != null)";
1768  mOut.startBlock();
1769  mOut.indent() << "for (Allocation tempIn : mTempIns)";
1770  mOut.startBlock();
1771  mOut.indent() << "tempIn.destroy();\n";
1772  mOut.endBlock();
1773  mOut.indent() << "mTempIns = null;  // make Java objects eligible for garbage collection\n";
1774  mOut.endBlock();
1775  mOut.indent() << "mGotResult = true;\n";
1776  mOut.endBlock();
1777
1778  mOut.indent() << "return mResult;\n";
1779  endFunction();
1780
1781  startFunction(AM_Private, false, nullptr, ClassName, 1, "Allocation", "out");
1782  // TODO: Generate allocation type check and size check?  Or move
1783  // responsibility for instantiating the Allocation here, instead of
1784  // the reduce_* method?
1785  mOut.indent() << "mTempIns = null;\n";
1786  mOut.indent() << "mOut = out;\n";
1787  mOut.indent() << "mGotResult = false;\n";
1788  endFunction();
1789  mOut.indent() << "private Allocation[] mTempIns;\n";
1790  mOut.indent() << "private Allocation mOut;\n";
1791  // TODO: If result is reference type rather than primitive type, we
1792  // could omit mGotResult and use mResult==null to indicate that we
1793  // haven't obtained the result yet.
1794  mOut.indent() << "private boolean mGotResult;\n";
1795  mOut.indent() << "private " << GetMethodReturnTypeName << " mResult;\n";
1796  mOut.endBlock();
1797}
1798
1799//////////////////////////////////////////////////////////////////////////////////////////////////////
1800
1801void RSReflectionJava::genTypeInstanceFromPointer(const RSExportType *ET) {
1802  if (ET->getClass() == RSExportType::ExportClassPointer) {
1803    // For pointer parameters to original forEach kernels.
1804    const RSExportPointerType *EPT =
1805        static_cast<const RSExportPointerType *>(ET);
1806    genTypeInstance(EPT->getPointeeType());
1807  } else {
1808    // For handling pass-by-value kernel parameters.
1809    genTypeInstance(ET);
1810  }
1811}
1812
1813void RSReflectionJava::genTypeInstance(const RSExportType *ET) {
1814  switch (ET->getClass()) {
1815  case RSExportType::ExportClassPrimitive:
1816  case RSExportType::ExportClassVector:
1817  case RSExportType::ExportClassConstantArray: {
1818    std::string TypeName = ET->getElementName();
1819    if (addTypeNameForElement(TypeName)) {
1820      mOut.indent() << RS_ELEM_PREFIX << TypeName << " = Element." << TypeName
1821                    << "(rs);\n";
1822    }
1823    break;
1824  }
1825
1826  case RSExportType::ExportClassRecord: {
1827    std::string ClassName = ET->getElementName();
1828    if (addTypeNameForElement(ClassName)) {
1829      mOut.indent() << RS_ELEM_PREFIX << ClassName << " = " << ClassName
1830                    << ".createElement(rs);\n";
1831    }
1832    break;
1833  }
1834
1835  default:
1836    break;
1837  }
1838}
1839
1840void RSReflectionJava::genFieldPackerInstance(const RSExportType *ET) {
1841  switch (ET->getClass()) {
1842  case RSExportType::ExportClassPrimitive:
1843  case RSExportType::ExportClassVector:
1844  case RSExportType::ExportClassConstantArray:
1845  case RSExportType::ExportClassRecord: {
1846    std::string TypeName = ET->getElementName();
1847    addTypeNameForFieldPacker(TypeName);
1848    break;
1849  }
1850
1851  default:
1852    break;
1853  }
1854}
1855
1856void RSReflectionJava::genTypeCheck(const RSExportType *ET,
1857                                    const char *VarName) {
1858  mOut.indent() << "// check " << VarName << "\n";
1859
1860  if (ET->getClass() == RSExportType::ExportClassPointer) {
1861    const RSExportPointerType *EPT =
1862        static_cast<const RSExportPointerType *>(ET);
1863    ET = EPT->getPointeeType();
1864  }
1865
1866  std::string TypeName;
1867
1868  switch (ET->getClass()) {
1869  case RSExportType::ExportClassPrimitive:
1870  case RSExportType::ExportClassVector:
1871  case RSExportType::ExportClassRecord: {
1872    TypeName = ET->getElementName();
1873    break;
1874  }
1875
1876  default:
1877    break;
1878  }
1879
1880  if (!TypeName.empty()) {
1881    mOut.indent() << "if (!" << VarName
1882                  << ".getType().getElement().isCompatible(" RS_ELEM_PREFIX
1883                  << TypeName << ")) {\n";
1884    mOut.indent() << "    throw new RSRuntimeException(\"Type mismatch with "
1885                  << TypeName << "!\");\n";
1886    mOut.indent() << "}\n";
1887  }
1888}
1889
1890void RSReflectionJava::genPrimitiveTypeExportVariable(const RSExportVar *EV) {
1891  slangAssert(
1892      (EV->getType()->getClass() == RSExportType::ExportClassPrimitive) &&
1893      "Variable should be type of primitive here");
1894
1895  const RSExportPrimitiveType *EPT =
1896      static_cast<const RSExportPrimitiveType *>(EV->getType());
1897  std::string TypeName = GetTypeName(EPT);
1898  std::string VarName = EV->getName();
1899
1900  genPrivateExportVariable(TypeName, EV->getName());
1901
1902  if (EV->isConst()) {
1903    mOut.indent() << "public final static " << TypeName
1904                  << " " RS_EXPORT_VAR_CONST_PREFIX << VarName << " = ";
1905    const clang::APValue &Val = EV->getInit();
1906    genInitValue(Val, EPT->getType() == DataTypeBoolean);
1907    mOut << ";\n";
1908  } else {
1909    // set_*()
1910    // This must remain synchronized, since multiple Dalvik threads may
1911    // be calling setters.
1912    startFunction(AM_PublicSynchronized, false, "void", "set_" + VarName, 1,
1913                  TypeName.c_str(), "v");
1914    if ((EPT->getElementSizeInBytes() < 4) || EV->isUnsigned()) {
1915      // We create/cache a per-type FieldPacker. This allows us to reuse the
1916      // validation logic (for catching negative inputs from Dalvik, as well
1917      // as inputs that are too large to be represented in the unsigned type).
1918      // Sub-integer types are also handled specially here, so that we don't
1919      // overwrite bytes accidentally.
1920      std::string ElemName = EPT->getElementName();
1921      std::string FPName;
1922      FPName = RS_FP_PREFIX + ElemName;
1923      mOut.indent() << "if (" << FPName << "!= null) {\n";
1924      mOut.increaseIndent();
1925      mOut.indent() << FPName << ".reset();\n";
1926      mOut.decreaseIndent();
1927      mOut.indent() << "} else {\n";
1928      mOut.increaseIndent();
1929      mOut.indent() << FPName << " = new FieldPacker(" << EPT->getElementSizeInBytes()
1930                    << ");\n";
1931      mOut.decreaseIndent();
1932      mOut.indent() << "}\n";
1933
1934      genPackVarOfType(EPT, "v", FPName.c_str());
1935      mOut.indent() << "setVar(" << RS_EXPORT_VAR_INDEX_PREFIX << VarName
1936                    << ", " << FPName << ");\n";
1937    } else {
1938      mOut.indent() << "setVar(" << RS_EXPORT_VAR_INDEX_PREFIX << VarName
1939                    << ", v);\n";
1940    }
1941
1942    // Dalvik update comes last, since the input may be invalid (and hence
1943    // throw an exception).
1944    mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;\n";
1945
1946    endFunction();
1947  }
1948
1949  genGetExportVariable(TypeName, VarName);
1950  genGetFieldID(VarName);
1951}
1952
1953void RSReflectionJava::genInitValue(const clang::APValue &Val, bool asBool) {
1954  switch (Val.getKind()) {
1955  case clang::APValue::Int: {
1956    llvm::APInt api = Val.getInt();
1957    if (asBool) {
1958      mOut << ((api.getSExtValue() == 0) ? "false" : "true");
1959    } else {
1960      // TODO: Handle unsigned correctly
1961      mOut << api.getSExtValue();
1962      if (api.getBitWidth() > 32) {
1963        mOut << "L";
1964      }
1965    }
1966    break;
1967  }
1968
1969  case clang::APValue::Float: {
1970    llvm::APFloat apf = Val.getFloat();
1971    llvm::SmallString<30> s;
1972    apf.toString(s);
1973    mOut << s.c_str();
1974    if (&apf.getSemantics() == &llvm::APFloat::IEEEsingle) {
1975      if (s.count('.') == 0) {
1976        mOut << ".f";
1977      } else {
1978        mOut << "f";
1979      }
1980    }
1981    break;
1982  }
1983
1984  case clang::APValue::ComplexInt:
1985  case clang::APValue::ComplexFloat:
1986  case clang::APValue::LValue:
1987  case clang::APValue::Vector: {
1988    slangAssert(false && "Primitive type cannot have such kind of initializer");
1989    break;
1990  }
1991
1992  default: { slangAssert(false && "Unknown kind of initializer"); }
1993  }
1994}
1995
1996void RSReflectionJava::genPointerTypeExportVariable(const RSExportVar *EV) {
1997  const RSExportType *ET = EV->getType();
1998  const RSExportType *PointeeType;
1999
2000  slangAssert((ET->getClass() == RSExportType::ExportClassPointer) &&
2001              "Variable should be type of pointer here");
2002
2003  PointeeType = static_cast<const RSExportPointerType *>(ET)->getPointeeType();
2004  std::string TypeName = GetTypeName(ET);
2005  std::string VarName = EV->getName();
2006
2007  genPrivateExportVariable(TypeName, VarName);
2008
2009  // bind_*()
2010  startFunction(AM_Public, false, "void", "bind_" + VarName, 1,
2011                TypeName.c_str(), "v");
2012
2013  mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;\n";
2014  mOut.indent() << "if (v == null) bindAllocation(null, "
2015                << RS_EXPORT_VAR_INDEX_PREFIX << VarName << ");\n";
2016
2017  if (PointeeType->getClass() == RSExportType::ExportClassRecord) {
2018    mOut.indent() << "else bindAllocation(v.getAllocation(), "
2019                  << RS_EXPORT_VAR_INDEX_PREFIX << VarName << ");\n";
2020  } else {
2021    mOut.indent() << "else bindAllocation(v, " << RS_EXPORT_VAR_INDEX_PREFIX
2022                  << VarName << ");\n";
2023  }
2024
2025  endFunction();
2026
2027  genGetExportVariable(TypeName, VarName);
2028}
2029
2030void RSReflectionJava::genVectorTypeExportVariable(const RSExportVar *EV) {
2031  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassVector) &&
2032              "Variable should be type of vector here");
2033
2034  std::string TypeName = GetTypeName(EV->getType());
2035  std::string VarName = EV->getName();
2036
2037  genPrivateExportVariable(TypeName, VarName);
2038  genSetExportVariable(TypeName, EV, 1);
2039  genGetExportVariable(TypeName, VarName);
2040  genGetFieldID(VarName);
2041}
2042
2043void RSReflectionJava::genMatrixTypeExportVariable(const RSExportVar *EV) {
2044  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassMatrix) &&
2045              "Variable should be type of matrix here");
2046
2047  const RSExportType *ET = EV->getType();
2048  std::string TypeName = GetTypeName(ET);
2049  std::string VarName = EV->getName();
2050
2051  genPrivateExportVariable(TypeName, VarName);
2052
2053  // set_*()
2054  if (!EV->isConst()) {
2055    const char *FieldPackerName = "fp";
2056    startFunction(AM_PublicSynchronized, false, "void", "set_" + VarName, 1,
2057                  TypeName.c_str(), "v");
2058    mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;\n";
2059
2060    if (genCreateFieldPacker(ET, FieldPackerName))
2061      genPackVarOfType(ET, "v", FieldPackerName);
2062    mOut.indent() << "setVar(" RS_EXPORT_VAR_INDEX_PREFIX << VarName << ", "
2063                  << FieldPackerName << ");\n";
2064
2065    endFunction();
2066  }
2067
2068  genGetExportVariable(TypeName, VarName);
2069  genGetFieldID(VarName);
2070}
2071
2072void
2073RSReflectionJava::genConstantArrayTypeExportVariable(const RSExportVar *EV) {
2074  const RSExportType *const ET = EV->getType();
2075  slangAssert(
2076      (ET->getClass() == RSExportType::ExportClassConstantArray) &&
2077      "Variable should be type of constant array here");
2078
2079  std::string TypeName = GetTypeName(EV->getType());
2080  std::string VarName = EV->getName();
2081
2082  genPrivateExportVariable(TypeName, VarName);
2083  genSetExportVariable(TypeName, EV, static_cast<const RSExportConstantArrayType *>(ET)->getNumElement());
2084  genGetExportVariable(TypeName, VarName);
2085  genGetFieldID(VarName);
2086}
2087
2088void RSReflectionJava::genRecordTypeExportVariable(const RSExportVar *EV) {
2089  slangAssert((EV->getType()->getClass() == RSExportType::ExportClassRecord) &&
2090              "Variable should be type of struct here");
2091
2092  std::string TypeName = GetTypeName(EV->getType());
2093  std::string VarName = EV->getName();
2094
2095  genPrivateExportVariable(TypeName, VarName);
2096  genSetExportVariable(TypeName, EV, 1);
2097  genGetExportVariable(TypeName, VarName);
2098  genGetFieldID(VarName);
2099}
2100
2101void RSReflectionJava::genPrivateExportVariable(const std::string &TypeName,
2102                                                const std::string &VarName) {
2103  mOut.indent() << "private " << TypeName << " " << RS_EXPORT_VAR_PREFIX
2104                << VarName << ";\n";
2105}
2106
2107// Dimension = array element count; otherwise, 1.
2108void RSReflectionJava::genSetExportVariable(const std::string &TypeName,
2109                                            const RSExportVar *EV,
2110                                            unsigned Dimension) {
2111  if (!EV->isConst()) {
2112    const char *FieldPackerName = "fp";
2113    std::string VarName = EV->getName();
2114    const RSExportType *ET = EV->getType();
2115    startFunction(AM_PublicSynchronized, false, "void", "set_" + VarName, 1,
2116                  TypeName.c_str(), "v");
2117    mOut.indent() << RS_EXPORT_VAR_PREFIX << VarName << " = v;\n";
2118
2119    if (genCreateFieldPacker(ET, FieldPackerName))
2120      genPackVarOfType(ET, "v", FieldPackerName);
2121
2122    if (mRSContext->getTargetAPI() < SLANG_JB_TARGET_API) {
2123      // Legacy apps must use the old setVar() without Element/dim components.
2124      mOut.indent() << "setVar(" << RS_EXPORT_VAR_INDEX_PREFIX << VarName
2125                    << ", " << FieldPackerName << ");\n";
2126    } else {
2127      // We only have support for one-dimensional array reflection today,
2128      // but the entry point (i.e. setVar()) takes an array of dimensions.
2129      mOut.indent() << "int []__dimArr = new int[1];\n";
2130      mOut.indent() << "__dimArr[0] = " << Dimension << ";\n";
2131      mOut.indent() << "setVar(" << RS_EXPORT_VAR_INDEX_PREFIX << VarName
2132                    << ", " << FieldPackerName << ", " << RS_ELEM_PREFIX
2133                    << ET->getElementName() << ", __dimArr);\n";
2134    }
2135
2136    endFunction();
2137  }
2138}
2139
2140void RSReflectionJava::genGetExportVariable(const std::string &TypeName,
2141                                            const std::string &VarName) {
2142  startFunction(AM_Public, false, TypeName.c_str(), "get_" + VarName, 0);
2143
2144  mOut.indent() << "return " << RS_EXPORT_VAR_PREFIX << VarName << ";\n";
2145
2146  endFunction();
2147}
2148
2149void RSReflectionJava::genGetFieldID(const std::string &VarName) {
2150  // We only generate getFieldID_*() for non-Pointer (bind) types.
2151  if (mRSContext->getTargetAPI() >= SLANG_JB_MR1_TARGET_API) {
2152    startFunction(AM_Public, false, "Script.FieldID", "getFieldID_" + VarName,
2153                  0);
2154
2155    mOut.indent() << "return createFieldID(" << RS_EXPORT_VAR_INDEX_PREFIX
2156                  << VarName << ", null);\n";
2157
2158    endFunction();
2159  }
2160}
2161
2162/******************* Methods to generate script class /end *******************/
2163
2164bool RSReflectionJava::genCreateFieldPacker(const RSExportType *ET,
2165                                            const char *FieldPackerName) {
2166  size_t AllocSize = ET->getAllocSize();
2167  if (AllocSize > 0)
2168    mOut.indent() << "FieldPacker " << FieldPackerName << " = new FieldPacker("
2169                  << AllocSize << ");\n";
2170  else
2171    return false;
2172  return true;
2173}
2174
2175void RSReflectionJava::genPackVarOfType(const RSExportType *ET,
2176                                        const char *VarName,
2177                                        const char *FieldPackerName) {
2178  switch (ET->getClass()) {
2179  case RSExportType::ExportClassPrimitive:
2180  case RSExportType::ExportClassVector: {
2181    mOut.indent() << FieldPackerName << "."
2182                  << GetPackerAPIName(
2183                         static_cast<const RSExportPrimitiveType *>(ET)) << "("
2184                  << VarName << ");\n";
2185    break;
2186  }
2187  case RSExportType::ExportClassPointer: {
2188    // Must reflect as type Allocation in Java
2189    const RSExportType *PointeeType =
2190        static_cast<const RSExportPointerType *>(ET)->getPointeeType();
2191
2192    if (PointeeType->getClass() != RSExportType::ExportClassRecord) {
2193      mOut.indent() << FieldPackerName << ".addI32(" << VarName
2194                    << ".getPtr());\n";
2195    } else {
2196      mOut.indent() << FieldPackerName << ".addI32(" << VarName
2197                    << ".getAllocation().getPtr());\n";
2198    }
2199    break;
2200  }
2201  case RSExportType::ExportClassMatrix: {
2202    mOut.indent() << FieldPackerName << ".addMatrix(" << VarName << ");\n";
2203    break;
2204  }
2205  case RSExportType::ExportClassConstantArray: {
2206    const RSExportConstantArrayType *ECAT =
2207        static_cast<const RSExportConstantArrayType *>(ET);
2208
2209    // TODO(zonr): more elegant way. Currently, we obtain the unique index
2210    //             variable (this method involves recursive call which means
2211    //             we may have more than one level loop, therefore we can't
2212    //             always use the same index variable name here) name given
2213    //             in the for-loop from counting the '.' in @VarName.
2214    unsigned Level = 0;
2215    size_t LastDotPos = 0;
2216    std::string ElementVarName(VarName);
2217
2218    while (LastDotPos != std::string::npos) {
2219      LastDotPos = ElementVarName.find_first_of('.', LastDotPos + 1);
2220      Level++;
2221    }
2222    std::string IndexVarName("ct");
2223    IndexVarName.append(llvm::utostr_32(Level));
2224
2225    mOut.indent() << "for (int " << IndexVarName << " = 0; " << IndexVarName
2226                  << " < " << ECAT->getNumElement() << "; " << IndexVarName << "++)";
2227    mOut.startBlock();
2228
2229    ElementVarName.append("[" + IndexVarName + "]");
2230    genPackVarOfType(ECAT->getElementType(), ElementVarName.c_str(),
2231                     FieldPackerName);
2232
2233    mOut.endBlock();
2234    break;
2235  }
2236  case RSExportType::ExportClassRecord: {
2237    const RSExportRecordType *ERT = static_cast<const RSExportRecordType *>(ET);
2238    // Relative pos from now on in field packer
2239    unsigned Pos = 0;
2240
2241    for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
2242                                                  E = ERT->fields_end();
2243         I != E; I++) {
2244      const RSExportRecordType::Field *F = *I;
2245      std::string FieldName;
2246      size_t FieldOffset = F->getOffsetInParent();
2247      const RSExportType *T = F->getType();
2248      size_t FieldStoreSize = T->getStoreSize();
2249      size_t FieldAllocSize = T->getAllocSize();
2250
2251      if (VarName != nullptr)
2252        FieldName = VarName + ("." + F->getName());
2253      else
2254        FieldName = F->getName();
2255
2256      if (FieldOffset > Pos) {
2257        mOut.indent() << FieldPackerName << ".skip(" << (FieldOffset - Pos)
2258                      << ");\n";
2259      }
2260
2261      genPackVarOfType(F->getType(), FieldName.c_str(), FieldPackerName);
2262
2263      // There is padding in the field type
2264      if (FieldAllocSize > FieldStoreSize) {
2265        mOut.indent() << FieldPackerName << ".skip("
2266                      << (FieldAllocSize - FieldStoreSize) << ");\n";
2267      }
2268
2269      Pos = FieldOffset + FieldAllocSize;
2270    }
2271
2272    // There maybe some padding after the struct
2273    if (ERT->getAllocSize() > Pos) {
2274      mOut.indent() << FieldPackerName << ".skip(" << ERT->getAllocSize() - Pos
2275                    << ");\n";
2276    }
2277    break;
2278  }
2279  default: { slangAssert(false && "Unknown class of type"); }
2280  }
2281}
2282
2283void RSReflectionJava::genAllocateVarOfType(const RSExportType *T,
2284                                            const std::string &VarName) {
2285  switch (T->getClass()) {
2286  case RSExportType::ExportClassPrimitive: {
2287    // Primitive type like int in Java has its own storage once it's declared.
2288    //
2289    // FIXME: Should we allocate storage for RS object?
2290    // if (static_cast<const RSExportPrimitiveType *>(T)->isRSObjectType())
2291    //  mOut.indent() << VarName << " = new " << GetTypeName(T) << "();\n";
2292    break;
2293  }
2294  case RSExportType::ExportClassPointer: {
2295    // Pointer type is an instance of Allocation or a TypeClass whose value is
2296    // expected to be assigned by programmer later in Java program. Therefore
2297    // we don't reflect things like [VarName] = new Allocation();
2298    mOut.indent() << VarName << " = null;\n";
2299    break;
2300  }
2301  case RSExportType::ExportClassConstantArray: {
2302    const RSExportConstantArrayType *ECAT =
2303        static_cast<const RSExportConstantArrayType *>(T);
2304    const RSExportType *ElementType = ECAT->getElementType();
2305
2306    mOut.indent() << VarName << " = new " << GetTypeName(ElementType) << "["
2307                  << ECAT->getNumElement() << "];\n";
2308
2309    // Primitive type element doesn't need allocation code.
2310    if (ElementType->getClass() != RSExportType::ExportClassPrimitive) {
2311      mOut.indent() << "for (int $ct = 0; $ct < " << ECAT->getNumElement()
2312                    << "; $ct++)";
2313      mOut.startBlock();
2314
2315      std::string ElementVarName(VarName);
2316      ElementVarName.append("[$ct]");
2317      genAllocateVarOfType(ElementType, ElementVarName);
2318
2319      mOut.endBlock();
2320    }
2321    break;
2322  }
2323  case RSExportType::ExportClassVector:
2324  case RSExportType::ExportClassMatrix:
2325  case RSExportType::ExportClassRecord: {
2326    mOut.indent() << VarName << " = new " << GetTypeName(T) << "();\n";
2327    break;
2328  }
2329  }
2330}
2331
2332void RSReflectionJava::genNewItemBufferIfNull(const char *Index) {
2333  mOut.indent() << "if (" << RS_TYPE_ITEM_BUFFER_NAME " == null) ";
2334  mOut << RS_TYPE_ITEM_BUFFER_NAME << " = new " << RS_TYPE_ITEM_CLASS_NAME
2335       << "[getType().getX() /* count */];\n";
2336  if (Index != nullptr) {
2337    mOut.indent() << "if (" << RS_TYPE_ITEM_BUFFER_NAME << "[" << Index
2338                  << "] == null) ";
2339    mOut << RS_TYPE_ITEM_BUFFER_NAME << "[" << Index << "] = new "
2340         << RS_TYPE_ITEM_CLASS_NAME << "();\n";
2341  }
2342}
2343
2344void RSReflectionJava::genNewItemBufferPackerIfNull() {
2345  mOut.indent() << "if (" << RS_TYPE_ITEM_BUFFER_PACKER_NAME << " == null) ";
2346  mOut << RS_TYPE_ITEM_BUFFER_PACKER_NAME " = new FieldPacker("
2347       <<  mItemSizeof << " * getType().getX()/* count */);\n";
2348}
2349
2350/********************** Methods to generate type class  **********************/
2351bool RSReflectionJava::genTypeClass(const RSExportRecordType *ERT,
2352                                    std::string &ErrorMsg) {
2353  std::string ClassName = ERT->getElementName();
2354  std::string superClassName = getRSPackageName();
2355  superClassName += RS_TYPE_CLASS_SUPER_CLASS_NAME;
2356
2357  if (!startClass(AM_Public, false, ClassName, superClassName.c_str(),
2358                  ErrorMsg))
2359    return false;
2360
2361  mGeneratedFileNames->push_back(ClassName);
2362
2363  genTypeItemClass(ERT);
2364
2365  // Declare item buffer and item buffer packer
2366  mOut.indent() << "private " << RS_TYPE_ITEM_CLASS_NAME << " "
2367                << RS_TYPE_ITEM_BUFFER_NAME << "[];\n";
2368  mOut.indent() << "private FieldPacker " << RS_TYPE_ITEM_BUFFER_PACKER_NAME
2369                << ";\n";
2370  mOut.indent() << "private static java.lang.ref.WeakReference<Element> "
2371                << RS_TYPE_ELEMENT_REF_NAME
2372                << " = new java.lang.ref.WeakReference<Element>(null);\n";
2373
2374  genTypeClassConstructor(ERT);
2375  genTypeClassCopyToArrayLocal(ERT);
2376  genTypeClassCopyToArray(ERT);
2377  genTypeClassItemSetter(ERT);
2378  genTypeClassItemGetter(ERT);
2379  genTypeClassComponentSetter(ERT);
2380  genTypeClassComponentGetter(ERT);
2381  genTypeClassCopyAll(ERT);
2382  if (!mRSContext->isCompatLib()) {
2383    // Skip the resize method if we are targeting a compatibility library.
2384    genTypeClassResize();
2385  }
2386
2387  endClass();
2388
2389  resetFieldIndex();
2390  clearFieldIndexMap();
2391
2392  return true;
2393}
2394
2395void RSReflectionJava::genTypeItemClass(const RSExportRecordType *ERT) {
2396  mOut.indent() << "static public class " RS_TYPE_ITEM_CLASS_NAME;
2397  mOut.startBlock();
2398
2399  // Sizeof should not be exposed for 64-bit; it is not accurate
2400  if (mRSContext->getTargetAPI() < 21) {
2401      mOut.indent() << "public static final int sizeof = " << ERT->getAllocSize()
2402                    << ";\n";
2403  }
2404
2405  // Member elements
2406  mOut << "\n";
2407  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
2408                                                FE = ERT->fields_end();
2409       FI != FE; FI++) {
2410    mOut.indent() << GetTypeName((*FI)->getType()) << " " << (*FI)->getName()
2411                  << ";\n";
2412  }
2413
2414  // Constructor
2415  mOut << "\n";
2416  mOut.indent() << RS_TYPE_ITEM_CLASS_NAME << "()";
2417  mOut.startBlock();
2418
2419  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
2420                                                FE = ERT->fields_end();
2421       FI != FE; FI++) {
2422    const RSExportRecordType::Field *F = *FI;
2423    genAllocateVarOfType(F->getType(), F->getName());
2424  }
2425
2426  // end Constructor
2427  mOut.endBlock();
2428
2429  // end Item class
2430  mOut.endBlock();
2431}
2432
2433void RSReflectionJava::genTypeClassConstructor(const RSExportRecordType *ERT) {
2434  const char *RenderScriptVar = "rs";
2435
2436  startFunction(AM_Public, true, "Element", "createElement", 1, "RenderScript",
2437                RenderScriptVar);
2438
2439  // TODO(all): Fix weak-refs + multi-context issue.
2440  // mOut.indent() << "Element e = " << RS_TYPE_ELEMENT_REF_NAME
2441  //            << ".get();\n";
2442  // mOut.indent() << "if (e != null) return e;\n";
2443  RSReflectionJavaElementBuilder builder("eb", ERT, RenderScriptVar, &mOut,
2444                                         mRSContext, this);
2445  builder.generate();
2446
2447  mOut.indent() << "return eb.create();\n";
2448  // mOut.indent() << "e = eb.create();\n";
2449  // mOut.indent() << RS_TYPE_ELEMENT_REF_NAME
2450  //            << " = new java.lang.ref.WeakReference<Element>(e);\n";
2451  // mOut.indent() << "return e;\n";
2452  endFunction();
2453
2454  // private with element
2455  startFunction(AM_Private, false, nullptr, getClassName(), 1, "RenderScript",
2456                RenderScriptVar);
2457  mOut.indent() << RS_TYPE_ITEM_BUFFER_NAME << " = null;\n";
2458  mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << " = null;\n";
2459  mOut.indent() << "mElement = createElement(" << RenderScriptVar << ");\n";
2460  endFunction();
2461
2462  // 1D without usage
2463  startFunction(AM_Public, false, nullptr, getClassName(), 2, "RenderScript",
2464                RenderScriptVar, "int", "count");
2465
2466  mOut.indent() << RS_TYPE_ITEM_BUFFER_NAME << " = null;\n";
2467  mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << " = null;\n";
2468  mOut.indent() << "mElement = createElement(" << RenderScriptVar << ");\n";
2469  // Call init() in super class
2470  mOut.indent() << "init(" << RenderScriptVar << ", count);\n";
2471  endFunction();
2472
2473  // 1D with usage
2474  startFunction(AM_Public, false, nullptr, getClassName(), 3, "RenderScript",
2475                RenderScriptVar, "int", "count", "int", "usages");
2476
2477  mOut.indent() << RS_TYPE_ITEM_BUFFER_NAME << " = null;\n";
2478  mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << " = null;\n";
2479  mOut.indent() << "mElement = createElement(" << RenderScriptVar << ");\n";
2480  // Call init() in super class
2481  mOut.indent() << "init(" << RenderScriptVar << ", count, usages);\n";
2482  endFunction();
2483
2484  // create1D with usage
2485  startFunction(AM_Public, true, getClassName().c_str(), "create1D", 3,
2486                "RenderScript", RenderScriptVar, "int", "dimX", "int",
2487                "usages");
2488  mOut.indent() << getClassName() << " obj = new " << getClassName() << "("
2489                << RenderScriptVar << ");\n";
2490  mOut.indent() << "obj.mAllocation = Allocation.createSized("
2491                   "rs, obj.mElement, dimX, usages);\n";
2492  mOut.indent() << "return obj;\n";
2493  endFunction();
2494
2495  // create1D without usage
2496  startFunction(AM_Public, true, getClassName().c_str(), "create1D", 2,
2497                "RenderScript", RenderScriptVar, "int", "dimX");
2498  mOut.indent() << "return create1D(" << RenderScriptVar
2499                << ", dimX, Allocation.USAGE_SCRIPT);\n";
2500  endFunction();
2501
2502  // create2D without usage
2503  startFunction(AM_Public, true, getClassName().c_str(), "create2D", 3,
2504                "RenderScript", RenderScriptVar, "int", "dimX", "int", "dimY");
2505  mOut.indent() << "return create2D(" << RenderScriptVar
2506                << ", dimX, dimY, Allocation.USAGE_SCRIPT);\n";
2507  endFunction();
2508
2509  // create2D with usage
2510  startFunction(AM_Public, true, getClassName().c_str(), "create2D", 4,
2511                "RenderScript", RenderScriptVar, "int", "dimX", "int", "dimY",
2512                "int", "usages");
2513
2514  mOut.indent() << getClassName() << " obj = new " << getClassName() << "("
2515                << RenderScriptVar << ");\n";
2516  mOut.indent() << "Type.Builder b = new Type.Builder(rs, obj.mElement);\n";
2517  mOut.indent() << "b.setX(dimX);\n";
2518  mOut.indent() << "b.setY(dimY);\n";
2519  mOut.indent() << "Type t = b.create();\n";
2520  mOut.indent() << "obj.mAllocation = Allocation.createTyped(rs, t, usages);\n";
2521  mOut.indent() << "return obj;\n";
2522  endFunction();
2523
2524  // createTypeBuilder
2525  startFunction(AM_Public, true, "Type.Builder", "createTypeBuilder", 1,
2526                "RenderScript", RenderScriptVar);
2527  mOut.indent() << "Element e = createElement(" << RenderScriptVar << ");\n";
2528  mOut.indent() << "return new Type.Builder(rs, e);\n";
2529  endFunction();
2530
2531  // createCustom with usage
2532  startFunction(AM_Public, true, getClassName().c_str(), "createCustom", 3,
2533                "RenderScript", RenderScriptVar, "Type.Builder", "tb", "int",
2534                "usages");
2535  mOut.indent() << getClassName() << " obj = new " << getClassName() << "("
2536                << RenderScriptVar << ");\n";
2537  mOut.indent() << "Type t = tb.create();\n";
2538  mOut.indent() << "if (t.getElement() != obj.mElement) {\n";
2539  mOut.indent() << "    throw new RSIllegalArgumentException("
2540                   "\"Type.Builder did not match expected element type.\");\n";
2541  mOut.indent() << "}\n";
2542  mOut.indent() << "obj.mAllocation = Allocation.createTyped(rs, t, usages);\n";
2543  mOut.indent() << "return obj;\n";
2544  endFunction();
2545}
2546
2547void RSReflectionJava::genTypeClassCopyToArray(const RSExportRecordType *ERT) {
2548  startFunction(AM_Private, false, "void", "copyToArray", 2,
2549                RS_TYPE_ITEM_CLASS_NAME, "i", "int", "index");
2550
2551  genNewItemBufferPackerIfNull();
2552  mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << ".reset(index * "
2553                << mItemSizeof << ");\n";
2554
2555  mOut.indent() << "copyToArrayLocal(i, " RS_TYPE_ITEM_BUFFER_PACKER_NAME
2556                   ");\n";
2557
2558  endFunction();
2559}
2560
2561void
2562RSReflectionJava::genTypeClassCopyToArrayLocal(const RSExportRecordType *ERT) {
2563  startFunction(AM_Private, false, "void", "copyToArrayLocal", 2,
2564                RS_TYPE_ITEM_CLASS_NAME, "i", "FieldPacker", "fp");
2565
2566  genPackVarOfType(ERT, "i", "fp");
2567
2568  endFunction();
2569}
2570
2571void RSReflectionJava::genTypeClassItemSetter(const RSExportRecordType *ERT) {
2572  startFunction(AM_PublicSynchronized, false, "void", "set", 3,
2573                RS_TYPE_ITEM_CLASS_NAME, "i", "int", "index", "boolean",
2574                "copyNow");
2575  genNewItemBufferIfNull(nullptr);
2576  mOut.indent() << RS_TYPE_ITEM_BUFFER_NAME << "[index] = i;\n";
2577
2578  mOut.indent() << "if (copyNow) ";
2579  mOut.startBlock();
2580
2581  mOut.indent() << "copyToArray(i, index);\n";
2582  mOut.indent() << "FieldPacker fp = new FieldPacker(" << mItemSizeof << ");\n";
2583  mOut.indent() << "copyToArrayLocal(i, fp);\n";
2584  mOut.indent() << "mAllocation.setFromFieldPacker(index, fp);\n";
2585
2586  // End of if (copyNow)
2587  mOut.endBlock();
2588
2589  endFunction();
2590}
2591
2592void RSReflectionJava::genTypeClassItemGetter(const RSExportRecordType *ERT) {
2593  startFunction(AM_PublicSynchronized, false, RS_TYPE_ITEM_CLASS_NAME, "get", 1,
2594                "int", "index");
2595  mOut.indent() << "if (" << RS_TYPE_ITEM_BUFFER_NAME
2596                << " == null) return null;\n";
2597  mOut.indent() << "return " << RS_TYPE_ITEM_BUFFER_NAME << "[index];\n";
2598  endFunction();
2599}
2600
2601void
2602RSReflectionJava::genTypeClassComponentSetter(const RSExportRecordType *ERT) {
2603  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
2604                                                FE = ERT->fields_end();
2605       FI != FE; FI++) {
2606    const RSExportRecordType::Field *F = *FI;
2607    size_t FieldOffset = F->getOffsetInParent();
2608    size_t FieldStoreSize = F->getType()->getStoreSize();
2609    unsigned FieldIndex = getFieldIndex(F);
2610
2611    startFunction(AM_PublicSynchronized, false, "void", "set_" + F->getName(),
2612                  3, "int", "index", GetTypeName(F->getType()).c_str(), "v",
2613                  "boolean", "copyNow");
2614    genNewItemBufferPackerIfNull();
2615    genNewItemBufferIfNull("index");
2616    mOut.indent() << RS_TYPE_ITEM_BUFFER_NAME << "[index]." << F->getName()
2617                  << " = v;\n";
2618
2619    mOut.indent() << "if (copyNow) ";
2620    mOut.startBlock();
2621
2622    if (FieldOffset > 0) {
2623      mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << ".reset(index * "
2624                    << mItemSizeof << " + " << FieldOffset
2625                    << ");\n";
2626    } else {
2627      mOut.indent() << RS_TYPE_ITEM_BUFFER_PACKER_NAME << ".reset(index * "
2628                    << mItemSizeof << ");\n";
2629    }
2630    genPackVarOfType(F->getType(), "v", RS_TYPE_ITEM_BUFFER_PACKER_NAME);
2631
2632    mOut.indent() << "FieldPacker fp = new FieldPacker(" << FieldStoreSize
2633                  << ");\n";
2634    genPackVarOfType(F->getType(), "v", "fp");
2635    mOut.indent() << "mAllocation.setFromFieldPacker(index, " << FieldIndex
2636                  << ", fp);\n";
2637
2638    // End of if (copyNow)
2639    mOut.endBlock();
2640
2641    endFunction();
2642  }
2643}
2644
2645void
2646RSReflectionJava::genTypeClassComponentGetter(const RSExportRecordType *ERT) {
2647  for (RSExportRecordType::const_field_iterator FI = ERT->fields_begin(),
2648                                                FE = ERT->fields_end();
2649       FI != FE; FI++) {
2650    const RSExportRecordType::Field *F = *FI;
2651    startFunction(AM_PublicSynchronized, false,
2652                  GetTypeName(F->getType()).c_str(), "get_" + F->getName(), 1,
2653                  "int", "index");
2654    mOut.indent() << "if (" RS_TYPE_ITEM_BUFFER_NAME << " == null) return "
2655                  << GetTypeNullValue(F->getType()) << ";\n";
2656    mOut.indent() << "return " RS_TYPE_ITEM_BUFFER_NAME << "[index]."
2657                  << F->getName() << ";\n";
2658    endFunction();
2659  }
2660}
2661
2662void RSReflectionJava::genTypeClassCopyAll(const RSExportRecordType *ERT) {
2663  startFunction(AM_PublicSynchronized, false, "void", "copyAll", 0);
2664
2665  mOut.indent() << "for (int ct = 0; ct < " << RS_TYPE_ITEM_BUFFER_NAME
2666                << ".length; ct++)"
2667                << " copyToArray(" << RS_TYPE_ITEM_BUFFER_NAME
2668                << "[ct], ct);\n";
2669  mOut.indent() << "mAllocation.setFromFieldPacker(0, "
2670                << RS_TYPE_ITEM_BUFFER_PACKER_NAME ");\n";
2671
2672  endFunction();
2673}
2674
2675void RSReflectionJava::genTypeClassResize() {
2676  startFunction(AM_PublicSynchronized, false, "void", "resize", 1, "int",
2677                "newSize");
2678
2679  mOut.indent() << "if (mItemArray != null) ";
2680  mOut.startBlock();
2681  mOut.indent() << "int oldSize = mItemArray.length;\n";
2682  mOut.indent() << "int copySize = Math.min(oldSize, newSize);\n";
2683  mOut.indent() << "if (newSize == oldSize) return;\n";
2684  mOut.indent() << "Item ni[] = new Item[newSize];\n";
2685  mOut.indent() << "System.arraycopy(mItemArray, 0, ni, 0, copySize);\n";
2686  mOut.indent() << "mItemArray = ni;\n";
2687  mOut.endBlock();
2688  mOut.indent() << "mAllocation.resize(newSize);\n";
2689
2690  mOut.indent() << "if (" RS_TYPE_ITEM_BUFFER_PACKER_NAME
2691                   " != null) " RS_TYPE_ITEM_BUFFER_PACKER_NAME " = "
2692                   "new FieldPacker(" << mItemSizeof << " * getType().getX()/* count */);\n";
2693
2694  endFunction();
2695}
2696
2697/******************** Methods to generate type class /end ********************/
2698
2699/********** Methods to create Element in Java of given record type ***********/
2700
2701RSReflectionJavaElementBuilder::RSReflectionJavaElementBuilder(
2702    const char *ElementBuilderName, const RSExportRecordType *ERT,
2703    const char *RenderScriptVar, GeneratedFile *Out, const RSContext *RSContext,
2704    RSReflectionJava *Reflection)
2705    : mElementBuilderName(ElementBuilderName), mERT(ERT),
2706      mRenderScriptVar(RenderScriptVar), mOut(Out), mPaddingFieldIndex(1),
2707      mRSContext(RSContext), mReflection(Reflection) {
2708  if (mRSContext->getTargetAPI() < SLANG_ICS_TARGET_API) {
2709    mPaddingPrefix = "#padding_";
2710  } else {
2711    mPaddingPrefix = "#rs_padding_";
2712  }
2713}
2714
2715void RSReflectionJavaElementBuilder::generate() {
2716  mOut->indent() << "Element.Builder " << mElementBuilderName
2717                 << " = new Element.Builder(" << mRenderScriptVar << ");\n";
2718  genAddElement(mERT, "", /* ArraySize = */ 0);
2719}
2720
2721void RSReflectionJavaElementBuilder::genAddElement(const RSExportType *ET,
2722                                                   const std::string &VarName,
2723                                                   unsigned ArraySize) {
2724  std::string ElementConstruct = GetBuiltinElementConstruct(ET);
2725
2726  if (ElementConstruct != "") {
2727    genAddStatementStart();
2728    *mOut << ElementConstruct << "(" << mRenderScriptVar << ")";
2729    genAddStatementEnd(VarName, ArraySize);
2730  } else {
2731
2732    switch (ET->getClass()) {
2733    case RSExportType::ExportClassPrimitive: {
2734      const RSExportPrimitiveType *EPT =
2735          static_cast<const RSExportPrimitiveType *>(ET);
2736      const char *DataTypeName =
2737          RSExportPrimitiveType::getRSReflectionType(EPT)->rs_type;
2738      genAddStatementStart();
2739      *mOut << "Element.createUser(" << mRenderScriptVar
2740            << ", Element.DataType." << DataTypeName << ")";
2741      genAddStatementEnd(VarName, ArraySize);
2742      break;
2743    }
2744    case RSExportType::ExportClassVector: {
2745      const RSExportVectorType *EVT =
2746          static_cast<const RSExportVectorType *>(ET);
2747      const char *DataTypeName =
2748          RSExportPrimitiveType::getRSReflectionType(EVT)->rs_type;
2749      genAddStatementStart();
2750      *mOut << "Element.createVector(" << mRenderScriptVar
2751            << ", Element.DataType." << DataTypeName << ", "
2752            << EVT->getNumElement() << ")";
2753      genAddStatementEnd(VarName, ArraySize);
2754      break;
2755    }
2756    case RSExportType::ExportClassPointer:
2757      // Pointer type variable should be resolved in
2758      // GetBuiltinElementConstruct()
2759      slangAssert(false && "??");
2760      break;
2761    case RSExportType::ExportClassMatrix:
2762      // Matrix type variable should be resolved
2763      // in GetBuiltinElementConstruct()
2764      slangAssert(false && "??");
2765      break;
2766    case RSExportType::ExportClassConstantArray: {
2767      const RSExportConstantArrayType *ECAT =
2768          static_cast<const RSExportConstantArrayType *>(ET);
2769
2770      const RSExportType *ElementType = ECAT->getElementType();
2771      if (ElementType->getClass() != RSExportType::ExportClassRecord) {
2772        genAddElement(ECAT->getElementType(), VarName, ECAT->getNumElement());
2773      } else {
2774        std::string NewElementBuilderName(mElementBuilderName);
2775        NewElementBuilderName.append(1, '_');
2776
2777        RSReflectionJavaElementBuilder builder(
2778            NewElementBuilderName.c_str(),
2779            static_cast<const RSExportRecordType *>(ElementType),
2780            mRenderScriptVar, mOut, mRSContext, mReflection);
2781        builder.generate();
2782
2783        ArraySize = ECAT->getNumElement();
2784        genAddStatementStart();
2785        *mOut << NewElementBuilderName << ".create()";
2786        genAddStatementEnd(VarName, ArraySize);
2787      }
2788      break;
2789    }
2790    case RSExportType::ExportClassRecord: {
2791      // Simalar to case of RSExportType::ExportClassRecord in genPackVarOfType.
2792      //
2793      // TODO(zonr): Generalize these two function such that there's no
2794      //             duplicated codes.
2795      const RSExportRecordType *ERT =
2796          static_cast<const RSExportRecordType *>(ET);
2797      int Pos = 0; // relative pos from now on
2798
2799      for (RSExportRecordType::const_field_iterator I = ERT->fields_begin(),
2800                                                    E = ERT->fields_end();
2801           I != E; I++) {
2802        const RSExportRecordType::Field *F = *I;
2803        int FieldOffset = F->getOffsetInParent();
2804        const RSExportType *T = F->getType();
2805        int FieldStoreSize = T->getStoreSize();
2806        int FieldAllocSize = T->getAllocSize();
2807
2808        std::string FieldName;
2809        if (!VarName.empty())
2810          FieldName = VarName + "." + F->getName();
2811        else
2812          FieldName = F->getName();
2813
2814        // Alignment
2815        genAddPadding(FieldOffset - Pos);
2816
2817        // eb.add(...)
2818        mReflection->addFieldIndexMapping(F);
2819        if (F->getType()->getClass() != RSExportType::ExportClassRecord) {
2820          genAddElement(F->getType(), FieldName, 0);
2821        } else {
2822          std::string NewElementBuilderName(mElementBuilderName);
2823          NewElementBuilderName.append(1, '_');
2824
2825          RSReflectionJavaElementBuilder builder(
2826              NewElementBuilderName.c_str(),
2827              static_cast<const RSExportRecordType *>(F->getType()),
2828              mRenderScriptVar, mOut, mRSContext, mReflection);
2829          builder.generate();
2830
2831          genAddStatementStart();
2832          *mOut << NewElementBuilderName << ".create()";
2833          genAddStatementEnd(FieldName, ArraySize);
2834        }
2835
2836        if (mRSContext->getTargetAPI() < SLANG_ICS_TARGET_API) {
2837          // There is padding within the field type. This is only necessary
2838          // for HC-targeted APIs.
2839          genAddPadding(FieldAllocSize - FieldStoreSize);
2840        }
2841
2842        Pos = FieldOffset + FieldAllocSize;
2843      }
2844
2845      // There maybe some padding after the struct
2846      size_t RecordAllocSize = ERT->getAllocSize();
2847
2848      genAddPadding(RecordAllocSize - Pos);
2849      break;
2850    }
2851    default:
2852      slangAssert(false && "Unknown class of type");
2853      break;
2854    }
2855  }
2856}
2857
2858void RSReflectionJavaElementBuilder::genAddPadding(int PaddingSize) {
2859  while (PaddingSize > 0) {
2860    const std::string &VarName = createPaddingField();
2861    genAddStatementStart();
2862    if (PaddingSize >= 4) {
2863      *mOut << "Element.U32(" << mRenderScriptVar << ")";
2864      PaddingSize -= 4;
2865    } else if (PaddingSize >= 2) {
2866      *mOut << "Element.U16(" << mRenderScriptVar << ")";
2867      PaddingSize -= 2;
2868    } else if (PaddingSize >= 1) {
2869      *mOut << "Element.U8(" << mRenderScriptVar << ")";
2870      PaddingSize -= 1;
2871    }
2872    genAddStatementEnd(VarName, 0);
2873  }
2874}
2875
2876void RSReflectionJavaElementBuilder::genAddStatementStart() {
2877  mOut->indent() << mElementBuilderName << ".add(";
2878}
2879
2880void
2881RSReflectionJavaElementBuilder::genAddStatementEnd(const std::string &VarName,
2882                                                   unsigned ArraySize) {
2883  *mOut << ", \"" << VarName << "\"";
2884  if (ArraySize > 0) {
2885    *mOut << ", " << ArraySize;
2886  }
2887  *mOut << ");\n";
2888  // TODO Review incFieldIndex.  It's probably better to assign the numbers at
2889  // the start rather
2890  // than as we're generating the code.
2891  mReflection->incFieldIndex();
2892}
2893
2894/******** Methods to create Element in Java of given record type /end ********/
2895
2896bool RSReflectionJava::reflect() {
2897  std::string ErrorMsg;
2898  if (!genScriptClass(mScriptClassName, ErrorMsg)) {
2899    std::cerr << "Failed to generate class " << mScriptClassName << " ("
2900              << ErrorMsg << ")\n";
2901    return false;
2902  }
2903
2904  mGeneratedFileNames->push_back(mScriptClassName);
2905
2906  // class ScriptField_<TypeName>
2907  for (RSContext::const_export_type_iterator
2908           TI = mRSContext->export_types_begin(),
2909           TE = mRSContext->export_types_end();
2910       TI != TE; TI++) {
2911    const RSExportType *ET = TI->getValue();
2912
2913    if (ET->getClass() == RSExportType::ExportClassRecord) {
2914      const RSExportRecordType *ERT =
2915          static_cast<const RSExportRecordType *>(ET);
2916
2917      if (!ERT->isArtificial() && !genTypeClass(ERT, ErrorMsg)) {
2918        std::cerr << "Failed to generate type class for struct '"
2919                  << ERT->getName() << "' (" << ErrorMsg << ")\n";
2920        return false;
2921      }
2922    }
2923  }
2924
2925  return true;
2926}
2927
2928const char *RSReflectionJava::AccessModifierStr(AccessModifier AM) {
2929  switch (AM) {
2930  case AM_Public:
2931    return "public";
2932    break;
2933  case AM_Protected:
2934    return "protected";
2935    break;
2936  case AM_Private:
2937    return "private";
2938    break;
2939  case AM_PublicSynchronized:
2940    return "public synchronized";
2941    break;
2942  default:
2943    return "";
2944    break;
2945  }
2946}
2947
2948bool RSReflectionJava::startClass(AccessModifier AM, bool IsStatic,
2949                                  const std::string &ClassName,
2950                                  const char *SuperClassName,
2951                                  std::string &ErrorMsg) {
2952  // Open file for class
2953  std::string FileName = ClassName + ".java";
2954  if (!mOut.startFile(mOutputDirectory, FileName, mRSSourceFileName,
2955                      mRSContext->getLicenseNote(), true,
2956                      mRSContext->getVerbose())) {
2957    return false;
2958  }
2959
2960  // Package
2961  if (!mPackageName.empty()) {
2962    mOut << "package " << mPackageName << ";\n";
2963  }
2964  mOut << "\n";
2965
2966  // Imports
2967  mOut << "import " << mRSPackageName << ".*;\n";
2968  if (getEmbedBitcodeInJava()) {
2969    mOut << "import " << mPackageName << "."
2970          << RSSlangReflectUtils::JavaBitcodeClassNameFromRSFileName(
2971                 mRSSourceFileName.c_str()) << ";\n";
2972  } else {
2973    mOut << "import android.content.res.Resources;\n";
2974  }
2975  mOut << "\n";
2976
2977  // All reflected classes should be annotated as hidden, so that they won't
2978  // be exposed in SDK.
2979  mOut << "/**\n";
2980  mOut << " * @hide\n";
2981  mOut << " */\n";
2982
2983  mOut << AccessModifierStr(AM) << ((IsStatic) ? " static" : "") << " class "
2984       << ClassName;
2985  if (SuperClassName != nullptr)
2986    mOut << " extends " << SuperClassName;
2987
2988  mOut.startBlock();
2989
2990  mClassName = ClassName;
2991
2992  return true;
2993}
2994
2995void RSReflectionJava::endClass() {
2996  mOut.endBlock();
2997  mOut.closeFile();
2998  clear();
2999}
3000
3001void RSReflectionJava::startTypeClass(const std::string &ClassName) {
3002  mOut.indent() << "public static class " << ClassName;
3003  mOut.startBlock();
3004}
3005
3006void RSReflectionJava::endTypeClass() { mOut.endBlock(); }
3007
3008void RSReflectionJava::startFunction(AccessModifier AM, bool IsStatic,
3009                                     const char *ReturnType,
3010                                     const std::string &FunctionName, int Argc,
3011                                     ...) {
3012  ArgTy Args;
3013  va_list vl;
3014  va_start(vl, Argc);
3015
3016  for (int i = 0; i < Argc; i++) {
3017    const char *ArgType = va_arg(vl, const char *);
3018    const char *ArgName = va_arg(vl, const char *);
3019
3020    Args.push_back(std::make_pair(ArgType, ArgName));
3021  }
3022  va_end(vl);
3023
3024  startFunction(AM, IsStatic, ReturnType, FunctionName, Args);
3025}
3026
3027void RSReflectionJava::startFunction(AccessModifier AM, bool IsStatic,
3028                                     const char *ReturnType,
3029                                     const std::string &FunctionName,
3030                                     const ArgTy &Args) {
3031  mOut.indent() << AccessModifierStr(AM) << ((IsStatic) ? " static " : " ")
3032                << ((ReturnType) ? ReturnType : "") << " " << FunctionName
3033                << "(";
3034
3035  bool FirstArg = true;
3036  for (ArgTy::const_iterator I = Args.begin(), E = Args.end(); I != E; I++) {
3037    if (!FirstArg)
3038      mOut << ", ";
3039    else
3040      FirstArg = false;
3041
3042    mOut << I->first << " " << I->second;
3043  }
3044
3045  mOut << ")";
3046  mOut.startBlock();
3047}
3048
3049void RSReflectionJava::endFunction() { mOut.endBlock(); }
3050
3051bool RSReflectionJava::addTypeNameForElement(const std::string &TypeName) {
3052  if (mTypesToCheck.find(TypeName) == mTypesToCheck.end()) {
3053    mTypesToCheck.insert(TypeName);
3054    return true;
3055  } else {
3056    return false;
3057  }
3058}
3059
3060bool RSReflectionJava::addTypeNameForFieldPacker(const std::string &TypeName) {
3061  if (mFieldPackerTypes.find(TypeName) == mFieldPackerTypes.end()) {
3062    mFieldPackerTypes.insert(TypeName);
3063    return true;
3064  } else {
3065    return false;
3066  }
3067}
3068
3069} // namespace slang
3070