InitListHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. // Can not split structuredOrByteBuffer
  115. isAKindOfStructuredOrByteBuffer(initType))
  116. return false;
  117. // We are certain the current intializer will be replaced by now.
  118. initializers.pop_back();
  119. const auto &loc = init->getSourceLocation();
  120. const auto *structDecl = initType->getAsStructureType()->getDecl();
  121. // Create MemberExpr for each field of the struct
  122. llvm::SmallVector<SpirvInstruction *, 4> fields;
  123. uint32_t i = 0;
  124. for (auto *field : structDecl->fields()) {
  125. auto *extract =
  126. spvBuilder.createCompositeExtract(field->getType(), init, {i}, loc);
  127. fields.push_back(extract);
  128. ++i;
  129. }
  130. // Push in the reverse order
  131. initializers.insert(initializers.end(), fields.rbegin(), fields.rend());
  132. return true;
  133. }
  134. bool InitListHandler::tryToSplitConstantArray() {
  135. if (initializers.empty())
  136. return false;
  137. auto *init = initializers.back();
  138. const QualType initType = init->getAstResultType();
  139. if (!initType->isConstantArrayType())
  140. return false;
  141. // We are certain the current intializer will be replaced by now.
  142. initializers.pop_back();
  143. const auto &loc = init->getSourceLocation();
  144. const auto &context = theEmitter.getASTContext();
  145. const auto *arrayType = context.getAsConstantArrayType(initType);
  146. const auto elemType = arrayType->getElementType();
  147. // TODO: handle (unlikely) extra large array size?
  148. const auto size = static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  149. // Create ArraySubscriptExpr for each element of the array
  150. // TODO: It will generate lots of elements if the array size is very large.
  151. // But do we have a better solution?
  152. llvm::SmallVector<SpirvInstruction *, 4> elements;
  153. for (uint32_t i = 0; i < size; ++i) {
  154. auto *extract = spvBuilder.createCompositeExtract(elemType, init, {i}, loc);
  155. elements.push_back(extract);
  156. }
  157. // Push in the reverse order
  158. initializers.insert(initializers.end(), elements.rbegin(), elements.rend());
  159. return true;
  160. }
  161. SpirvInstruction *InitListHandler::createInitForType(QualType type,
  162. SourceLocation srcLoc) {
  163. type = type.getCanonicalType();
  164. if (type->isBuiltinType())
  165. return createInitForBuiltinType(type, srcLoc);
  166. QualType elemType = {};
  167. uint32_t elemCount = 0;
  168. if (isVectorType(type, &elemType, &elemCount))
  169. return createInitForVectorType(elemType, elemCount, srcLoc);
  170. // The purpose of this check is for vectors of size 1 (for which isVectorType
  171. // is false).
  172. if (isScalarType(type, &elemType))
  173. return createInitForVectorType(elemType, 1, srcLoc);
  174. if (hlsl::IsHLSLMatType(type)) {
  175. return createInitForMatrixType(type, srcLoc);
  176. }
  177. // Samplers, (RW)Buffers, (RW)Textures
  178. // It is important that this happens before checking of structure types.
  179. if (isOpaqueType(type))
  180. return createInitForBufferOrImageType(type, srcLoc);
  181. // This should happen before the check for normal struct types
  182. if (isAKindOfStructuredOrByteBuffer(type)) {
  183. return createInitForBufferOrImageType(type, srcLoc);
  184. }
  185. if (type->isStructureType())
  186. return createInitForStructType(type, srcLoc);
  187. if (type->isConstantArrayType())
  188. return createInitForConstantArrayType(type, srcLoc);
  189. emitError("initializer for type %0 unimplemented", srcLoc) << type;
  190. return nullptr;
  191. }
  192. SpirvInstruction *
  193. InitListHandler::createInitForBuiltinType(QualType type,
  194. SourceLocation srcLoc) {
  195. assert(type->isBuiltinType());
  196. if (!scalars.empty()) {
  197. const auto init = scalars.front();
  198. scalars.pop_front();
  199. return theEmitter.castToType(init.first, init.second, type, srcLoc);
  200. }
  201. // Keep splitting structs or arrays
  202. while (tryToSplitStruct() || tryToSplitConstantArray())
  203. ;
  204. auto init = initializers.back();
  205. initializers.pop_back();
  206. if (!init->getAstResultType()->isBuiltinType()) {
  207. decompose(init, srcLoc);
  208. return createInitForBuiltinType(type, srcLoc);
  209. }
  210. return theEmitter.castToType(init, init->getAstResultType(), type, srcLoc);
  211. }
  212. SpirvInstruction *
  213. InitListHandler::createInitForVectorType(QualType elemType, uint32_t count,
  214. SourceLocation srcLoc) {
  215. // If we don't have leftover scalars, we can try to see if there is a vector
  216. // of the same size in the original initializer list so that we can use it
  217. // directly. For all other cases, we need to construct a new vector as the
  218. // initializer.
  219. if (scalars.empty()) {
  220. // Keep splitting structs or arrays
  221. while (tryToSplitStruct() || tryToSplitConstantArray())
  222. ;
  223. auto init = initializers.back();
  224. const auto initType = init->getAstResultType();
  225. uint32_t elemCount = 0;
  226. if (isVectorType(initType, nullptr, &elemCount) && elemCount == count) {
  227. initializers.pop_back();
  228. /// HLSL vector types are parameterized templates and we cannot
  229. /// construct them. So we construct an ExtVectorType here instead.
  230. /// This is unfortunate since it means we need to handle ExtVectorType
  231. /// in all type casting methods in SpirvEmitter.
  232. const auto toVecType =
  233. theEmitter.getASTContext().getExtVectorType(elemType, count);
  234. return theEmitter.castToType(init, initType, toVecType, srcLoc);
  235. }
  236. }
  237. if (count == 1)
  238. return createInitForBuiltinType(elemType, srcLoc);
  239. llvm::SmallVector<SpirvInstruction *, 4> elements;
  240. for (uint32_t i = 0; i < count; ++i) {
  241. // All elements are scalars, which should already be casted to the correct
  242. // type if necessary.
  243. elements.push_back(createInitForBuiltinType(elemType, srcLoc));
  244. }
  245. const QualType vecType = astContext.getExtVectorType(elemType, count);
  246. // TODO: use OpConstantComposite when all components are constants
  247. return spvBuilder.createCompositeConstruct(vecType, elements, srcLoc);
  248. }
  249. SpirvInstruction *
  250. InitListHandler::createInitForMatrixType(QualType matrixType,
  251. SourceLocation srcLoc) {
  252. uint32_t rowCount = 0, colCount = 0;
  253. hlsl::GetHLSLMatRowColCount(matrixType, rowCount, colCount);
  254. const QualType elemType = hlsl::GetHLSLMatElementType(matrixType);
  255. // Same as the vector case, first try to see if we already have a matrix at
  256. // the beginning of the initializer queue.
  257. if (scalars.empty()) {
  258. // Keep splitting structs or arrays
  259. while (tryToSplitStruct() || tryToSplitConstantArray())
  260. ;
  261. auto init = initializers.back();
  262. if (hlsl::IsHLSLMatType(init->getAstResultType())) {
  263. uint32_t initRowCount = 0, initColCount = 0;
  264. hlsl::GetHLSLMatRowColCount(init->getAstResultType(), initRowCount,
  265. initColCount);
  266. if (rowCount == initRowCount && colCount == initColCount) {
  267. initializers.pop_back();
  268. return theEmitter.castToType(init, init->getAstResultType(), matrixType,
  269. srcLoc);
  270. }
  271. }
  272. }
  273. if (rowCount == 1)
  274. return createInitForVectorType(elemType, colCount, srcLoc);
  275. if (colCount == 1)
  276. return createInitForVectorType(elemType, rowCount, srcLoc);
  277. llvm::SmallVector<SpirvInstruction *, 4> vectors;
  278. for (uint32_t i = 0; i < rowCount; ++i) {
  279. // All elements are vectors, which should already be casted to the correct
  280. // type if necessary.
  281. vectors.push_back(createInitForVectorType(elemType, colCount, srcLoc));
  282. }
  283. // TODO: use OpConstantComposite when all components are constants
  284. return spvBuilder.createCompositeConstruct(matrixType, vectors, srcLoc);
  285. }
  286. SpirvInstruction *
  287. InitListHandler::createInitForStructType(QualType type, SourceLocation srcLoc) {
  288. assert(type->isStructureType() && !isSampler(type));
  289. // Same as the vector case, first try to see if we already have a struct at
  290. // the beginning of the initializer queue.
  291. if (scalars.empty()) {
  292. // Keep splitting arrays
  293. while (tryToSplitConstantArray())
  294. ;
  295. auto init = initializers.back();
  296. // We can only avoid decomposing and reconstructing when the type is
  297. // exactly the same.
  298. if (type.getCanonicalType() ==
  299. init->getAstResultType().getCanonicalType()) {
  300. initializers.pop_back();
  301. return init;
  302. }
  303. // Otherwise, if the next initializer is a struct, it is not of the same
  304. // type as we expected. Split it. Just need to do one iteration since a
  305. // field in the next struct initializer may be of the same struct type as
  306. // a field we are about the construct.
  307. tryToSplitStruct();
  308. }
  309. llvm::SmallVector<SpirvInstruction *, 4> fields;
  310. const RecordDecl *structDecl = type->getAsStructureType()->getDecl();
  311. for (const auto *field : structDecl->fields()) {
  312. fields.push_back(createInitForType(field->getType(), field->getLocation()));
  313. if (!fields.back())
  314. return nullptr;
  315. }
  316. // TODO: use OpConstantComposite when all components are constants
  317. return spvBuilder.createCompositeConstruct(type, fields, srcLoc);
  318. }
  319. SpirvInstruction *
  320. InitListHandler::createInitForConstantArrayType(QualType type,
  321. SourceLocation srcLoc) {
  322. assert(type->isConstantArrayType());
  323. // Same as the vector case, first try to see if we already have an array at
  324. // the beginning of the initializer queue.
  325. if (scalars.empty()) {
  326. // Keep splitting structs
  327. while (tryToSplitStruct())
  328. ;
  329. auto init = initializers.back();
  330. // We can only avoid decomposing and reconstructing when the type is
  331. // exactly the same.
  332. if (type.getCanonicalType() ==
  333. init->getAstResultType().getCanonicalType()) {
  334. initializers.pop_back();
  335. return init;
  336. }
  337. // Otherwise, if the next initializer is an array, it is not of the same
  338. // type as we expected. Split it. Just need to do one iteration since the
  339. // next array initializer may have the same element type as the one we
  340. // are about to construct but with different size.
  341. tryToSplitConstantArray();
  342. }
  343. const auto *arrType = theEmitter.getASTContext().getAsConstantArrayType(type);
  344. const auto elemType = arrType->getElementType();
  345. // TODO: handle (unlikely) extra large array size?
  346. const auto size = static_cast<uint32_t>(arrType->getSize().getZExtValue());
  347. llvm::SmallVector<SpirvInstruction *, 4> elements;
  348. for (uint32_t i = 0; i < size; ++i)
  349. elements.push_back(createInitForType(elemType, srcLoc));
  350. // TODO: use OpConstantComposite when all components are constants
  351. return spvBuilder.createCompositeConstruct(type, elements, srcLoc);
  352. }
  353. SpirvInstruction *
  354. InitListHandler::createInitForBufferOrImageType(QualType type,
  355. SourceLocation srcLoc) {
  356. assert(isOpaqueType(type) || isAKindOfStructuredOrByteBuffer(type));
  357. // Samplers, (RW)Buffers, and (RW)Textures are translated into OpTypeSampler
  358. // and OpTypeImage. They should be treated similar as builtin types.
  359. if (!scalars.empty()) {
  360. const auto init = scalars.front();
  361. scalars.pop_front();
  362. // Require exact type match between the initializer and the target component
  363. if (init.second.getCanonicalType() != type.getCanonicalType()) {
  364. emitError("cannot cast initializer type %0 into variable type %1", srcLoc)
  365. << init.second << type;
  366. return nullptr;
  367. }
  368. return init.first;
  369. }
  370. // Keep splitting structs or arrays
  371. while (tryToSplitStruct() || tryToSplitConstantArray())
  372. ;
  373. auto init = initializers.back();
  374. initializers.pop_back();
  375. if (init->getAstResultType().getCanonicalType() != type.getCanonicalType()) {
  376. emitError("Cannot cast initializer type %0 into variable type %1", srcLoc)
  377. << init->getAstResultType() << type;
  378. return nullptr;
  379. }
  380. return init;
  381. }
  382. } // end namespace spirv
  383. } // end namespace clang