InitListHandler.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. //===------- InitListHandler.cpp - Initializer List Handler -----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements an initalizer list handler that takes in an
  10. // InitListExpr and emits the corresponding SPIR-V instructions for it.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "InitListHandler.h"
  14. #include <algorithm>
  15. #include <iterator>
  16. #include "llvm/ADT/SmallVector.h"
  17. namespace clang {
  18. namespace spirv {
  19. InitListHandler::InitListHandler(SPIRVEmitter &emitter)
  20. : theEmitter(emitter), theBuilder(emitter.getModuleBuilder()),
  21. typeTranslator(emitter.getTypeTranslator()),
  22. diags(emitter.getDiagnosticsEngine()) {}
  23. uint32_t InitListHandler::process(const InitListExpr *expr) {
  24. initializers.clear();
  25. scalars.clear();
  26. flatten(expr);
  27. // Reverse the whole initializer list so we can manipulate the list at the
  28. // tail of the vector. This is more efficient than using a deque.
  29. std::reverse(std::begin(initializers), std::end(initializers));
  30. const uint32_t init = createInitForType(expr->getType(), expr->getExprLoc());
  31. if (init) {
  32. // For successful translation, we should have consumed all initializers and
  33. // scalars extracted from them.
  34. assert(initializers.empty());
  35. assert(scalars.empty());
  36. }
  37. return init;
  38. }
  39. void InitListHandler::flatten(const InitListExpr *expr) {
  40. const auto numInits = expr->getNumInits();
  41. for (uint32_t i = 0; i < numInits; ++i) {
  42. const Expr *init = expr->getInit(i);
  43. if (const auto *subInitList = dyn_cast<InitListExpr>(init)) {
  44. flatten(subInitList);
  45. } else if (const auto *subInitList = dyn_cast<InitListExpr>(
  46. // Ignore constructor casts which are no-ops
  47. // For cases like: <type>(<initializer-list>)
  48. init->IgnoreParenNoopCasts(theEmitter.getASTContext()))) {
  49. flatten(subInitList);
  50. } else {
  51. initializers.push_back(init);
  52. }
  53. }
  54. }
  55. void InitListHandler::decompose(const Expr *expr) {
  56. const QualType type = expr->getType();
  57. if (hlsl::IsHLSLVecType(type)) {
  58. const uint32_t vec = theEmitter.loadIfGLValue(expr);
  59. const QualType elemType = hlsl::GetHLSLVecElementType(type);
  60. const auto size = hlsl::GetHLSLVecSize(type);
  61. decomposeVector(vec, elemType, size);
  62. } else if (hlsl::IsHLSLMatType(type)) {
  63. const uint32_t mat = theEmitter.loadIfGLValue(expr);
  64. const QualType elemType = hlsl::GetHLSLMatElementType(type);
  65. uint32_t rowCount = 0, colCount = 0;
  66. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  67. if (rowCount == 1 || colCount == 1) {
  68. // This also handles the scalar case
  69. decomposeVector(mat, elemType, rowCount == 1 ? colCount : rowCount);
  70. } else {
  71. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  72. for (uint32_t i = 0; i < rowCount; ++i)
  73. for (uint32_t j = 0; j < colCount; ++j) {
  74. const uint32_t element =
  75. theBuilder.createCompositeExtract(elemTypeId, mat, {i, j});
  76. scalars.emplace_back(element, elemType);
  77. }
  78. }
  79. } else {
  80. llvm_unreachable("decompose() should only handle vector or matrix types");
  81. }
  82. }
  83. void InitListHandler::decomposeVector(uint32_t vec, QualType elemType,
  84. uint32_t size) {
  85. if (size == 1) {
  86. // Decomposing of size-1 vector just results in the vector itself.
  87. scalars.emplace_back(vec, elemType);
  88. } else {
  89. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  90. for (uint32_t i = 0; i < size; ++i) {
  91. const uint32_t element =
  92. theBuilder.createCompositeExtract(elemTypeId, vec, {i});
  93. scalars.emplace_back(element, elemType);
  94. }
  95. }
  96. }
  97. bool InitListHandler::tryToSplitStruct() {
  98. if (initializers.empty())
  99. return false;
  100. auto *init = const_cast<Expr *>(initializers.back());
  101. const QualType initType = init->getType();
  102. if (!initType->isStructureType() ||
  103. // Sampler types will pass the above check but we cannot split it.
  104. TypeTranslator::isSampler(initType))
  105. return false;
  106. // We are certain the current intializer will be replaced by now.
  107. initializers.pop_back();
  108. const auto &context = theEmitter.getASTContext();
  109. const auto *structDecl = initType->getAsStructureType()->getDecl();
  110. // Create MemberExpr for each field of the struct
  111. llvm::SmallVector<const Expr *, 4> fields;
  112. for (auto *field : structDecl->fields()) {
  113. fields.push_back(MemberExpr::Create(
  114. context, init, /*isarraw*/ false, /*OperatorLoc*/ {},
  115. /*QualifierLoc*/ {}, /*TemplateKWLoc*/ {}, field,
  116. DeclAccessPair::make(field, AS_none),
  117. DeclarationNameInfo(field->getDeclName(), /*NameLoc*/ {}),
  118. /*TemplateArgumentListInfo*/ nullptr, field->getType(),
  119. init->getValueKind(), OK_Ordinary));
  120. }
  121. // Push in the reverse order
  122. initializers.insert(initializers.end(), fields.rbegin(), fields.rend());
  123. return true;
  124. }
  125. bool InitListHandler::tryToSplitConstantArray() {
  126. if (initializers.empty())
  127. return false;
  128. auto *init = const_cast<Expr *>(initializers.back());
  129. const QualType initType = init->getType();
  130. if (!initType->isConstantArrayType())
  131. return false;
  132. // We are certain the current intializer will be replaced by now.
  133. initializers.pop_back();
  134. const auto &context = theEmitter.getASTContext();
  135. const auto u32Type = context.getIntTypeForBitwidth(32, /*sigined*/ 0);
  136. const auto *arrayType = context.getAsConstantArrayType(initType);
  137. const auto elemType = arrayType->getElementType();
  138. // TODO: handle (unlikely) extra large array size?
  139. const auto size = static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  140. // Create ArraySubscriptExpr for each element of the array
  141. // TODO: It will generate lots of elements if the array size is very large.
  142. // But do we have a better solution?
  143. llvm::SmallVector<const Expr *, 4> elements;
  144. for (uint32_t i = 0; i < size; ++i) {
  145. const auto iVal =
  146. llvm::APInt(/*numBits*/ 32, uint64_t(i), /*isSigned*/ false);
  147. auto *index = IntegerLiteral::Create(context, iVal, u32Type, {});
  148. const auto *element = new (context)
  149. ArraySubscriptExpr(init, index, elemType, VK_LValue, OK_Ordinary, {});
  150. elements.push_back(element);
  151. }
  152. // Push in the reverse order
  153. initializers.insert(initializers.end(), elements.rbegin(), elements.rend());
  154. return true;
  155. }
  156. uint32_t InitListHandler::createInitForType(QualType type,
  157. SourceLocation srcLoc) {
  158. type = type.getCanonicalType();
  159. if (type->isBuiltinType())
  160. return createInitForBuiltinType(type, srcLoc);
  161. if (hlsl::IsHLSLVecType(type))
  162. return createInitForVectorType(hlsl::GetHLSLVecElementType(type),
  163. hlsl::GetHLSLVecSize(type), srcLoc);
  164. if (hlsl::IsHLSLMatType(type)) {
  165. uint32_t rowCount = 0, colCount = 0;
  166. hlsl::GetHLSLMatRowColCount(type, rowCount, colCount);
  167. const QualType elemType = hlsl::GetHLSLMatElementType(type);
  168. return createInitForMatrixType(elemType, rowCount, colCount, srcLoc);
  169. }
  170. // Samplers, (RW)Buffers, (RW)Textures
  171. // It is important that this happens before checking of structure types.
  172. if (TypeTranslator::isOpaqueType(type))
  173. return createInitForSamplerImageType(type, srcLoc);
  174. // This should happen before the check for normal struct types
  175. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(type)) {
  176. emitError("cannot handle structured/byte buffer as initializer", srcLoc);
  177. return 0;
  178. }
  179. if (type->isStructureType())
  180. return createInitForStructType(type);
  181. if (type->isConstantArrayType())
  182. return createInitForConstantArrayType(type, srcLoc);
  183. emitError("initializer for type %0 unimplemented", srcLoc) << type;
  184. return 0;
  185. }
  186. uint32_t InitListHandler::createInitForBuiltinType(QualType type,
  187. SourceLocation srcLoc) {
  188. assert(type->isBuiltinType());
  189. if (!scalars.empty()) {
  190. const auto init = scalars.front();
  191. scalars.pop_front();
  192. return theEmitter.castToType(init.first, init.second, type, srcLoc);
  193. }
  194. // Keep splitting structs or arrays
  195. while (tryToSplitStruct() || tryToSplitConstantArray())
  196. ;
  197. const Expr *init = initializers.back();
  198. initializers.pop_back();
  199. if (!init->getType()->isBuiltinType()) {
  200. decompose(init);
  201. return createInitForBuiltinType(type, srcLoc);
  202. }
  203. const uint32_t value = theEmitter.loadIfGLValue(init);
  204. return theEmitter.castToType(value, init->getType(), type, srcLoc);
  205. }
  206. uint32_t InitListHandler::createInitForVectorType(QualType elemType,
  207. uint32_t count,
  208. SourceLocation srcLoc) {
  209. // If we don't have leftover scalars, we can try to see if there is a vector
  210. // of the same size in the original initializer list so that we can use it
  211. // directly. For all other cases, we need to construct a new vector as the
  212. // initializer.
  213. if (scalars.empty()) {
  214. // Keep splitting structs or arrays
  215. while (tryToSplitStruct() || tryToSplitConstantArray())
  216. ;
  217. const Expr *init = initializers.back();
  218. if (hlsl::IsHLSLVecType(init->getType()) &&
  219. hlsl::GetHLSLVecSize(init->getType()) == count) {
  220. initializers.pop_back();
  221. /// HLSL vector types are parameterized templates and we cannot
  222. /// construct them. So we construct an ExtVectorType here instead.
  223. /// This is unfortunate since it means we need to handle ExtVectorType
  224. /// in all type casting methods in SPIRVEmitter.
  225. const auto toVecType =
  226. theEmitter.getASTContext().getExtVectorType(elemType, count);
  227. return theEmitter.castToType(theEmitter.loadIfGLValue(init),
  228. init->getType(), toVecType, srcLoc);
  229. }
  230. }
  231. if (count == 1)
  232. return createInitForBuiltinType(elemType, srcLoc);
  233. llvm::SmallVector<uint32_t, 4> elements;
  234. for (uint32_t i = 0; i < count; ++i) {
  235. // All elements are scalars, which should already be casted to the correct
  236. // type if necessary.
  237. elements.push_back(createInitForBuiltinType(elemType, srcLoc));
  238. }
  239. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  240. const uint32_t vecType = theBuilder.getVecType(elemTypeId, count);
  241. // TODO: use OpConstantComposite when all components are constants
  242. return theBuilder.createCompositeConstruct(vecType, elements);
  243. }
  244. uint32_t InitListHandler::createInitForMatrixType(QualType elemType,
  245. uint32_t rowCount,
  246. uint32_t colCount,
  247. SourceLocation srcLoc) {
  248. // Same as the vector case, first try to see if we already have a matrix at
  249. // the beginning of the initializer queue.
  250. if (scalars.empty()) {
  251. // Keep splitting structs or arrays
  252. while (tryToSplitStruct() || tryToSplitConstantArray())
  253. ;
  254. const Expr *init = initializers.back();
  255. if (hlsl::IsHLSLMatType(init->getType())) {
  256. uint32_t initRowCount = 0, initColCount = 0;
  257. hlsl::GetHLSLMatRowColCount(init->getType(), initRowCount, initColCount);
  258. if (rowCount == initRowCount && colCount == initColCount) {
  259. initializers.pop_back();
  260. // TODO: We only support FP matrices now. Do type cast here after
  261. // adding more matrix types.
  262. return theEmitter.loadIfGLValue(init);
  263. }
  264. }
  265. }
  266. if (rowCount == 1)
  267. return createInitForVectorType(elemType, colCount, srcLoc);
  268. if (colCount == 1)
  269. return createInitForVectorType(elemType, rowCount, srcLoc);
  270. llvm::SmallVector<uint32_t, 4> vectors;
  271. for (uint32_t i = 0; i < rowCount; ++i) {
  272. // All elements are vectors, which should already be casted to the correct
  273. // type if necessary.
  274. vectors.push_back(createInitForVectorType(elemType, colCount, srcLoc));
  275. }
  276. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  277. const uint32_t vecType = theBuilder.getVecType(elemTypeId, colCount);
  278. const uint32_t matType = theBuilder.getMatType(vecType, rowCount);
  279. // TODO: use OpConstantComposite when all components are constants
  280. return theBuilder.createCompositeConstruct(matType, vectors);
  281. }
  282. uint32_t InitListHandler::createInitForStructType(QualType type) {
  283. assert(type->isStructureType() && !TypeTranslator::isSampler(type));
  284. // Same as the vector case, first try to see if we already have a struct at
  285. // the beginning of the initializer queue.
  286. if (scalars.empty()) {
  287. // Keep splitting arrays
  288. while (tryToSplitConstantArray())
  289. ;
  290. const Expr *init = initializers.back();
  291. // We can only avoid decomposing and reconstructing when the type is
  292. // exactly the same.
  293. if (type.getCanonicalType() == init->getType().getCanonicalType()) {
  294. initializers.pop_back();
  295. return theEmitter.loadIfGLValue(init);
  296. }
  297. // Otherwise, if the next initializer is a struct, it is not of the same
  298. // type as we expected. Split it. Just need to do one iteration since a
  299. // field in the next struct initializer may be of the same struct type as
  300. // a field we are about the construct.
  301. tryToSplitStruct();
  302. }
  303. llvm::SmallVector<uint32_t, 4> fields;
  304. const RecordDecl *structDecl = type->getAsStructureType()->getDecl();
  305. for (const auto *field : structDecl->fields()) {
  306. fields.push_back(createInitForType(field->getType(), field->getLocation()));
  307. if (!fields.back())
  308. return 0;
  309. }
  310. const uint32_t typeId = typeTranslator.translateType(type);
  311. // TODO: use OpConstantComposite when all components are constants
  312. return theBuilder.createCompositeConstruct(typeId, fields);
  313. }
  314. uint32_t
  315. InitListHandler::createInitForConstantArrayType(QualType type,
  316. SourceLocation srcLoc) {
  317. assert(type->isConstantArrayType());
  318. // Same as the vector case, first try to see if we already have an array at
  319. // the beginning of the initializer queue.
  320. if (scalars.empty()) {
  321. // Keep splitting structs
  322. while (tryToSplitStruct())
  323. ;
  324. const Expr *init = initializers.back();
  325. // We can only avoid decomposing and reconstructing when the type is
  326. // exactly the same.
  327. if (type.getCanonicalType() == init->getType().getCanonicalType()) {
  328. initializers.pop_back();
  329. return theEmitter.loadIfGLValue(init);
  330. }
  331. // Otherwise, if the next initializer is an array, it is not of the same
  332. // type as we expected. Split it. Just need to do one iteration since the
  333. // next array initializer may have the same element type as the one we
  334. // are about to construct but with different size.
  335. tryToSplitConstantArray();
  336. }
  337. const auto *arrType = theEmitter.getASTContext().getAsConstantArrayType(type);
  338. const auto elemType = arrType->getElementType();
  339. // TODO: handle (unlikely) extra large array size?
  340. const auto size = static_cast<uint32_t>(arrType->getSize().getZExtValue());
  341. llvm::SmallVector<uint32_t, 4> elements;
  342. for (uint32_t i = 0; i < size; ++i)
  343. elements.push_back(createInitForType(elemType, srcLoc));
  344. const uint32_t typeId = typeTranslator.translateType(type);
  345. // TODO: use OpConstantComposite when all components are constants
  346. return theBuilder.createCompositeConstruct(typeId, elements);
  347. }
  348. uint32_t InitListHandler::createInitForSamplerImageType(QualType type,
  349. SourceLocation srcLoc) {
  350. assert(TypeTranslator::isOpaqueType(type));
  351. // Samplers, (RW)Buffers, and (RW)Textures are translated into OpTypeSampler
  352. // and OpTypeImage. They should be treated similar as builtin types.
  353. if (!scalars.empty()) {
  354. const auto init = scalars.front();
  355. scalars.pop_front();
  356. // Require exact type match between the initializer and the target component
  357. if (init.second.getCanonicalType() != type.getCanonicalType()) {
  358. emitError("cannot cast initializer type %0 into variable type %1", srcLoc)
  359. << init.second << type;
  360. return 0;
  361. }
  362. return init.first;
  363. }
  364. // Keep splitting structs or arrays
  365. while (tryToSplitStruct() || tryToSplitConstantArray())
  366. ;
  367. const Expr *init = initializers.back();
  368. initializers.pop_back();
  369. if (init->getType().getCanonicalType() != type.getCanonicalType()) {
  370. init->dump();
  371. emitError("cannot cast initializer type %0 into variable type %1",
  372. init->getLocStart())
  373. << init->getType() << type;
  374. return 0;
  375. }
  376. return theEmitter.loadIfGLValue(init);
  377. }
  378. } // end namespace spirv
  379. } // end namespace clang