slang_rs_export_type.h revision eca0534a31b6185d6ab758f5e97acd7a4cb21e8e
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  // NOTE: There's no any instance of RSExportPrimitiveType which mType
268  // is of the value DataTypeRSMatrix*. DataTypeRSMatrix* enumeration here is
269  // only for RSExportPrimitiveType::GetRSObjectType to *recognize* the struct
270  // rs_matrix{2x2, 3x3, 4x4}. These matrix type are represented as
271  // RSExportMatrixType.
272  DataType mType;
273  bool mNormalized;
274
275  typedef llvm::StringMap<DataType> RSSpecificTypeMapTy;
276  static llvm::ManagedStatic<RSSpecificTypeMapTy> RSSpecificTypeMap;
277
278  static llvm::Type *RSObjectLLVMType;
279
280  static const size_t SizeOfDataTypeInBits[];
281  // @T was normalized by calling RSExportType::NormalizeType() before calling
282  // this.
283  // @TypeName was retrieved from RSExportType::GetTypeName() before calling
284  // this
285  static RSExportPrimitiveType *Create(RSContext *Context,
286                                       const clang::Type *T,
287                                       const llvm::StringRef &TypeName,
288                                       bool Normalized = false);
289
290 protected:
291  RSExportPrimitiveType(RSContext *Context,
292                        // for derived class to set their type class
293                        ExportClass Class,
294                        const llvm::StringRef &Name,
295                        DataType DT,
296                        bool Normalized)
297      : RSExportType(Context, Class, Name),
298        mType(DT),
299        mNormalized(Normalized) {
300    return;
301  }
302
303  virtual llvm::Type *convertToLLVMType() const;
304
305  static DataType GetDataType(RSContext *Context, const clang::Type *T);
306
307 public:
308  // T is normalized by calling RSExportType::NormalizeType() before
309  // calling this
310  static bool IsPrimitiveType(const clang::Type *T);
311
312  // @T may not be normalized
313  static RSExportPrimitiveType *Create(RSContext *Context,
314                                       const clang::Type *T);
315
316  static DataType GetRSSpecificType(const llvm::StringRef &TypeName);
317  static DataType GetRSSpecificType(const clang::Type *T);
318
319  static bool IsRSMatrixType(DataType DT);
320  static bool IsRSObjectType(DataType DT);
321  static bool IsRSObjectType(const clang::Type *T) {
322    return IsRSObjectType(GetRSSpecificType(T));
323  }
324
325  // Determines whether T is [an array of] struct that contains at least one
326  // RS object type within it.
327  static bool IsStructureTypeWithRSObject(const clang::Type *T);
328
329  static size_t GetSizeInBits(const RSExportPrimitiveType *EPT);
330
331  inline DataType getType() const { return mType; }
332  inline bool isRSObjectType() const {
333      return IsRSObjectType(mType);
334  }
335
336  virtual bool equals(const RSExportable *E) const;
337
338  static RSReflectionType *getRSReflectionType(DataType DT);
339  static RSReflectionType *getRSReflectionType(
340      const RSExportPrimitiveType *EPT) {
341    return getRSReflectionType(EPT->getType());
342  }
343
344  virtual unsigned getSize() const { return (GetSizeInBits(this) >> 3); }
345
346  std::string getElementName() const {
347    return getRSReflectionType(this)->rs_short_type;
348  }
349};  // RSExportPrimitiveType
350
351
352class RSExportPointerType : public RSExportType {
353  friend class RSExportType;
354  friend class RSExportFunc;
355 private:
356  const RSExportType *mPointeeType;
357
358  RSExportPointerType(RSContext *Context,
359                      const llvm::StringRef &Name,
360                      const RSExportType *PointeeType)
361      : RSExportType(Context, ExportClassPointer, Name),
362        mPointeeType(PointeeType) {
363    return;
364  }
365
366  // @PT was normalized by calling RSExportType::NormalizeType() before calling
367  // this.
368  static RSExportPointerType *Create(RSContext *Context,
369                                     const clang::PointerType *PT,
370                                     const llvm::StringRef &TypeName);
371
372  virtual llvm::Type *convertToLLVMType() const;
373
374 public:
375  virtual bool keep();
376
377  inline const RSExportType *getPointeeType() const { return mPointeeType; }
378
379  virtual bool equals(const RSExportable *E) const;
380};  // RSExportPointerType
381
382
383class RSExportVectorType : public RSExportPrimitiveType {
384  friend class RSExportType;
385  friend class RSExportElement;
386 private:
387  unsigned mNumElement;   // number of element
388
389  RSExportVectorType(RSContext *Context,
390                     const llvm::StringRef &Name,
391                     DataType DT,
392                     bool Normalized,
393                     unsigned NumElement)
394      : RSExportPrimitiveType(Context, ExportClassVector, Name,
395                              DT, Normalized),
396        mNumElement(NumElement) {
397    return;
398  }
399
400  // @EVT was normalized by calling RSExportType::NormalizeType() before
401  // calling this.
402  static RSExportVectorType *Create(RSContext *Context,
403                                    const clang::ExtVectorType *EVT,
404                                    const llvm::StringRef &TypeName,
405                                    bool Normalized = false);
406
407  virtual llvm::Type *convertToLLVMType() const;
408
409 public:
410  static llvm::StringRef GetTypeName(const clang::ExtVectorType *EVT);
411
412  inline unsigned getNumElement() const { return mNumElement; }
413
414  std::string getElementName() const {
415    std::stringstream Name;
416    Name << RSExportPrimitiveType::getRSReflectionType(this)->rs_short_type
417         << "_" << getNumElement();
418    return Name.str();
419  }
420
421  virtual bool equals(const RSExportable *E) const;
422};
423
424// Only *square* *float* matrix is supported by now.
425//
426// struct rs_matrix{2x2,3x3,4x4, ..., NxN} should be defined as the following
427// form *exactly*:
428//  typedef struct {
429//    float m[{NxN}];
430//  } rs_matrixNxN;
431//
432//  where mDim will be N.
433class RSExportMatrixType : public RSExportType {
434  friend class RSExportType;
435 private:
436  unsigned mDim;  // dimension
437
438  RSExportMatrixType(RSContext *Context,
439                     const llvm::StringRef &Name,
440                     unsigned Dim)
441    : RSExportType(Context, ExportClassMatrix, Name),
442      mDim(Dim) {
443    return;
444  }
445
446  virtual llvm::Type *convertToLLVMType() const;
447
448 public:
449  // @RT was normalized by calling RSExportType::NormalizeType() before
450  // calling this.
451  static RSExportMatrixType *Create(RSContext *Context,
452                                    const clang::RecordType *RT,
453                                    const llvm::StringRef &TypeName,
454                                    unsigned Dim);
455
456  inline unsigned getDim() const { return mDim; }
457
458  virtual bool equals(const RSExportable *E) const;
459};
460
461class RSExportConstantArrayType : public RSExportType {
462  friend class RSExportType;
463 private:
464  const RSExportType *mElementType;  // Array element type
465  unsigned mSize;  // Array size
466
467  RSExportConstantArrayType(RSContext *Context,
468                            const RSExportType *ElementType,
469                            unsigned Size)
470    : RSExportType(Context,
471                   ExportClassConstantArray,
472                   CreateDummyName("ConstantArray", std::string())),
473      mElementType(ElementType),
474      mSize(Size) {
475    return;
476  }
477
478  // @CAT was normalized by calling RSExportType::NormalizeType() before
479  // calling this.
480  static RSExportConstantArrayType *Create(RSContext *Context,
481                                           const clang::ConstantArrayType *CAT);
482
483  virtual llvm::Type *convertToLLVMType() const;
484
485 public:
486  virtual unsigned getSize() const { return mSize; }
487  inline const RSExportType *getElementType() const { return mElementType; }
488
489  std::string getElementName() const {
490    return mElementType->getElementName();
491  }
492
493  virtual bool keep();
494  virtual bool equals(const RSExportable *E) const;
495};
496
497class RSExportRecordType : public RSExportType {
498  friend class RSExportType;
499 public:
500  class Field {
501   private:
502    const RSExportType *mType;
503    // Field name
504    std::string mName;
505    // Link to the struct that contain this field
506    const RSExportRecordType *mParent;
507    // Offset in the container
508    size_t mOffset;
509
510   public:
511    Field(const RSExportType *T,
512          const llvm::StringRef &Name,
513          const RSExportRecordType *Parent,
514          size_t Offset)
515        : mType(T),
516          mName(Name.data(), Name.size()),
517          mParent(Parent),
518          mOffset(Offset) {
519      return;
520    }
521
522    inline const RSExportRecordType *getParent() const { return mParent; }
523    inline const RSExportType *getType() const { return mType; }
524    inline const std::string &getName() const { return mName; }
525    inline size_t getOffsetInParent() const { return mOffset; }
526  };
527
528  typedef std::list<const Field*>::const_iterator const_field_iterator;
529
530  inline const_field_iterator fields_begin() const {
531    return this->mFields.begin();
532  }
533  inline const_field_iterator fields_end() const {
534    return this->mFields.end();
535  }
536
537 private:
538  std::list<const Field*> mFields;
539  bool mIsPacked;
540  // Artificial export struct type is not exported by user (and thus it won't
541  // get reflected)
542  bool mIsArtificial;
543  size_t mStoreSize;
544  size_t mAllocSize;
545
546  RSExportRecordType(RSContext *Context,
547                     const llvm::StringRef &Name,
548                     bool IsPacked,
549                     bool IsArtificial,
550                     size_t StoreSize,
551                     size_t AllocSize)
552      : RSExportType(Context, ExportClassRecord, Name),
553        mIsPacked(IsPacked),
554        mIsArtificial(IsArtificial),
555        mStoreSize(StoreSize),
556        mAllocSize(AllocSize) {
557    return;
558  }
559
560  // @RT was normalized by calling RSExportType::NormalizeType() before calling
561  // this.
562  // @TypeName was retrieved from RSExportType::GetTypeName() before calling
563  // this.
564  static RSExportRecordType *Create(RSContext *Context,
565                                    const clang::RecordType *RT,
566                                    const llvm::StringRef &TypeName,
567                                    bool mIsArtificial = false);
568
569  virtual llvm::Type *convertToLLVMType() const;
570
571 public:
572  inline const std::list<const Field*>& getFields() const { return mFields; }
573  inline bool isPacked() const { return mIsPacked; }
574  inline bool isArtificial() const { return mIsArtificial; }
575  virtual size_t getStoreSize() const { return mStoreSize; }
576  virtual size_t getAllocSize() const { return mAllocSize; }
577
578  virtual std::string getElementName() const {
579    return "ScriptField_" + getName();
580  }
581
582  virtual bool keep();
583  virtual bool equals(const RSExportable *E) const;
584
585  ~RSExportRecordType() {
586    for (std::list<const Field*>::iterator I = mFields.begin(),
587             E = mFields.end();
588         I != E;
589         I++)
590      if (*I != NULL)
591        delete *I;
592    return;
593  }
594};  // RSExportRecordType
595
596}   // namespace slang
597
598#endif  // _FRAMEWORKS_COMPILE_SLANG_SLANG_RS_EXPORT_TYPE_H_  NOLINT
599