slang_rs_export_type.h revision 01321838204e213b314f7d6fa5bfc1f94dbf347e
1/*
2 * Copyright 2010-2012, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _FRAMEWORKS_COMPILE_SLANG_SLANG_RS_EXPORT_TYPE_H_  // NOLINT
18#define _FRAMEWORKS_COMPILE_SLANG_SLANG_RS_EXPORT_TYPE_H_
19
20#include <list>
21#include <set>
22#include <string>
23#include <sstream>
24
25#include "clang/AST/Decl.h"
26#include "clang/AST/Type.h"
27
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/ADT/StringRef.h"
31
32#include "llvm/Support/ManagedStatic.h"
33
34#include "slang_rs_exportable.h"
35
36#define GET_CANONICAL_TYPE(T) \
37    (((T) == NULL) ? NULL : (T)->getCanonicalTypeInternal().getTypePtr())
38#define UNSAFE_CAST_TYPE(TT, T) \
39    static_cast<TT*>(T->getCanonicalTypeInternal().getTypePtr())
40#define GET_EXT_VECTOR_ELEMENT_TYPE(T) \
41    (((T) == NULL) ? NULL : \
42                     GET_CANONICAL_TYPE((T)->getElementType().getTypePtr()))
43#define GET_POINTEE_TYPE(T) \
44    (((T) == NULL) ? NULL : \
45                     GET_CANONICAL_TYPE((T)->getPointeeType().getTypePtr()))
46#define GET_CONSTANT_ARRAY_ELEMENT_TYPE(T)  \
47    (((T) == NULL) ? NULL : \
48                     GET_CANONICAL_TYPE((T)->getElementType().getTypePtr()))
49
50namespace llvm {
51  class Type;
52}   // namespace llvm
53
54namespace slang {
55
56class RSContext;
57
58// Broad grouping of the data types
59enum DataTypeCategory {
60    PrimitiveDataType,
61    MatrixDataType,
62    ObjectDataType
63};
64
65// From graphics/java/android/renderscript/Element.java: Element.DataType
66/* NOTE: The values of the enums are found compiled in the bit code (i.e. as
67 * values, not symbolic.  When adding new types, you must add them to the end.
68 * If removing types, you can't re-use the integer value.
69 *
70 * TODO: but if you do this, you won't be able to keep using First* & Last*
71 * for validation.
72 *
73 * IMPORTANT: This enum should correspond one-for-one to the entries found in the
74 * gReflectionsTypes table (except for the two negative numbers).  Don't edit one without
75 * the other.
76 */
77enum DataType {
78    DataTypeIsStruct = -2,
79    DataTypeUnknown = -1,
80
81    DataTypeFloat16 = 0,
82    DataTypeFloat32 = 1,
83    DataTypeFloat64 = 2,
84    DataTypeSigned8 = 3,
85    DataTypeSigned16 = 4,
86    DataTypeSigned32 = 5,
87    DataTypeSigned64 = 6,
88    DataTypeUnsigned8 = 7,
89    DataTypeUnsigned16 = 8,
90    DataTypeUnsigned32 = 9,
91    DataTypeUnsigned64 = 10,
92    DataTypeBoolean = 11,
93    DataTypeUnsigned565 = 12,
94    DataTypeUnsigned5551 = 13,
95    DataTypeUnsigned4444 = 14,
96
97    DataTypeRSMatrix2x2 = 15,
98    DataTypeRSMatrix3x3 = 16,
99    DataTypeRSMatrix4x4 = 17,
100
101    DataTypeRSElement = 18,
102    DataTypeRSType = 19,
103    DataTypeRSAllocation = 20,
104    DataTypeRSSampler = 21,
105    DataTypeRSScript = 22,
106    DataTypeRSMesh = 23,
107    DataTypeRSPath = 24,
108    DataTypeRSProgramFragment = 25,
109    DataTypeRSProgramVertex = 26,
110    DataTypeRSProgramRaster = 27,
111    DataTypeRSProgramStore = 28,
112    DataTypeRSFont = 29,
113
114    // This should always be last and correspond to the size of the gReflectionTypes table.
115    DataTypeMax
116};
117
118typedef struct {
119    DataTypeCategory category;
120    const char * rs_type;
121    const char * rs_short_type;
122    uint32_t size_in_bits;
123    const char * c_name;
124    const char * java_name;
125    const char * rs_c_vector_prefix;
126    const char * rs_java_vector_prefix;
127    bool java_promotion;
128} RSReflectionType;
129
130
131typedef struct RSReflectionTypeData_rec {
132    const RSReflectionType *type;
133    uint32_t vecSize;
134    bool isPointer;
135    uint32_t arraySize;
136
137    // Subelements
138    //std::vector<const struct RSReflectionTypeData_rec *> fields;
139    //std::vector< std::string > fieldNames;
140    //std::vector< uint32_t> fieldOffsetBytes;
141} RSReflectionTypeData;
142
143// Make a name for types that are too complicated to create the real names.
144std::string CreateDummyName(const char *type, const std::string &name);
145
146inline bool IsDummyName(const llvm::StringRef &Name) {
147  return Name.startswith("<");
148}
149
150class RSExportType : public RSExportable {
151  friend class RSExportElement;
152 public:
153  typedef enum {
154    ExportClassPrimitive,
155    ExportClassPointer,
156    ExportClassVector,
157    ExportClassMatrix,
158    ExportClassConstantArray,
159    ExportClassRecord
160  } ExportClass;
161
162  void convertToRTD(RSReflectionTypeData *rtd) const;
163
164 private:
165  ExportClass mClass;
166  std::string mName;
167
168  // Cache the result after calling convertToLLVMType() at the first time
169  mutable llvm::Type *mLLVMType;
170
171 protected:
172  RSExportType(RSContext *Context,
173               ExportClass Class,
174               const llvm::StringRef &Name);
175
176  // Let's make it private since there're some prerequisites to call this
177  // function.
178  //
179  // @T was normalized by calling RSExportType::NormalizeType().
180  // @TypeName was retrieve from RSExportType::GetTypeName() before calling
181  //           this.
182  //
183  static RSExportType *Create(RSContext *Context,
184                              const clang::Type *T,
185                              const llvm::StringRef &TypeName);
186
187  static llvm::StringRef GetTypeName(const clang::Type *T);
188
189  // This function convert the RSExportType to LLVM type. Actually, it should be
190  // "convert Clang type to LLVM type." However, clang doesn't make this API
191  // (lib/CodeGen/CodeGenTypes.h) public, we need to do by ourselves.
192  //
193  // Once we can get LLVM type, we can use LLVM to get alignment information,
194  // allocation size of a given type and structure layout that LLVM used
195  // (all of these information are target dependent) without dealing with these
196  // by ourselves.
197  virtual llvm::Type *convertToLLVMType() const = 0;
198  // Record type may recursively reference its type definition. We need a
199  // temporary type setup before the type construction gets done.
200  inline void setAbstractLLVMType(llvm::Type *LLVMType) const {
201    mLLVMType = LLVMType;
202  }
203
204  virtual ~RSExportType();
205
206 public:
207  // This function additionally verifies that the Type T is exportable.
208  // If it is not, this function returns false. Otherwise it returns true.
209  static bool NormalizeType(const clang::Type *&T,
210                            llvm::StringRef &TypeName,
211                            RSContext *Context,
212                            const clang::VarDecl *VD);
213
214  // This function checks whether the specified type can be handled by RS/FS.
215  // If it cannot, this function returns false. Otherwise it returns true.
216  // Filterscript has additional restrictions on supported types.
217  static bool ValidateType(slang::RSContext *Context, clang::ASTContext &C,
218                           clang::QualType QT, clang::NamedDecl *ND,
219                           clang::SourceLocation Loc, unsigned int TargetAPI,
220                           bool IsFilterscript);
221
222  // This function ensures that the VarDecl can be properly handled by RS.
223  // If it cannot, this function returns false. Otherwise it returns true.
224  // Filterscript has additional restrictions on supported types.
225  static bool ValidateVarDecl(slang::RSContext *Context, clang::VarDecl *VD,
226                              unsigned int TargetAPI, bool IsFilterscript);
227
228  // @T may not be normalized
229  static RSExportType *Create(RSContext *Context, const clang::Type *T);
230  static RSExportType *CreateFromDecl(RSContext *Context,
231                                      const clang::VarDecl *VD);
232
233  static const clang::Type *GetTypeOfDecl(const clang::DeclaratorDecl *DD);
234
235  inline ExportClass getClass() const { return mClass; }
236
237  virtual unsigned getSize() const { return 1; }
238
239  inline llvm::Type *getLLVMType() const {
240    if (mLLVMType == NULL)
241      mLLVMType = convertToLLVMType();
242    return mLLVMType;
243  }
244
245  // Return the maximum number of bytes that may be written when this type is stored.
246  virtual size_t getStoreSize() const;
247
248  // Return the distance in bytes between successive elements of this type; it includes padding.
249  virtual size_t getAllocSize() const;
250
251  inline const std::string &getName() const { return mName; }
252
253  virtual std::string getElementName() const {
254    // Base case is actually an invalid C/Java identifier.
255    return "@@INVALID@@";
256  }
257
258  virtual bool keep();
259  virtual bool equals(const RSExportable *E) const;
260};  // RSExportType
261
262// Primitive types
263class RSExportPrimitiveType : public RSExportType {
264  friend class RSExportType;
265  friend class RSExportElement;
266 private:
267  DataType mType;
268  bool mNormalized;
269
270  typedef llvm::StringMap<DataType> RSSpecificTypeMapTy;
271  static llvm::ManagedStatic<RSSpecificTypeMapTy> RSSpecificTypeMap;
272
273  static llvm::Type *RSObjectLLVMType;
274
275  static const size_t SizeOfDataTypeInBits[];
276  // @T was normalized by calling RSExportType::NormalizeType() before calling
277  // this.
278  // @TypeName was retrieved from RSExportType::GetTypeName() before calling
279  // this
280  static RSExportPrimitiveType *Create(RSContext *Context,
281                                       const clang::Type *T,
282                                       const llvm::StringRef &TypeName,
283                                       bool Normalized = false);
284
285 protected:
286  RSExportPrimitiveType(RSContext *Context,
287                        // for derived class to set their type class
288                        ExportClass Class,
289                        const llvm::StringRef &Name,
290                        DataType DT,
291                        bool Normalized)
292      : RSExportType(Context, Class, Name),
293        mType(DT),
294        mNormalized(Normalized) {
295    return;
296  }
297
298  virtual llvm::Type *convertToLLVMType() const;
299
300  static DataType GetDataType(RSContext *Context, const clang::Type *T);
301
302 public:
303  // T is normalized by calling RSExportType::NormalizeType() before
304  // calling this
305  static bool IsPrimitiveType(const clang::Type *T);
306
307  // @T may not be normalized
308  static RSExportPrimitiveType *Create(RSContext *Context,
309                                       const clang::Type *T);
310
311  static DataType GetRSSpecificType(const llvm::StringRef &TypeName);
312  static DataType GetRSSpecificType(const clang::Type *T);
313
314  static bool IsRSMatrixType(DataType DT);
315  static bool IsRSObjectType(DataType DT);
316  static bool IsRSObjectType(const clang::Type *T) {
317    return IsRSObjectType(GetRSSpecificType(T));
318  }
319
320  // Determines whether T is [an array of] struct that contains at least one
321  // RS object type within it.
322  static bool IsStructureTypeWithRSObject(const clang::Type *T);
323
324  static size_t GetSizeInBits(const RSExportPrimitiveType *EPT);
325
326  inline DataType getType() const { return mType; }
327  inline bool isRSObjectType() const {
328      return IsRSObjectType(mType);
329  }
330
331  virtual bool equals(const RSExportable *E) const;
332
333  static RSReflectionType *getRSReflectionType(DataType DT);
334  static RSReflectionType *getRSReflectionType(
335      const RSExportPrimitiveType *EPT) {
336    return getRSReflectionType(EPT->getType());
337  }
338
339  virtual unsigned getSize() const { return (GetSizeInBits(this) >> 3); }
340
341  std::string getElementName() const {
342    return getRSReflectionType(this)->rs_short_type;
343  }
344};  // RSExportPrimitiveType
345
346
347class RSExportPointerType : public RSExportType {
348  friend class RSExportType;
349  friend class RSExportFunc;
350 private:
351  const RSExportType *mPointeeType;
352
353  RSExportPointerType(RSContext *Context,
354                      const llvm::StringRef &Name,
355                      const RSExportType *PointeeType)
356      : RSExportType(Context, ExportClassPointer, Name),
357        mPointeeType(PointeeType) {
358    return;
359  }
360
361  // @PT was normalized by calling RSExportType::NormalizeType() before calling
362  // this.
363  static RSExportPointerType *Create(RSContext *Context,
364                                     const clang::PointerType *PT,
365                                     const llvm::StringRef &TypeName);
366
367  virtual llvm::Type *convertToLLVMType() const;
368
369 public:
370  virtual bool keep();
371
372  inline const RSExportType *getPointeeType() const { return mPointeeType; }
373
374  virtual bool equals(const RSExportable *E) const;
375};  // RSExportPointerType
376
377
378class RSExportVectorType : public RSExportPrimitiveType {
379  friend class RSExportType;
380  friend class RSExportElement;
381 private:
382  unsigned mNumElement;   // number of element
383
384  RSExportVectorType(RSContext *Context,
385                     const llvm::StringRef &Name,
386                     DataType DT,
387                     bool Normalized,
388                     unsigned NumElement)
389      : RSExportPrimitiveType(Context, ExportClassVector, Name,
390                              DT, Normalized),
391        mNumElement(NumElement) {
392    return;
393  }
394
395  // @EVT was normalized by calling RSExportType::NormalizeType() before
396  // calling this.
397  static RSExportVectorType *Create(RSContext *Context,
398                                    const clang::ExtVectorType *EVT,
399                                    const llvm::StringRef &TypeName,
400                                    bool Normalized = false);
401
402  virtual llvm::Type *convertToLLVMType() const;
403
404 public:
405  static llvm::StringRef GetTypeName(const clang::ExtVectorType *EVT);
406
407  inline unsigned getNumElement() const { return mNumElement; }
408
409  std::string getElementName() const {
410    std::stringstream Name;
411    Name << RSExportPrimitiveType::getRSReflectionType(this)->rs_short_type
412         << "_" << getNumElement();
413    return Name.str();
414  }
415
416  virtual bool equals(const RSExportable *E) const;
417};
418
419// Only *square* *float* matrix is supported by now.
420//
421// struct rs_matrix{2x2,3x3,4x4, ..., NxN} should be defined as the following
422// form *exactly*:
423//  typedef struct {
424//    float m[{NxN}];
425//  } rs_matrixNxN;
426//
427//  where mDim will be N.
428class RSExportMatrixType : public RSExportType {
429  friend class RSExportType;
430 private:
431  unsigned mDim;  // dimension
432
433  RSExportMatrixType(RSContext *Context,
434                     const llvm::StringRef &Name,
435                     unsigned Dim)
436    : RSExportType(Context, ExportClassMatrix, Name),
437      mDim(Dim) {
438    return;
439  }
440
441  virtual llvm::Type *convertToLLVMType() const;
442
443 public:
444  // @RT was normalized by calling RSExportType::NormalizeType() before
445  // calling this.
446  static RSExportMatrixType *Create(RSContext *Context,
447                                    const clang::RecordType *RT,
448                                    const llvm::StringRef &TypeName,
449                                    unsigned Dim);
450
451  inline unsigned getDim() const { return mDim; }
452
453  virtual bool equals(const RSExportable *E) const;
454};
455
456class RSExportConstantArrayType : public RSExportType {
457  friend class RSExportType;
458 private:
459  const RSExportType *mElementType;  // Array element type
460  unsigned mSize;  // Array size
461
462  RSExportConstantArrayType(RSContext *Context,
463                            const RSExportType *ElementType,
464                            unsigned Size)
465    : RSExportType(Context,
466                   ExportClassConstantArray,
467                   CreateDummyName("ConstantArray", std::string())),
468      mElementType(ElementType),
469      mSize(Size) {
470    return;
471  }
472
473  // @CAT was normalized by calling RSExportType::NormalizeType() before
474  // calling this.
475  static RSExportConstantArrayType *Create(RSContext *Context,
476                                           const clang::ConstantArrayType *CAT);
477
478  virtual llvm::Type *convertToLLVMType() const;
479
480 public:
481  virtual unsigned getSize() const { return mSize; }
482  inline const RSExportType *getElementType() const { return mElementType; }
483
484  std::string getElementName() const {
485    return mElementType->getElementName();
486  }
487
488  virtual bool keep();
489  virtual bool equals(const RSExportable *E) const;
490};
491
492class RSExportRecordType : public RSExportType {
493  friend class RSExportType;
494 public:
495  class Field {
496   private:
497    const RSExportType *mType;
498    // Field name
499    std::string mName;
500    // Link to the struct that contain this field
501    const RSExportRecordType *mParent;
502    // Offset in the container
503    size_t mOffset;
504
505   public:
506    Field(const RSExportType *T,
507          const llvm::StringRef &Name,
508          const RSExportRecordType *Parent,
509          size_t Offset)
510        : mType(T),
511          mName(Name.data(), Name.size()),
512          mParent(Parent),
513          mOffset(Offset) {
514      return;
515    }
516
517    inline const RSExportRecordType *getParent() const { return mParent; }
518    inline const RSExportType *getType() const { return mType; }
519    inline const std::string &getName() const { return mName; }
520    inline size_t getOffsetInParent() const { return mOffset; }
521  };
522
523  typedef std::list<const Field*>::const_iterator const_field_iterator;
524
525  inline const_field_iterator fields_begin() const {
526    return this->mFields.begin();
527  }
528  inline const_field_iterator fields_end() const {
529    return this->mFields.end();
530  }
531
532 private:
533  std::list<const Field*> mFields;
534  bool mIsPacked;
535  // Artificial export struct type is not exported by user (and thus it won't
536  // get reflected)
537  bool mIsArtificial;
538  size_t mStoreSize;
539  size_t mAllocSize;
540
541  RSExportRecordType(RSContext *Context,
542                     const llvm::StringRef &Name,
543                     bool IsPacked,
544                     bool IsArtificial,
545                     size_t StoreSize,
546                     size_t AllocSize)
547      : RSExportType(Context, ExportClassRecord, Name),
548        mIsPacked(IsPacked),
549        mIsArtificial(IsArtificial),
550        mStoreSize(StoreSize),
551        mAllocSize(AllocSize) {
552    return;
553  }
554
555  // @RT was normalized by calling RSExportType::NormalizeType() before calling
556  // this.
557  // @TypeName was retrieved from RSExportType::GetTypeName() before calling
558  // this.
559  static RSExportRecordType *Create(RSContext *Context,
560                                    const clang::RecordType *RT,
561                                    const llvm::StringRef &TypeName,
562                                    bool mIsArtificial = false);
563
564  virtual llvm::Type *convertToLLVMType() const;
565
566 public:
567  inline const std::list<const Field*>& getFields() const { return mFields; }
568  inline bool isPacked() const { return mIsPacked; }
569  inline bool isArtificial() const { return mIsArtificial; }
570  virtual size_t getStoreSize() const { return mStoreSize; }
571  virtual size_t getAllocSize() const { return mAllocSize; }
572
573  virtual std::string getElementName() const {
574    return "ScriptField_" + getName();
575  }
576
577  virtual bool keep();
578  virtual bool equals(const RSExportable *E) const;
579
580  ~RSExportRecordType() {
581    for (std::list<const Field*>::iterator I = mFields.begin(),
582             E = mFields.end();
583         I != E;
584         I++)
585      if (*I != NULL)
586        delete *I;
587    return;
588  }
589};  // RSExportRecordType
590
591}   // namespace slang
592
593#endif  // _FRAMEWORKS_COMPILE_SLANG_SLANG_RS_EXPORT_TYPE_H_  NOLINT
594