slang_rs_export_type.cpp revision e1ee54e9548271704f50b9b1fc34bb9a5816f3e0
1/* 2 * Copyright 2010-2012, The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include "slang_rs_export_type.h" 18 19#include <list> 20#include <vector> 21 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/Attr.h" 24#include "clang/AST/RecordLayout.h" 25 26#include "llvm/ADT/StringExtras.h" 27#include "llvm/IR/DataLayout.h" 28#include "llvm/IR/DerivedTypes.h" 29#include "llvm/IR/Type.h" 30 31#include "slang_assert.h" 32#include "slang_rs_context.h" 33#include "slang_rs_export_element.h" 34#include "slang_version.h" 35 36#define CHECK_PARENT_EQUALITY(ParentClass, E) \ 37 if (!ParentClass::matchODR(E, true)) \ 38 return false; 39 40namespace slang { 41 42namespace { 43 44// For the data types we support: 45// Category - data type category 46// SName - "common name" in script (C99) 47// RsType - element name in RenderScript 48// RsShortType - short element name in RenderScript 49// SizeInBits - size in bits 50// CName - reflected C name 51// JavaName - reflected Java name 52// JavaArrayElementName - reflected name in Java arrays 53// CVecName - prefix for C vector types 54// JavaVecName - prefix for Java vector type 55// JavaPromotion - unsigned type undergoing Java promotion 56// 57// IMPORTANT: The data types in this table should be at the same index as 58// specified by the corresponding DataType enum. 59// 60// TODO: Pull this information out into a separate file. 61static RSReflectionType gReflectionTypes[] = { 62#define _ nullptr 63 // Category SName RsType RsST CName JN JAEN CVN JVN JP 64{PrimitiveDataType, "half", "FLOAT_16", "F16", 16, "half", "short", "short", "Half", "Short", false}, 65{PrimitiveDataType, "float", "FLOAT_32", "F32", 32, "float", "float", "float", "Float", "Float", false}, 66{PrimitiveDataType, "double", "FLOAT_64", "F64", 64, "double", "double", "double", "Double", "Double", false}, 67{PrimitiveDataType, "char", "SIGNED_8", "I8", 8, "int8_t", "byte", "byte", "Byte", "Byte", false}, 68{PrimitiveDataType, "short", "SIGNED_16", "I16", 16, "int16_t", "short", "short", "Short", "Short", false}, 69{PrimitiveDataType, "int", "SIGNED_32", "I32", 32, "int32_t", "int", "int", "Int", "Int", false}, 70{PrimitiveDataType, "long", "SIGNED_64", "I64", 64, "int64_t", "long", "long", "Long", "Long", false}, 71{PrimitiveDataType, "uchar", "UNSIGNED_8", "U8", 8, "uint8_t", "short", "byte", "UByte", "Short", true}, 72{PrimitiveDataType, "ushort", "UNSIGNED_16", "U16", 16, "uint16_t", "int", "short", "UShort", "Int", true}, 73{PrimitiveDataType, "uint", "UNSIGNED_32", "U32", 32, "uint32_t", "long", "int", "UInt", "Long", true}, 74{PrimitiveDataType, "ulong", "UNSIGNED_64", "U64", 64, "uint64_t", "long", "long", "ULong", "Long", false}, 75{PrimitiveDataType, "bool", "BOOLEAN", "BOOLEAN", 8, "bool", "boolean", "byte", _, _, false}, 76{PrimitiveDataType, _, "UNSIGNED_5_6_5", _, 16, _, _, _, _, _, false}, 77{PrimitiveDataType, _, "UNSIGNED_5_5_5_1", _, 16, _, _, _, _, _, false}, 78{PrimitiveDataType, _, "UNSIGNED_4_4_4_4", _, 16, _, _, _, _, _, false}, 79 80{MatrixDataType, "rs_matrix2x2", "MATRIX_2X2", _, 4*32, "rs_matrix2x2", "Matrix2f", _, _, _, false}, 81{MatrixDataType, "rs_matrix3x3", "MATRIX_3X3", _, 9*32, "rs_matrix3x3", "Matrix3f", _, _, _, false}, 82{MatrixDataType, "rs_matrix4x4", "MATRIX_4X4", _, 16*32, "rs_matrix4x4", "Matrix4f", _, _, _, false}, 83 84// RS object types are 32 bits in 32-bit RS, but 256 bits in 64-bit RS. 85// This is handled specially by the GetElementSizeInBits() method. 86{ObjectDataType, _, "RS_ELEMENT", "ELEMENT", 32, "Element", "Element", _, _, _, false}, 87{ObjectDataType, _, "RS_TYPE", "TYPE", 32, "Type", "Type", _, _, _, false}, 88{ObjectDataType, _, "RS_ALLOCATION", "ALLOCATION", 32, "Allocation", "Allocation", _, _, _, false}, 89{ObjectDataType, _, "RS_SAMPLER", "SAMPLER", 32, "Sampler", "Sampler", _, _, _, false}, 90{ObjectDataType, _, "RS_SCRIPT", "SCRIPT", 32, "Script", "Script", _, _, _, false}, 91{ObjectDataType, _, "RS_MESH", "MESH", 32, "Mesh", "Mesh", _, _, _, false}, 92{ObjectDataType, _, "RS_PATH", "PATH", 32, "Path", "Path", _, _, _, false}, 93{ObjectDataType, _, "RS_PROGRAM_FRAGMENT", "PROGRAM_FRAGMENT", 32, "ProgramFragment", "ProgramFragment", _, _, _, false}, 94{ObjectDataType, _, "RS_PROGRAM_VERTEX", "PROGRAM_VERTEX", 32, "ProgramVertex", "ProgramVertex", _, _, _, false}, 95{ObjectDataType, _, "RS_PROGRAM_RASTER", "PROGRAM_RASTER", 32, "ProgramRaster", "ProgramRaster", _, _, _, false}, 96{ObjectDataType, _, "RS_PROGRAM_STORE", "PROGRAM_STORE", 32, "ProgramStore", "ProgramStore", _, _, _, false}, 97{ObjectDataType, _, "RS_FONT", "FONT", 32, "Font", "Font", _, _, _, false}, 98#undef _ 99}; 100 101const int kMaxVectorSize = 4; 102 103struct BuiltinInfo { 104 clang::BuiltinType::Kind builtinTypeKind; 105 DataType type; 106 /* TODO If we return std::string instead of llvm::StringRef, we could build 107 * the name instead of duplicating the entries. 108 */ 109 const char *cname[kMaxVectorSize]; 110}; 111 112 113BuiltinInfo BuiltinInfoTable[] = { 114 {clang::BuiltinType::Bool, DataTypeBoolean, 115 {"bool", "bool2", "bool3", "bool4"}}, 116 {clang::BuiltinType::Char_U, DataTypeUnsigned8, 117 {"uchar", "uchar2", "uchar3", "uchar4"}}, 118 {clang::BuiltinType::UChar, DataTypeUnsigned8, 119 {"uchar", "uchar2", "uchar3", "uchar4"}}, 120 {clang::BuiltinType::Char16, DataTypeSigned16, 121 {"short", "short2", "short3", "short4"}}, 122 {clang::BuiltinType::Char32, DataTypeSigned32, 123 {"int", "int2", "int3", "int4"}}, 124 {clang::BuiltinType::UShort, DataTypeUnsigned16, 125 {"ushort", "ushort2", "ushort3", "ushort4"}}, 126 {clang::BuiltinType::UInt, DataTypeUnsigned32, 127 {"uint", "uint2", "uint3", "uint4"}}, 128 {clang::BuiltinType::ULong, DataTypeUnsigned64, 129 {"ulong", "ulong2", "ulong3", "ulong4"}}, 130 {clang::BuiltinType::ULongLong, DataTypeUnsigned64, 131 {"ulong", "ulong2", "ulong3", "ulong4"}}, 132 133 {clang::BuiltinType::Char_S, DataTypeSigned8, 134 {"char", "char2", "char3", "char4"}}, 135 {clang::BuiltinType::SChar, DataTypeSigned8, 136 {"char", "char2", "char3", "char4"}}, 137 {clang::BuiltinType::Short, DataTypeSigned16, 138 {"short", "short2", "short3", "short4"}}, 139 {clang::BuiltinType::Int, DataTypeSigned32, 140 {"int", "int2", "int3", "int4"}}, 141 {clang::BuiltinType::Long, DataTypeSigned64, 142 {"long", "long2", "long3", "long4"}}, 143 {clang::BuiltinType::LongLong, DataTypeSigned64, 144 {"long", "long2", "long3", "long4"}}, 145 {clang::BuiltinType::Half, DataTypeFloat16, 146 {"half", "half2", "half3", "half4"}}, 147 {clang::BuiltinType::Float, DataTypeFloat32, 148 {"float", "float2", "float3", "float4"}}, 149 {clang::BuiltinType::Double, DataTypeFloat64, 150 {"double", "double2", "double3", "double4"}}, 151}; 152const int BuiltinInfoTableCount = sizeof(BuiltinInfoTable) / sizeof(BuiltinInfoTable[0]); 153 154struct NameAndPrimitiveType { 155 const char *name; 156 DataType dataType; 157}; 158 159static NameAndPrimitiveType MatrixAndObjectDataTypes[] = { 160 {"rs_matrix2x2", DataTypeRSMatrix2x2}, 161 {"rs_matrix3x3", DataTypeRSMatrix3x3}, 162 {"rs_matrix4x4", DataTypeRSMatrix4x4}, 163 {"rs_element", DataTypeRSElement}, 164 {"rs_type", DataTypeRSType}, 165 {"rs_allocation", DataTypeRSAllocation}, 166 {"rs_sampler", DataTypeRSSampler}, 167 {"rs_script", DataTypeRSScript}, 168 {"rs_mesh", DataTypeRSMesh}, 169 {"rs_path", DataTypeRSPath}, 170 {"rs_program_fragment", DataTypeRSProgramFragment}, 171 {"rs_program_vertex", DataTypeRSProgramVertex}, 172 {"rs_program_raster", DataTypeRSProgramRaster}, 173 {"rs_program_store", DataTypeRSProgramStore}, 174 {"rs_font", DataTypeRSFont}, 175}; 176 177const int MatrixAndObjectDataTypesCount = 178 sizeof(MatrixAndObjectDataTypes) / sizeof(MatrixAndObjectDataTypes[0]); 179 180static const clang::Type *TypeExportableHelper( 181 const clang::Type *T, 182 llvm::SmallPtrSet<const clang::Type*, 8>& SPS, 183 slang::RSContext *Context, 184 const clang::VarDecl *VD, 185 const clang::RecordDecl *TopLevelRecord, 186 ExportKind EK); 187 188template <unsigned N> 189static void ReportTypeError(slang::RSContext *Context, 190 const clang::NamedDecl *ND, 191 const clang::RecordDecl *TopLevelRecord, 192 const char (&Message)[N], 193 unsigned int TargetAPI = 0) { 194 // Attempt to use the type declaration first (if we have one). 195 // Fall back to the variable definition, if we are looking at something 196 // like an array declaration that can't be exported. 197 if (TopLevelRecord) { 198 Context->ReportError(TopLevelRecord->getLocation(), Message) 199 << TopLevelRecord->getName() << TargetAPI; 200 } else if (ND) { 201 Context->ReportError(ND->getLocation(), Message) << ND->getName() 202 << TargetAPI; 203 } else { 204 slangAssert(false && "Variables should be validated before exporting"); 205 } 206} 207 208static const clang::Type *ConstantArrayTypeExportableHelper( 209 const clang::ConstantArrayType *CAT, 210 llvm::SmallPtrSet<const clang::Type*, 8>& SPS, 211 slang::RSContext *Context, 212 const clang::VarDecl *VD, 213 const clang::RecordDecl *TopLevelRecord, 214 ExportKind EK) { 215 // Check element type 216 const clang::Type *ElementType = GetConstantArrayElementType(CAT); 217 if (ElementType->isArrayType()) { 218 ReportTypeError(Context, VD, TopLevelRecord, 219 "multidimensional arrays cannot be exported: '%0'"); 220 return nullptr; 221 } else if (ElementType->isExtVectorType()) { 222 const clang::ExtVectorType *EVT = 223 static_cast<const clang::ExtVectorType*>(ElementType); 224 unsigned numElements = EVT->getNumElements(); 225 226 const clang::Type *BaseElementType = GetExtVectorElementType(EVT); 227 if (!RSExportPrimitiveType::IsPrimitiveType(BaseElementType)) { 228 ReportTypeError(Context, VD, TopLevelRecord, 229 "vectors of non-primitive types cannot be exported: '%0'"); 230 return nullptr; 231 } 232 233 if (numElements == 3 && CAT->getSize() != 1) { 234 ReportTypeError(Context, VD, TopLevelRecord, 235 "arrays of width 3 vector types cannot be exported: '%0'"); 236 return nullptr; 237 } 238 } 239 240 if (TypeExportableHelper(ElementType, SPS, Context, VD, 241 TopLevelRecord, EK) == nullptr) { 242 return nullptr; 243 } else { 244 return CAT; 245 } 246} 247 248BuiltinInfo *FindBuiltinType(clang::BuiltinType::Kind builtinTypeKind) { 249 for (int i = 0; i < BuiltinInfoTableCount; i++) { 250 if (builtinTypeKind == BuiltinInfoTable[i].builtinTypeKind) { 251 return &BuiltinInfoTable[i]; 252 } 253 } 254 return nullptr; 255} 256 257static const clang::Type *TypeExportableHelper( 258 clang::Type const *T, 259 llvm::SmallPtrSet<clang::Type const *, 8> &SPS, 260 slang::RSContext *Context, 261 clang::VarDecl const *VD, 262 clang::RecordDecl const *TopLevelRecord, 263 ExportKind EK) { 264 // Normalize first 265 if ((T = GetCanonicalType(T)) == nullptr) 266 return nullptr; 267 268 if (SPS.count(T)) 269 return T; 270 271 const clang::Type *CTI = T->getCanonicalTypeInternal().getTypePtr(); 272 273 switch (T->getTypeClass()) { 274 case clang::Type::Builtin: { 275 const clang::BuiltinType *BT = static_cast<const clang::BuiltinType*>(CTI); 276 return FindBuiltinType(BT->getKind()) == nullptr ? nullptr : T; 277 } 278 case clang::Type::Record: { 279 if (RSExportPrimitiveType::GetRSSpecificType(T) != DataTypeUnknown) { 280 return T; // RS object type, no further checks are needed 281 } 282 283 // Check internal struct 284 if (T->isUnionType()) { 285 ReportTypeError(Context, VD, T->getAsUnionType()->getDecl(), 286 "unions cannot be exported: '%0'"); 287 return nullptr; 288 } else if (!T->isStructureType()) { 289 slangAssert(false && "Unknown type cannot be exported"); 290 return nullptr; 291 } 292 293 clang::RecordDecl *RD = T->getAsStructureType()->getDecl(); 294 if (RD != nullptr) { 295 RD = RD->getDefinition(); 296 if (RD == nullptr) { 297 ReportTypeError(Context, nullptr, T->getAsStructureType()->getDecl(), 298 "struct is not defined in this module"); 299 return nullptr; 300 } 301 } 302 303 if (!TopLevelRecord) { 304 TopLevelRecord = RD; 305 } 306 if (RD->getName().empty()) { 307 ReportTypeError(Context, nullptr, RD, 308 "anonymous structures cannot be exported"); 309 return nullptr; 310 } 311 312 // Fast check 313 if (RD->hasFlexibleArrayMember() || RD->hasObjectMember()) 314 return nullptr; 315 316 // Insert myself into checking set 317 SPS.insert(T); 318 319 // Check all element 320 for (clang::RecordDecl::field_iterator FI = RD->field_begin(), 321 FE = RD->field_end(); 322 FI != FE; 323 FI++) { 324 const clang::FieldDecl *FD = *FI; 325 const clang::Type *FT = RSExportType::GetTypeOfDecl(FD); 326 FT = GetCanonicalType(FT); 327 328 if (!TypeExportableHelper(FT, SPS, Context, VD, TopLevelRecord, 329 EK)) { 330 return nullptr; 331 } 332 333 // We don't support bit fields yet 334 // 335 // TODO(zonr/srhines): allow bit fields of size 8, 16, 32 336 if (FD->isBitField()) { 337 Context->ReportError( 338 FD->getLocation(), 339 "bit fields are not able to be exported: '%0.%1'") 340 << RD->getName() << FD->getName(); 341 return nullptr; 342 } 343 } 344 345 return T; 346 } 347 case clang::Type::FunctionProto: 348 case clang::Type::FunctionNoProto: 349 ReportTypeError(Context, VD, TopLevelRecord, 350 "function types cannot be exported: '%0'"); 351 return nullptr; 352 case clang::Type::Pointer: { 353 if (TopLevelRecord) { 354 ReportTypeError(Context, VD, TopLevelRecord, 355 "structures containing pointers cannot be used as the type of " 356 "an exported global variable or the parameter to an exported " 357 "function: '%0'"); 358 return nullptr; 359 } 360 361 const clang::PointerType *PT = static_cast<const clang::PointerType*>(CTI); 362 const clang::Type *PointeeType = GetPointeeType(PT); 363 364 if (PointeeType->getTypeClass() == clang::Type::Pointer) { 365 ReportTypeError(Context, VD, TopLevelRecord, 366 "multiple levels of pointers cannot be exported: '%0'"); 367 return nullptr; 368 } 369 370 // Void pointers are forbidden for export, although we must accept 371 // void pointers that come in as arguments to a legacy kernel. 372 if (PointeeType->isVoidType() && EK != LegacyKernelArgument) { 373 ReportTypeError(Context, VD, TopLevelRecord, 374 "void pointers cannot be exported: '%0'"); 375 return nullptr; 376 } 377 378 // We don't support pointer with array-type pointee 379 if (PointeeType->isArrayType()) { 380 ReportTypeError(Context, VD, TopLevelRecord, 381 "pointers to arrays cannot be exported: '%0'"); 382 return nullptr; 383 } 384 385 // Check for unsupported pointee type 386 if (TypeExportableHelper(PointeeType, SPS, Context, VD, 387 TopLevelRecord, EK) == nullptr) 388 return nullptr; 389 else 390 return T; 391 } 392 case clang::Type::ExtVector: { 393 const clang::ExtVectorType *EVT = 394 static_cast<const clang::ExtVectorType*>(CTI); 395 // Only vector with size 2, 3 and 4 are supported. 396 if (EVT->getNumElements() < 2 || EVT->getNumElements() > 4) 397 return nullptr; 398 399 // Check base element type 400 const clang::Type *ElementType = GetExtVectorElementType(EVT); 401 402 if ((ElementType->getTypeClass() != clang::Type::Builtin) || 403 (TypeExportableHelper(ElementType, SPS, Context, VD, 404 TopLevelRecord, EK) == nullptr)) 405 return nullptr; 406 else 407 return T; 408 } 409 case clang::Type::ConstantArray: { 410 const clang::ConstantArrayType *CAT = 411 static_cast<const clang::ConstantArrayType*>(CTI); 412 413 return ConstantArrayTypeExportableHelper(CAT, SPS, Context, VD, 414 TopLevelRecord, EK); 415 } 416 case clang::Type::Enum: { 417 // FIXME: We currently convert enums to integers, rather than reflecting 418 // a more complete (and nicer type-safe Java version). 419 return Context->getASTContext().IntTy.getTypePtr(); 420 } 421 default: { 422 slangAssert(false && "Unknown type cannot be validated"); 423 return nullptr; 424 } 425 } 426} 427 428// Return the type that can be used to create RSExportType, will always return 429// the canonical type. 430// 431// If the Type T is not exportable, this function returns nullptr. DiagEngine is 432// used to generate proper Clang diagnostic messages when a non-exportable type 433// is detected. TopLevelRecord is used to capture the highest struct (in the 434// case of a nested hierarchy) for detecting other types that cannot be exported 435// (mostly pointers within a struct). 436static const clang::Type *TypeExportable(const clang::Type *T, 437 slang::RSContext *Context, 438 const clang::VarDecl *VD, 439 ExportKind EK) { 440 llvm::SmallPtrSet<const clang::Type*, 8> SPS = 441 llvm::SmallPtrSet<const clang::Type*, 8>(); 442 443 return TypeExportableHelper(T, SPS, Context, VD, nullptr, EK); 444} 445 446static bool ValidateRSObjectInVarDecl(slang::RSContext *Context, 447 const clang::VarDecl *VD, bool InCompositeType, 448 unsigned int TargetAPI) { 449 if (TargetAPI < SLANG_JB_TARGET_API) { 450 // Only if we are already in a composite type (like an array or structure). 451 if (InCompositeType) { 452 // Only if we are actually exported (i.e. non-static). 453 if (VD->hasLinkage() && 454 (VD->getFormalLinkage() == clang::ExternalLinkage)) { 455 // Only if we are not a pointer to an object. 456 const clang::Type *T = GetCanonicalType(VD->getType().getTypePtr()); 457 if (T->getTypeClass() != clang::Type::Pointer) { 458 ReportTypeError(Context, VD, nullptr, 459 "arrays/structures containing RS object types " 460 "cannot be exported in target API < %1: '%0'", 461 SLANG_JB_TARGET_API); 462 return false; 463 } 464 } 465 } 466 } 467 468 return true; 469} 470 471// Helper function for ValidateType(). We do a recursive descent on the 472// type hierarchy to ensure that we can properly export/handle the 473// declaration. 474// \return true if the variable declaration is valid, 475// false if it is invalid (along with proper diagnostics). 476// 477// C - ASTContext (for diagnostics + builtin types). 478// T - sub-type that we are validating. 479// ND - (optional) top-level named declaration that we are validating. 480// SPS - set of types we have already seen/validated. 481// InCompositeType - true if we are within an outer composite type. 482// UnionDecl - set if we are in a sub-type of a union. 483// TargetAPI - target SDK API level. 484// IsFilterscript - whether or not we are compiling for Filterscript 485// IsExtern - is this type externally visible (i.e. extern global or parameter 486// to an extern function) 487static bool ValidateTypeHelper( 488 slang::RSContext *Context, 489 clang::ASTContext &C, 490 const clang::Type *&T, 491 const clang::NamedDecl *ND, 492 clang::SourceLocation Loc, 493 llvm::SmallPtrSet<const clang::Type*, 8>& SPS, 494 bool InCompositeType, 495 clang::RecordDecl *UnionDecl, 496 unsigned int TargetAPI, 497 bool IsFilterscript, 498 bool IsExtern) { 499 if ((T = GetCanonicalType(T)) == nullptr) 500 return true; 501 502 if (SPS.count(T)) 503 return true; 504 505 const clang::Type *CTI = T->getCanonicalTypeInternal().getTypePtr(); 506 507 switch (T->getTypeClass()) { 508 case clang::Type::Record: { 509 if (RSExportPrimitiveType::IsRSObjectType(T)) { 510 const clang::VarDecl *VD = (ND ? llvm::dyn_cast<clang::VarDecl>(ND) : nullptr); 511 if (VD && !ValidateRSObjectInVarDecl(Context, VD, InCompositeType, 512 TargetAPI)) { 513 return false; 514 } 515 } 516 517 if (RSExportPrimitiveType::GetRSSpecificType(T) != DataTypeUnknown) { 518 if (!UnionDecl) { 519 return true; 520 } else if (RSExportPrimitiveType::IsRSObjectType(T)) { 521 ReportTypeError(Context, nullptr, UnionDecl, 522 "unions containing RS object types are not allowed"); 523 return false; 524 } 525 } 526 527 clang::RecordDecl *RD = nullptr; 528 529 // Check internal struct 530 if (T->isUnionType()) { 531 RD = T->getAsUnionType()->getDecl(); 532 UnionDecl = RD; 533 } else if (T->isStructureType()) { 534 RD = T->getAsStructureType()->getDecl(); 535 } else { 536 slangAssert(false && "Unknown type cannot be exported"); 537 return false; 538 } 539 540 if (RD != nullptr) { 541 RD = RD->getDefinition(); 542 if (RD == nullptr) { 543 // FIXME 544 return true; 545 } 546 } 547 548 // Fast check 549 if (RD->hasFlexibleArrayMember() || RD->hasObjectMember()) 550 return false; 551 552 // Insert myself into checking set 553 SPS.insert(T); 554 555 // Check all elements 556 for (clang::RecordDecl::field_iterator FI = RD->field_begin(), 557 FE = RD->field_end(); 558 FI != FE; 559 FI++) { 560 const clang::FieldDecl *FD = *FI; 561 const clang::Type *FT = RSExportType::GetTypeOfDecl(FD); 562 FT = GetCanonicalType(FT); 563 564 if (!ValidateTypeHelper(Context, C, FT, ND, Loc, SPS, true, UnionDecl, 565 TargetAPI, IsFilterscript, IsExtern)) { 566 return false; 567 } 568 } 569 570 return true; 571 } 572 573 case clang::Type::Builtin: { 574 if (IsFilterscript) { 575 clang::QualType QT = T->getCanonicalTypeInternal(); 576 if (QT == C.DoubleTy || 577 QT == C.LongDoubleTy || 578 QT == C.LongTy || 579 QT == C.LongLongTy) { 580 if (ND) { 581 Context->ReportError( 582 Loc, 583 "Builtin types > 32 bits in size are forbidden in " 584 "Filterscript: '%0'") 585 << ND->getName(); 586 } else { 587 Context->ReportError( 588 Loc, 589 "Builtin types > 32 bits in size are forbidden in " 590 "Filterscript"); 591 } 592 return false; 593 } 594 } 595 break; 596 } 597 598 case clang::Type::Pointer: { 599 if (IsFilterscript) { 600 if (ND) { 601 Context->ReportError(Loc, 602 "Pointers are forbidden in Filterscript: '%0'") 603 << ND->getName(); 604 return false; 605 } else { 606 // TODO(srhines): Find a better way to handle expressions (i.e. no 607 // NamedDecl) involving pointers in FS that should be allowed. 608 // An example would be calls to library functions like 609 // rsMatrixMultiply() that take rs_matrixNxN * types. 610 } 611 } 612 613 // Forbid pointers in structures that are externally visible. 614 if (InCompositeType && IsExtern) { 615 if (ND) { 616 Context->ReportError(Loc, 617 "structures containing pointers cannot be used as the type of " 618 "an exported global variable or the parameter to an exported " 619 "function: '%0'") 620 << ND->getName(); 621 } else { 622 Context->ReportError(Loc, 623 "structures containing pointers cannot be used as the type of " 624 "an exported global variable or the parameter to an exported " 625 "function"); 626 } 627 return false; 628 } 629 630 const clang::PointerType *PT = static_cast<const clang::PointerType*>(CTI); 631 const clang::Type *PointeeType = GetPointeeType(PT); 632 633 return ValidateTypeHelper(Context, C, PointeeType, ND, Loc, SPS, 634 InCompositeType, UnionDecl, TargetAPI, 635 IsFilterscript, IsExtern); 636 } 637 638 case clang::Type::ExtVector: { 639 const clang::ExtVectorType *EVT = 640 static_cast<const clang::ExtVectorType*>(CTI); 641 const clang::Type *ElementType = GetExtVectorElementType(EVT); 642 if (TargetAPI < SLANG_ICS_TARGET_API && 643 InCompositeType && 644 EVT->getNumElements() == 3 && 645 ND && 646 ND->getFormalLinkage() == clang::ExternalLinkage) { 647 ReportTypeError(Context, ND, nullptr, 648 "structs containing vectors of dimension 3 cannot " 649 "be exported at this API level: '%0'"); 650 return false; 651 } 652 return ValidateTypeHelper(Context, C, ElementType, ND, Loc, SPS, true, 653 UnionDecl, TargetAPI, IsFilterscript, IsExtern); 654 } 655 656 case clang::Type::ConstantArray: { 657 const clang::ConstantArrayType *CAT = static_cast<const clang::ConstantArrayType*>(CTI); 658 const clang::Type *ElementType = GetConstantArrayElementType(CAT); 659 return ValidateTypeHelper(Context, C, ElementType, ND, Loc, SPS, true, 660 UnionDecl, TargetAPI, IsFilterscript, IsExtern); 661 } 662 663 default: { 664 break; 665 } 666 } 667 668 return true; 669} 670 671} // namespace 672 673std::string CreateDummyName(const char *type, const std::string &name) { 674 std::stringstream S; 675 S << "<" << type; 676 if (!name.empty()) { 677 S << ":" << name; 678 } 679 S << ">"; 680 return S.str(); 681} 682 683/****************************** RSExportType ******************************/ 684bool RSExportType::NormalizeType(const clang::Type *&T, 685 llvm::StringRef &TypeName, 686 RSContext *Context, 687 const clang::VarDecl *VD, 688 ExportKind EK) { 689 if ((T = TypeExportable(T, Context, VD, EK)) == nullptr) { 690 return false; 691 } 692 // Get type name 693 TypeName = RSExportType::GetTypeName(T); 694 if (Context && TypeName.empty()) { 695 if (VD) { 696 Context->ReportError(VD->getLocation(), 697 "anonymous types cannot be exported"); 698 } else { 699 Context->ReportError("anonymous types cannot be exported"); 700 } 701 return false; 702 } 703 704 return true; 705} 706 707bool RSExportType::ValidateType(slang::RSContext *Context, clang::ASTContext &C, 708 clang::QualType QT, const clang::NamedDecl *ND, 709 clang::SourceLocation Loc, 710 unsigned int TargetAPI, bool IsFilterscript, 711 bool IsExtern) { 712 const clang::Type *T = QT.getTypePtr(); 713 llvm::SmallPtrSet<const clang::Type*, 8> SPS = 714 llvm::SmallPtrSet<const clang::Type*, 8>(); 715 716 // If this is an externally visible variable declaration, we check if the 717 // type is able to be exported first. 718 if (auto VD = llvm::dyn_cast_or_null<clang::VarDecl>(ND)) { 719 if (VD->getFormalLinkage() == clang::ExternalLinkage) { 720 if (!TypeExportable(T, Context, VD, NotLegacyKernelArgument)) { 721 return false; 722 } 723 } 724 } 725 return ValidateTypeHelper(Context, C, T, ND, Loc, SPS, false, nullptr, TargetAPI, 726 IsFilterscript, IsExtern); 727} 728 729bool RSExportType::ValidateVarDecl(slang::RSContext *Context, 730 clang::VarDecl *VD, unsigned int TargetAPI, 731 bool IsFilterscript) { 732 return ValidateType(Context, VD->getASTContext(), VD->getType(), VD, 733 VD->getLocation(), TargetAPI, IsFilterscript, 734 (VD->getFormalLinkage() == clang::ExternalLinkage)); 735} 736 737const clang::Type 738*RSExportType::GetTypeOfDecl(const clang::DeclaratorDecl *DD) { 739 if (DD) { 740 clang::QualType T = DD->getType(); 741 742 if (T.isNull()) 743 return nullptr; 744 else 745 return T.getTypePtr(); 746 } 747 return nullptr; 748} 749 750llvm::StringRef RSExportType::GetTypeName(const clang::Type* T) { 751 T = GetCanonicalType(T); 752 if (T == nullptr) 753 return llvm::StringRef(); 754 755 const clang::Type *CTI = T->getCanonicalTypeInternal().getTypePtr(); 756 757 switch (T->getTypeClass()) { 758 case clang::Type::Builtin: { 759 const clang::BuiltinType *BT = static_cast<const clang::BuiltinType*>(CTI); 760 BuiltinInfo *info = FindBuiltinType(BT->getKind()); 761 if (info != nullptr) { 762 return info->cname[0]; 763 } 764 slangAssert(false && "Unknown data type of the builtin"); 765 break; 766 } 767 case clang::Type::Record: { 768 clang::RecordDecl *RD; 769 if (T->isStructureType()) { 770 RD = T->getAsStructureType()->getDecl(); 771 } else { 772 break; 773 } 774 775 llvm::StringRef Name = RD->getName(); 776 if (Name.empty()) { 777 if (RD->getTypedefNameForAnonDecl() != nullptr) { 778 Name = RD->getTypedefNameForAnonDecl()->getName(); 779 } 780 781 if (Name.empty()) { 782 // Try to find a name from redeclaration (i.e. typedef) 783 for (clang::TagDecl::redecl_iterator RI = RD->redecls_begin(), 784 RE = RD->redecls_end(); 785 RI != RE; 786 RI++) { 787 slangAssert(*RI != nullptr && "cannot be NULL object"); 788 789 Name = (*RI)->getName(); 790 if (!Name.empty()) 791 break; 792 } 793 } 794 } 795 return Name; 796 } 797 case clang::Type::Pointer: { 798 // "*" plus pointee name 799 const clang::PointerType *P = static_cast<const clang::PointerType*>(CTI); 800 const clang::Type *PT = GetPointeeType(P); 801 llvm::StringRef PointeeName; 802 if (NormalizeType(PT, PointeeName, nullptr, nullptr, 803 NotLegacyKernelArgument)) { 804 char *Name = new char[ 1 /* * */ + PointeeName.size() + 1 ]; 805 Name[0] = '*'; 806 memcpy(Name + 1, PointeeName.data(), PointeeName.size()); 807 Name[PointeeName.size() + 1] = '\0'; 808 return Name; 809 } 810 break; 811 } 812 case clang::Type::ExtVector: { 813 const clang::ExtVectorType *EVT = 814 static_cast<const clang::ExtVectorType*>(CTI); 815 return RSExportVectorType::GetTypeName(EVT); 816 break; 817 } 818 case clang::Type::ConstantArray : { 819 // Construct name for a constant array is too complicated. 820 return "<ConstantArray>"; 821 } 822 default: { 823 break; 824 } 825 } 826 827 return llvm::StringRef(); 828} 829 830 831RSExportType *RSExportType::Create(RSContext *Context, 832 const clang::Type *T, 833 const llvm::StringRef &TypeName, 834 ExportKind EK) { 835 // Lookup the context to see whether the type was processed before. 836 // Newly created RSExportType will insert into context 837 // in RSExportType::RSExportType() 838 RSContext::export_type_iterator ETI = Context->findExportType(TypeName); 839 840 if (ETI != Context->export_types_end()) 841 return ETI->second; 842 843 const clang::Type *CTI = T->getCanonicalTypeInternal().getTypePtr(); 844 845 RSExportType *ET = nullptr; 846 switch (T->getTypeClass()) { 847 case clang::Type::Record: { 848 DataType dt = RSExportPrimitiveType::GetRSSpecificType(TypeName); 849 switch (dt) { 850 case DataTypeUnknown: { 851 // User-defined types 852 ET = RSExportRecordType::Create(Context, 853 T->getAsStructureType(), 854 TypeName); 855 break; 856 } 857 case DataTypeRSMatrix2x2: { 858 // 2 x 2 Matrix type 859 ET = RSExportMatrixType::Create(Context, 860 T->getAsStructureType(), 861 TypeName, 862 2); 863 break; 864 } 865 case DataTypeRSMatrix3x3: { 866 // 3 x 3 Matrix type 867 ET = RSExportMatrixType::Create(Context, 868 T->getAsStructureType(), 869 TypeName, 870 3); 871 break; 872 } 873 case DataTypeRSMatrix4x4: { 874 // 4 x 4 Matrix type 875 ET = RSExportMatrixType::Create(Context, 876 T->getAsStructureType(), 877 TypeName, 878 4); 879 break; 880 } 881 default: { 882 // Others are primitive types 883 ET = RSExportPrimitiveType::Create(Context, T, TypeName); 884 break; 885 } 886 } 887 break; 888 } 889 case clang::Type::Builtin: { 890 ET = RSExportPrimitiveType::Create(Context, T, TypeName); 891 break; 892 } 893 case clang::Type::Pointer: { 894 ET = RSExportPointerType::Create(Context, 895 static_cast<const clang::PointerType*>(CTI), 896 TypeName); 897 // FIXME: free the name (allocated in RSExportType::GetTypeName) 898 delete [] TypeName.data(); 899 break; 900 } 901 case clang::Type::ExtVector: { 902 ET = RSExportVectorType::Create(Context, 903 static_cast<const clang::ExtVectorType*>(CTI), 904 TypeName); 905 break; 906 } 907 case clang::Type::ConstantArray: { 908 ET = RSExportConstantArrayType::Create( 909 Context, 910 static_cast<const clang::ConstantArrayType*>(CTI)); 911 break; 912 } 913 default: { 914 Context->ReportError("unknown type cannot be exported: '%0'") 915 << T->getTypeClassName(); 916 break; 917 } 918 } 919 920 return ET; 921} 922 923RSExportType *RSExportType::Create(RSContext *Context, const clang::Type *T, 924 ExportKind EK, const clang::VarDecl *VD) { 925 llvm::StringRef TypeName; 926 if (NormalizeType(T, TypeName, Context, VD, EK)) { 927 return Create(Context, T, TypeName, EK); 928 } else { 929 return nullptr; 930 } 931} 932 933RSExportType *RSExportType::CreateFromDecl(RSContext *Context, 934 const clang::VarDecl *VD) { 935 return RSExportType::Create(Context, GetTypeOfDecl(VD), 936 NotLegacyKernelArgument, VD); 937} 938 939size_t RSExportType::getStoreSize() const { 940 return getRSContext()->getDataLayout().getTypeStoreSize(getLLVMType()); 941} 942 943size_t RSExportType::getAllocSize() const { 944 return getRSContext()->getDataLayout().getTypeAllocSize(getLLVMType()); 945} 946 947RSExportType::RSExportType(RSContext *Context, 948 ExportClass Class, 949 const llvm::StringRef &Name) 950 : RSExportable(Context, RSExportable::EX_TYPE), 951 mClass(Class), 952 // Make a copy on Name since memory stored @Name is either allocated in 953 // ASTContext or allocated in GetTypeName which will be destroyed later. 954 mName(Name.data(), Name.size()), 955 mLLVMType(nullptr) { 956 // Don't cache the type whose name start with '<'. Those type failed to 957 // get their name since constructing their name in GetTypeName() requiring 958 // complicated work. 959 if (!IsDummyName(Name)) { 960 // TODO(zonr): Need to check whether the insertion is successful or not. 961 Context->insertExportType(llvm::StringRef(Name), this); 962 } 963 964} 965 966bool RSExportType::keep() { 967 if (!RSExportable::keep()) 968 return false; 969 // Invalidate converted LLVM type. 970 mLLVMType = nullptr; 971 return true; 972} 973 974bool RSExportType::matchODR(const RSExportType *E, bool /* LookInto */) const { 975 return (E->getClass() == getClass()); 976} 977 978RSExportType::~RSExportType() { 979} 980 981/************************** RSExportPrimitiveType **************************/ 982llvm::ManagedStatic<RSExportPrimitiveType::RSSpecificTypeMapTy> 983RSExportPrimitiveType::RSSpecificTypeMap; 984 985bool RSExportPrimitiveType::IsPrimitiveType(const clang::Type *T) { 986 if ((T != nullptr) && (T->getTypeClass() == clang::Type::Builtin)) 987 return true; 988 else 989 return false; 990} 991 992DataType 993RSExportPrimitiveType::GetRSSpecificType(const llvm::StringRef &TypeName) { 994 if (TypeName.empty()) 995 return DataTypeUnknown; 996 997 if (RSSpecificTypeMap->empty()) { 998 for (int i = 0; i < MatrixAndObjectDataTypesCount; i++) { 999 (*RSSpecificTypeMap)[MatrixAndObjectDataTypes[i].name] = 1000 MatrixAndObjectDataTypes[i].dataType; 1001 } 1002 } 1003 1004 RSSpecificTypeMapTy::const_iterator I = RSSpecificTypeMap->find(TypeName); 1005 if (I == RSSpecificTypeMap->end()) 1006 return DataTypeUnknown; 1007 else 1008 return I->getValue(); 1009} 1010 1011DataType RSExportPrimitiveType::GetRSSpecificType(const clang::Type *T) { 1012 T = GetCanonicalType(T); 1013 if ((T == nullptr) || (T->getTypeClass() != clang::Type::Record)) 1014 return DataTypeUnknown; 1015 1016 return GetRSSpecificType( RSExportType::GetTypeName(T) ); 1017} 1018 1019bool RSExportPrimitiveType::IsRSMatrixType(DataType DT) { 1020 if (DT < 0 || DT >= DataTypeMax) { 1021 return false; 1022 } 1023 return gReflectionTypes[DT].category == MatrixDataType; 1024} 1025 1026bool RSExportPrimitiveType::IsRSObjectType(DataType DT) { 1027 if (DT < 0 || DT >= DataTypeMax) { 1028 return false; 1029 } 1030 return gReflectionTypes[DT].category == ObjectDataType; 1031} 1032 1033bool RSExportPrimitiveType::IsStructureTypeWithRSObject(const clang::Type *T) { 1034 bool RSObjectTypeSeen = false; 1035 slangAssert(T); 1036 while (T->isArrayType()) { 1037 T = T->getArrayElementTypeNoTypeQual(); 1038 slangAssert(T); 1039 } 1040 1041 const clang::RecordType *RT = T->getAsStructureType(); 1042 if (!RT) { 1043 return false; 1044 } 1045 1046 const clang::RecordDecl *RD = RT->getDecl(); 1047 if (RD) { 1048 RD = RD->getDefinition(); 1049 } 1050 if (!RD) { 1051 return false; 1052 } 1053 1054 for (clang::RecordDecl::field_iterator FI = RD->field_begin(), 1055 FE = RD->field_end(); 1056 FI != FE; 1057 FI++) { 1058 // We just look through all field declarations to see if we find a 1059 // declaration for an RS object type (or an array of one). 1060 const clang::FieldDecl *FD = *FI; 1061 const clang::Type *FT = RSExportType::GetTypeOfDecl(FD); 1062 while (FT && FT->isArrayType()) { 1063 FT = FT->getArrayElementTypeNoTypeQual(); 1064 } 1065 1066 DataType DT = GetRSSpecificType(FT); 1067 if (IsRSObjectType(DT)) { 1068 // RS object types definitely need to be zero-initialized 1069 RSObjectTypeSeen = true; 1070 } else { 1071 switch (DT) { 1072 case DataTypeRSMatrix2x2: 1073 case DataTypeRSMatrix3x3: 1074 case DataTypeRSMatrix4x4: 1075 // Matrix types should get zero-initialized as well 1076 RSObjectTypeSeen = true; 1077 break; 1078 default: 1079 // Ignore all other primitive types 1080 break; 1081 } 1082 while (FT && FT->isArrayType()) { 1083 FT = FT->getArrayElementTypeNoTypeQual(); 1084 } 1085 if (FT->isStructureType()) { 1086 // Recursively handle structs of structs (even though these can't 1087 // be exported, it is possible for a user to have them internally). 1088 RSObjectTypeSeen |= IsStructureTypeWithRSObject(FT); 1089 } 1090 } 1091 } 1092 1093 return RSObjectTypeSeen; 1094} 1095 1096size_t RSExportPrimitiveType::GetElementSizeInBits(const RSExportPrimitiveType *EPT) { 1097 int type = EPT->getType(); 1098 slangAssert((type > DataTypeUnknown && type < DataTypeMax) && 1099 "RSExportPrimitiveType::GetElementSizeInBits : unknown data type"); 1100 // All RS object types are 256 bits in 64-bit RS. 1101 if (EPT->isRSObjectType() && EPT->getRSContext()->is64Bit()) { 1102 return 256; 1103 } 1104 return gReflectionTypes[type].size_in_bits; 1105} 1106 1107DataType 1108RSExportPrimitiveType::GetDataType(RSContext *Context, const clang::Type *T) { 1109 if (T == nullptr) 1110 return DataTypeUnknown; 1111 1112 switch (T->getTypeClass()) { 1113 case clang::Type::Builtin: { 1114 const clang::BuiltinType *BT = 1115 static_cast<const clang::BuiltinType*>(T->getCanonicalTypeInternal().getTypePtr()); 1116 BuiltinInfo *info = FindBuiltinType(BT->getKind()); 1117 if (info != nullptr) { 1118 return info->type; 1119 } 1120 // The size of type WChar depend on platform so we abandon the support 1121 // to them. 1122 Context->ReportError("built-in type cannot be exported: '%0'") 1123 << T->getTypeClassName(); 1124 break; 1125 } 1126 case clang::Type::Record: { 1127 // must be RS object type 1128 return RSExportPrimitiveType::GetRSSpecificType(T); 1129 } 1130 default: { 1131 Context->ReportError("primitive type cannot be exported: '%0'") 1132 << T->getTypeClassName(); 1133 break; 1134 } 1135 } 1136 1137 return DataTypeUnknown; 1138} 1139 1140RSExportPrimitiveType 1141*RSExportPrimitiveType::Create(RSContext *Context, 1142 const clang::Type *T, 1143 const llvm::StringRef &TypeName, 1144 bool Normalized) { 1145 DataType DT = GetDataType(Context, T); 1146 1147 if ((DT == DataTypeUnknown) || TypeName.empty()) 1148 return nullptr; 1149 else 1150 return new RSExportPrimitiveType(Context, ExportClassPrimitive, TypeName, 1151 DT, Normalized); 1152} 1153 1154RSExportPrimitiveType *RSExportPrimitiveType::Create(RSContext *Context, 1155 const clang::Type *T) { 1156 llvm::StringRef TypeName; 1157 if (RSExportType::NormalizeType(T, TypeName, Context, nullptr, 1158 NotLegacyKernelArgument) && 1159 IsPrimitiveType(T)) { 1160 return Create(Context, T, TypeName); 1161 } else { 1162 return nullptr; 1163 } 1164} 1165 1166llvm::Type *RSExportPrimitiveType::convertToLLVMType() const { 1167 llvm::LLVMContext &C = getRSContext()->getLLVMContext(); 1168 1169 if (isRSObjectType()) { 1170 // struct { 1171 // int *p; 1172 // } __attribute__((packed, aligned(pointer_size))) 1173 // 1174 // which is 1175 // 1176 // <{ [1 x i32] }> in LLVM 1177 // 1178 std::vector<llvm::Type *> Elements; 1179 if (getRSContext()->is64Bit()) { 1180 // 64-bit path 1181 Elements.push_back(llvm::ArrayType::get(llvm::Type::getInt64Ty(C), 4)); 1182 return llvm::StructType::get(C, Elements, true); 1183 } else { 1184 // 32-bit legacy path 1185 Elements.push_back(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)); 1186 return llvm::StructType::get(C, Elements, true); 1187 } 1188 } 1189 1190 switch (mType) { 1191 case DataTypeFloat16: { 1192 return llvm::Type::getHalfTy(C); 1193 break; 1194 } 1195 case DataTypeFloat32: { 1196 return llvm::Type::getFloatTy(C); 1197 break; 1198 } 1199 case DataTypeFloat64: { 1200 return llvm::Type::getDoubleTy(C); 1201 break; 1202 } 1203 case DataTypeBoolean: { 1204 return llvm::Type::getInt1Ty(C); 1205 break; 1206 } 1207 case DataTypeSigned8: 1208 case DataTypeUnsigned8: { 1209 return llvm::Type::getInt8Ty(C); 1210 break; 1211 } 1212 case DataTypeSigned16: 1213 case DataTypeUnsigned16: 1214 case DataTypeUnsigned565: 1215 case DataTypeUnsigned5551: 1216 case DataTypeUnsigned4444: { 1217 return llvm::Type::getInt16Ty(C); 1218 break; 1219 } 1220 case DataTypeSigned32: 1221 case DataTypeUnsigned32: { 1222 return llvm::Type::getInt32Ty(C); 1223 break; 1224 } 1225 case DataTypeSigned64: 1226 case DataTypeUnsigned64: { 1227 return llvm::Type::getInt64Ty(C); 1228 break; 1229 } 1230 default: { 1231 slangAssert(false && "Unknown data type"); 1232 } 1233 } 1234 1235 return nullptr; 1236} 1237 1238bool RSExportPrimitiveType::matchODR(const RSExportType *E, 1239 bool /* LookInto */) const { 1240 CHECK_PARENT_EQUALITY(RSExportType, E); 1241 return (static_cast<const RSExportPrimitiveType*>(E)->getType() == getType()); 1242} 1243 1244RSReflectionType *RSExportPrimitiveType::getRSReflectionType(DataType DT) { 1245 if (DT > DataTypeUnknown && DT < DataTypeMax) { 1246 return &gReflectionTypes[DT]; 1247 } else { 1248 return nullptr; 1249 } 1250} 1251 1252/**************************** RSExportPointerType ****************************/ 1253 1254RSExportPointerType 1255*RSExportPointerType::Create(RSContext *Context, 1256 const clang::PointerType *PT, 1257 const llvm::StringRef &TypeName) { 1258 const clang::Type *PointeeType = GetPointeeType(PT); 1259 const RSExportType *PointeeET; 1260 1261 if (PointeeType->getTypeClass() != clang::Type::Pointer) { 1262 PointeeET = RSExportType::Create(Context, PointeeType, 1263 NotLegacyKernelArgument); 1264 } else { 1265 // Double or higher dimension of pointer, export as int* 1266 PointeeET = RSExportPrimitiveType::Create(Context, 1267 Context->getASTContext().IntTy.getTypePtr()); 1268 } 1269 1270 if (PointeeET == nullptr) { 1271 // Error diagnostic is emitted for corresponding pointee type 1272 return nullptr; 1273 } 1274 1275 return new RSExportPointerType(Context, TypeName, PointeeET); 1276} 1277 1278llvm::Type *RSExportPointerType::convertToLLVMType() const { 1279 llvm::Type *PointeeType = mPointeeType->getLLVMType(); 1280 return llvm::PointerType::getUnqual(PointeeType); 1281} 1282 1283bool RSExportPointerType::keep() { 1284 if (!RSExportType::keep()) 1285 return false; 1286 const_cast<RSExportType*>(mPointeeType)->keep(); 1287 return true; 1288} 1289 1290bool RSExportPointerType::matchODR(const RSExportType *E, 1291 bool /* LookInto */) const { 1292 // Exported types cannot contain pointers 1293 slangAssert(false && "Not supposed to perform ODR check on pointers"); 1294 return false; 1295} 1296 1297/***************************** RSExportVectorType *****************************/ 1298llvm::StringRef 1299RSExportVectorType::GetTypeName(const clang::ExtVectorType *EVT) { 1300 const clang::Type *ElementType = GetExtVectorElementType(EVT); 1301 llvm::StringRef name; 1302 1303 if ((ElementType->getTypeClass() != clang::Type::Builtin)) 1304 return name; 1305 1306 const clang::BuiltinType *BT = 1307 static_cast<const clang::BuiltinType*>( 1308 ElementType->getCanonicalTypeInternal().getTypePtr()); 1309 1310 if ((EVT->getNumElements() < 1) || 1311 (EVT->getNumElements() > 4)) 1312 return name; 1313 1314 BuiltinInfo *info = FindBuiltinType(BT->getKind()); 1315 if (info != nullptr) { 1316 int I = EVT->getNumElements() - 1; 1317 if (I < kMaxVectorSize) { 1318 name = info->cname[I]; 1319 } else { 1320 slangAssert(false && "Max vector is 4"); 1321 } 1322 } 1323 return name; 1324} 1325 1326RSExportVectorType *RSExportVectorType::Create(RSContext *Context, 1327 const clang::ExtVectorType *EVT, 1328 const llvm::StringRef &TypeName, 1329 bool Normalized) { 1330 slangAssert(EVT != nullptr && EVT->getTypeClass() == clang::Type::ExtVector); 1331 1332 const clang::Type *ElementType = GetExtVectorElementType(EVT); 1333 DataType DT = RSExportPrimitiveType::GetDataType(Context, ElementType); 1334 1335 if (DT != DataTypeUnknown) 1336 return new RSExportVectorType(Context, 1337 TypeName, 1338 DT, 1339 Normalized, 1340 EVT->getNumElements()); 1341 else 1342 return nullptr; 1343} 1344 1345llvm::Type *RSExportVectorType::convertToLLVMType() const { 1346 llvm::Type *ElementType = RSExportPrimitiveType::convertToLLVMType(); 1347 return llvm::VectorType::get(ElementType, getNumElement()); 1348} 1349 1350bool RSExportVectorType::matchODR(const RSExportType *E, 1351 bool /* LookInto*/) const { 1352 CHECK_PARENT_EQUALITY(RSExportPrimitiveType, E); 1353 return (static_cast<const RSExportVectorType*>(E)->getNumElement() 1354 == getNumElement()); 1355} 1356 1357/***************************** RSExportMatrixType *****************************/ 1358RSExportMatrixType *RSExportMatrixType::Create(RSContext *Context, 1359 const clang::RecordType *RT, 1360 const llvm::StringRef &TypeName, 1361 unsigned Dim) { 1362 slangAssert((RT != nullptr) && (RT->getTypeClass() == clang::Type::Record)); 1363 slangAssert((Dim > 1) && "Invalid dimension of matrix"); 1364 1365 // Check whether the struct rs_matrix is in our expected form (but assume it's 1366 // correct if we're not sure whether it's correct or not) 1367 const clang::RecordDecl* RD = RT->getDecl(); 1368 RD = RD->getDefinition(); 1369 if (RD != nullptr) { 1370 // Find definition, perform further examination 1371 if (RD->field_empty()) { 1372 Context->ReportError( 1373 RD->getLocation(), 1374 "invalid matrix struct: must have 1 field for saving values: '%0'") 1375 << RD->getName(); 1376 return nullptr; 1377 } 1378 1379 clang::RecordDecl::field_iterator FIT = RD->field_begin(); 1380 const clang::FieldDecl *FD = *FIT; 1381 const clang::Type *FT = RSExportType::GetTypeOfDecl(FD); 1382 if ((FT == nullptr) || (FT->getTypeClass() != clang::Type::ConstantArray)) { 1383 Context->ReportError(RD->getLocation(), 1384 "invalid matrix struct: first field should" 1385 " be an array with constant size: '%0'") 1386 << RD->getName(); 1387 return nullptr; 1388 } 1389 const clang::ConstantArrayType *CAT = 1390 static_cast<const clang::ConstantArrayType *>(FT); 1391 const clang::Type *ElementType = GetConstantArrayElementType(CAT); 1392 if ((ElementType == nullptr) || 1393 (ElementType->getTypeClass() != clang::Type::Builtin) || 1394 (static_cast<const clang::BuiltinType *>(ElementType)->getKind() != 1395 clang::BuiltinType::Float)) { 1396 Context->ReportError(RD->getLocation(), 1397 "invalid matrix struct: first field " 1398 "should be a float array: '%0'") 1399 << RD->getName(); 1400 return nullptr; 1401 } 1402 1403 if (CAT->getSize() != Dim * Dim) { 1404 Context->ReportError(RD->getLocation(), 1405 "invalid matrix struct: first field " 1406 "should be an array with size %0: '%1'") 1407 << (Dim * Dim) << (RD->getName()); 1408 return nullptr; 1409 } 1410 1411 FIT++; 1412 if (FIT != RD->field_end()) { 1413 Context->ReportError(RD->getLocation(), 1414 "invalid matrix struct: must have " 1415 "exactly 1 field: '%0'") 1416 << RD->getName(); 1417 return nullptr; 1418 } 1419 } 1420 1421 return new RSExportMatrixType(Context, TypeName, Dim); 1422} 1423 1424llvm::Type *RSExportMatrixType::convertToLLVMType() const { 1425 // Construct LLVM type: 1426 // struct { 1427 // float X[mDim * mDim]; 1428 // } 1429 1430 llvm::LLVMContext &C = getRSContext()->getLLVMContext(); 1431 llvm::ArrayType *X = llvm::ArrayType::get(llvm::Type::getFloatTy(C), 1432 mDim * mDim); 1433 return llvm::StructType::get(C, X, false); 1434} 1435 1436bool RSExportMatrixType::matchODR(const RSExportType *E, 1437 bool /* LookInto */) const { 1438 CHECK_PARENT_EQUALITY(RSExportType, E); 1439 return (static_cast<const RSExportMatrixType*>(E)->getDim() == getDim()); 1440} 1441 1442/************************* RSExportConstantArrayType *************************/ 1443RSExportConstantArrayType 1444*RSExportConstantArrayType::Create(RSContext *Context, 1445 const clang::ConstantArrayType *CAT) { 1446 slangAssert(CAT != nullptr && CAT->getTypeClass() == clang::Type::ConstantArray); 1447 1448 slangAssert((CAT->getSize().getActiveBits() < 32) && "array too large"); 1449 1450 unsigned Size = static_cast<unsigned>(CAT->getSize().getZExtValue()); 1451 slangAssert((Size > 0) && "Constant array should have size greater than 0"); 1452 1453 const clang::Type *ElementType = GetConstantArrayElementType(CAT); 1454 RSExportType *ElementET = RSExportType::Create(Context, ElementType, 1455 NotLegacyKernelArgument); 1456 1457 if (ElementET == nullptr) { 1458 return nullptr; 1459 } 1460 1461 return new RSExportConstantArrayType(Context, 1462 ElementET, 1463 Size); 1464} 1465 1466llvm::Type *RSExportConstantArrayType::convertToLLVMType() const { 1467 return llvm::ArrayType::get(mElementType->getLLVMType(), getNumElement()); 1468} 1469 1470bool RSExportConstantArrayType::keep() { 1471 if (!RSExportType::keep()) 1472 return false; 1473 const_cast<RSExportType*>(mElementType)->keep(); 1474 return true; 1475} 1476 1477bool RSExportConstantArrayType::matchODR(const RSExportType *E, 1478 bool LookInto) const { 1479 CHECK_PARENT_EQUALITY(RSExportType, E); 1480 const RSExportConstantArrayType *RHS = 1481 static_cast<const RSExportConstantArrayType*>(E); 1482 return ((getNumElement() == RHS->getNumElement()) && 1483 (getElementType()->matchODR(RHS->getElementType(), LookInto))); 1484} 1485 1486/**************************** RSExportRecordType ****************************/ 1487RSExportRecordType *RSExportRecordType::Create(RSContext *Context, 1488 const clang::RecordType *RT, 1489 const llvm::StringRef &TypeName, 1490 bool mIsArtificial) { 1491 slangAssert(RT != nullptr && RT->getTypeClass() == clang::Type::Record); 1492 1493 const clang::RecordDecl *RD = RT->getDecl(); 1494 slangAssert(RD->isStruct()); 1495 1496 RD = RD->getDefinition(); 1497 if (RD == nullptr) { 1498 slangAssert(false && "struct is not defined in this module"); 1499 return nullptr; 1500 } 1501 1502 // Struct layout construct by clang. We rely on this for obtaining the 1503 // alloc size of a struct and offset of every field in that struct. 1504 const clang::ASTRecordLayout *RL = 1505 &Context->getASTContext().getASTRecordLayout(RD); 1506 slangAssert((RL != nullptr) && 1507 "Failed to retrieve the struct layout from Clang."); 1508 1509 RSExportRecordType *ERT = 1510 new RSExportRecordType(Context, 1511 TypeName, 1512 RD->hasAttr<clang::PackedAttr>(), 1513 mIsArtificial, 1514 RL->getDataSize().getQuantity(), 1515 RL->getSize().getQuantity()); 1516 unsigned int Index = 0; 1517 1518 for (clang::RecordDecl::field_iterator FI = RD->field_begin(), 1519 FE = RD->field_end(); 1520 FI != FE; 1521 FI++, Index++) { 1522 1523 // FIXME: All fields should be primitive type 1524 slangAssert(FI->getKind() == clang::Decl::Field); 1525 clang::FieldDecl *FD = *FI; 1526 1527 if (FD->isBitField()) { 1528 return nullptr; 1529 } 1530 1531 if (FD->isImplicit() && (FD->getName() == RS_PADDING_FIELD_NAME)) 1532 continue; 1533 1534 // Type 1535 RSExportType *ET = RSExportElement::CreateFromDecl(Context, FD); 1536 1537 if (ET != nullptr) { 1538 ERT->mFields.push_back( 1539 new Field(ET, FD->getName(), ERT, 1540 static_cast<size_t>(RL->getFieldOffset(Index) >> 3))); 1541 } else { 1542 // clang static analysis complains about a potential memory leak 1543 // for the memory pointed by ERT at the end of this basic 1544 // block. This is a false warning because the compiler does not 1545 // see that the pointer to this memory is saved away in the 1546 // constructor for RSExportRecordType by calling 1547 // RSContext::newExportable(this). So, we disable this 1548 // particular instance of the warning. 1549 Context->ReportError(RD->getLocation(), 1550 "field type cannot be exported: '%0.%1'") 1551 << RD->getName() << FD->getName(); // NOLINT 1552 return nullptr; 1553 } 1554 } 1555 1556 return ERT; 1557} 1558 1559llvm::Type *RSExportRecordType::convertToLLVMType() const { 1560 // Create an opaque type since struct may reference itself recursively. 1561 1562 // TODO(sliao): LLVM took out the OpaqueType. Any other to migrate to? 1563 std::vector<llvm::Type*> FieldTypes; 1564 1565 for (const_field_iterator FI = fields_begin(), FE = fields_end(); 1566 FI != FE; 1567 FI++) { 1568 const Field *F = *FI; 1569 const RSExportType *FET = F->getType(); 1570 1571 FieldTypes.push_back(FET->getLLVMType()); 1572 } 1573 1574 llvm::StructType *ST = llvm::StructType::get(getRSContext()->getLLVMContext(), 1575 FieldTypes, 1576 mIsPacked); 1577 if (ST != nullptr) { 1578 return ST; 1579 } else { 1580 return nullptr; 1581 } 1582} 1583 1584bool RSExportRecordType::keep() { 1585 if (!RSExportType::keep()) 1586 return false; 1587 for (std::list<const Field*>::iterator I = mFields.begin(), 1588 E = mFields.end(); 1589 I != E; 1590 I++) { 1591 const_cast<RSExportType*>((*I)->getType())->keep(); 1592 } 1593 return true; 1594} 1595 1596bool RSExportRecordType::matchODR(const RSExportType *E, bool LookInto) const { 1597 CHECK_PARENT_EQUALITY(RSExportType, E); 1598 // Enforce ODR checking - the type E represents must hold 1599 // *exactly* the same "definition" as the one defined previously. We 1600 // say two record types A and B have the same definition iff: 1601 // 1602 // struct A { struct B { 1603 // Type(a1) a1, Type(b1) b1, 1604 // Type(a2) a2, Type(b1) b2, 1605 // ... ... 1606 // Type(aN) aN Type(bM) bM, 1607 // }; } 1608 // Cond. #0. A = B; 1609 // Cond. #1. They have same number of fields, i.e., N = M; 1610 // Cond. #2. for (i := 1 to N) 1611 // Type(ai).matchODR(Type(bi)) must hold; 1612 // Cond. #3. for (i := 1 to N) 1613 // Name(ai) = Name(bi) must hold; 1614 // 1615 // where, 1616 // Type(F) = the type of field F and 1617 // Name(F) = the field name. 1618 1619 1620 const RSExportRecordType *ERT = static_cast<const RSExportRecordType*>(E); 1621 // Cond. #0. 1622 if (getName() != ERT->getName()) 1623 return false; 1624 1625 // Examine fields - types and names 1626 if (LookInto) { 1627 // Cond. #1 1628 if (ERT->getFields().size() != getFields().size()) 1629 return false; 1630 1631 for (RSExportRecordType::const_field_iterator AI = fields_begin(), 1632 BI = ERT->fields_begin(), AE = fields_end(); AI != AE; ++AI, ++BI) { 1633 const RSExportType *AITy = (*AI)->getType(); 1634 const RSExportType *BITy = (*BI)->getType(); 1635 // Cond. #3; field names must agree 1636 if ((*AI)->getName() != (*BI)->getName()) 1637 return false; 1638 1639 // Cond. #2; field types must agree recursively until we see another 1640 // next level of RSExportRecordType - such field types will be 1641 // examined and reported later when checkODR() encounters them. 1642 if (!AITy->matchODR(BITy, false)) 1643 return false; 1644 } 1645 } 1646 return true; 1647} 1648 1649void RSExportType::convertToRTD(RSReflectionTypeData *rtd) const { 1650 memset(rtd, 0, sizeof(*rtd)); 1651 rtd->vecSize = 1; 1652 1653 switch(getClass()) { 1654 case RSExportType::ExportClassPrimitive: { 1655 const RSExportPrimitiveType *EPT = static_cast<const RSExportPrimitiveType*>(this); 1656 rtd->type = RSExportPrimitiveType::getRSReflectionType(EPT); 1657 return; 1658 } 1659 case RSExportType::ExportClassPointer: { 1660 const RSExportPointerType *EPT = static_cast<const RSExportPointerType*>(this); 1661 const RSExportType *PointeeType = EPT->getPointeeType(); 1662 PointeeType->convertToRTD(rtd); 1663 rtd->isPointer = true; 1664 return; 1665 } 1666 case RSExportType::ExportClassVector: { 1667 const RSExportVectorType *EVT = static_cast<const RSExportVectorType*>(this); 1668 rtd->type = EVT->getRSReflectionType(EVT); 1669 rtd->vecSize = EVT->getNumElement(); 1670 return; 1671 } 1672 case RSExportType::ExportClassMatrix: { 1673 const RSExportMatrixType *EMT = static_cast<const RSExportMatrixType*>(this); 1674 unsigned Dim = EMT->getDim(); 1675 slangAssert((Dim >= 2) && (Dim <= 4)); 1676 rtd->type = &gReflectionTypes[15 + Dim-2]; 1677 return; 1678 } 1679 case RSExportType::ExportClassConstantArray: { 1680 const RSExportConstantArrayType* CAT = 1681 static_cast<const RSExportConstantArrayType*>(this); 1682 CAT->getElementType()->convertToRTD(rtd); 1683 rtd->arraySize = CAT->getNumElement(); 1684 return; 1685 } 1686 case RSExportType::ExportClassRecord: { 1687 slangAssert(!"RSExportType::ExportClassRecord not implemented"); 1688 return;// RS_TYPE_CLASS_NAME_PREFIX + ET->getName() + ".Item"; 1689 } 1690 default: { 1691 slangAssert(false && "Unknown class of type"); 1692 } 1693 } 1694} 1695 1696 1697} // namespace slang 1698