InitListHandler.cpp 16 KB

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