InitListHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. return createInitForMatrixType(type, srcLoc);
  166. }
  167. // Samplers, (RW)Buffers, (RW)Textures
  168. // It is important that this happens before checking of structure types.
  169. if (TypeTranslator::isOpaqueType(type))
  170. return createInitForSamplerImageType(type, srcLoc);
  171. // This should happen before the check for normal struct types
  172. if (TypeTranslator::isAKindOfStructuredOrByteBuffer(type)) {
  173. emitError("cannot handle structured/byte buffer as initializer", srcLoc);
  174. return 0;
  175. }
  176. if (type->isStructureType())
  177. return createInitForStructType(type);
  178. if (type->isConstantArrayType())
  179. return createInitForConstantArrayType(type, srcLoc);
  180. emitError("initializer for type %0 unimplemented", srcLoc) << type;
  181. return 0;
  182. }
  183. uint32_t InitListHandler::createInitForBuiltinType(QualType type,
  184. SourceLocation srcLoc) {
  185. assert(type->isBuiltinType());
  186. if (!scalars.empty()) {
  187. const auto init = scalars.front();
  188. scalars.pop_front();
  189. return theEmitter.castToType(init.first, init.second, type, srcLoc);
  190. }
  191. // Keep splitting structs or arrays
  192. while (tryToSplitStruct() || tryToSplitConstantArray())
  193. ;
  194. const Expr *init = initializers.back();
  195. initializers.pop_back();
  196. if (!init->getType()->isBuiltinType()) {
  197. decompose(init);
  198. return createInitForBuiltinType(type, srcLoc);
  199. }
  200. const uint32_t value = theEmitter.loadIfGLValue(init);
  201. return theEmitter.castToType(value, init->getType(), type, srcLoc);
  202. }
  203. uint32_t InitListHandler::createInitForVectorType(QualType elemType,
  204. uint32_t count,
  205. SourceLocation srcLoc) {
  206. // If we don't have leftover scalars, we can try to see if there is a vector
  207. // of the same size in the original initializer list so that we can use it
  208. // directly. For all other cases, we need to construct a new vector as the
  209. // initializer.
  210. if (scalars.empty()) {
  211. // Keep splitting structs or arrays
  212. while (tryToSplitStruct() || tryToSplitConstantArray())
  213. ;
  214. const Expr *init = initializers.back();
  215. if (hlsl::IsHLSLVecType(init->getType()) &&
  216. hlsl::GetHLSLVecSize(init->getType()) == count) {
  217. initializers.pop_back();
  218. /// HLSL vector types are parameterized templates and we cannot
  219. /// construct them. So we construct an ExtVectorType here instead.
  220. /// This is unfortunate since it means we need to handle ExtVectorType
  221. /// in all type casting methods in SPIRVEmitter.
  222. const auto toVecType =
  223. theEmitter.getASTContext().getExtVectorType(elemType, count);
  224. return theEmitter.castToType(theEmitter.loadIfGLValue(init),
  225. init->getType(), toVecType, srcLoc);
  226. }
  227. }
  228. if (count == 1)
  229. return createInitForBuiltinType(elemType, srcLoc);
  230. llvm::SmallVector<uint32_t, 4> elements;
  231. for (uint32_t i = 0; i < count; ++i) {
  232. // All elements are scalars, which should already be casted to the correct
  233. // type if necessary.
  234. elements.push_back(createInitForBuiltinType(elemType, srcLoc));
  235. }
  236. const uint32_t elemTypeId = typeTranslator.translateType(elemType);
  237. const uint32_t vecType = theBuilder.getVecType(elemTypeId, count);
  238. // TODO: use OpConstantComposite when all components are constants
  239. return theBuilder.createCompositeConstruct(vecType, elements);
  240. }
  241. uint32_t InitListHandler::createInitForMatrixType(QualType matrixType,
  242. SourceLocation srcLoc) {
  243. uint32_t rowCount = 0, colCount = 0;
  244. hlsl::GetHLSLMatRowColCount(matrixType, rowCount, colCount);
  245. const QualType elemType = hlsl::GetHLSLMatElementType(matrixType);
  246. // Same as the vector case, first try to see if we already have a matrix at
  247. // the beginning of the initializer queue.
  248. if (scalars.empty()) {
  249. // Keep splitting structs or arrays
  250. while (tryToSplitStruct() || tryToSplitConstantArray())
  251. ;
  252. const Expr *init = initializers.back();
  253. if (hlsl::IsHLSLMatType(init->getType())) {
  254. uint32_t initRowCount = 0, initColCount = 0;
  255. hlsl::GetHLSLMatRowColCount(init->getType(), initRowCount, initColCount);
  256. if (rowCount == initRowCount && colCount == initColCount) {
  257. initializers.pop_back();
  258. // TODO: We only support FP matrices now. Do type cast here after
  259. // adding more matrix types.
  260. return theEmitter.loadIfGLValue(init);
  261. }
  262. }
  263. }
  264. if (rowCount == 1)
  265. return createInitForVectorType(elemType, colCount, srcLoc);
  266. if (colCount == 1)
  267. return createInitForVectorType(elemType, rowCount, srcLoc);
  268. llvm::SmallVector<uint32_t, 4> vectors;
  269. for (uint32_t i = 0; i < rowCount; ++i) {
  270. // All elements are vectors, which should already be casted to the correct
  271. // type if necessary.
  272. vectors.push_back(createInitForVectorType(elemType, colCount, srcLoc));
  273. }
  274. // TODO: use OpConstantComposite when all components are constants
  275. return theBuilder.createCompositeConstruct(
  276. typeTranslator.translateType(matrixType), vectors);
  277. }
  278. uint32_t InitListHandler::createInitForStructType(QualType type) {
  279. assert(type->isStructureType() && !TypeTranslator::isSampler(type));
  280. // Same as the vector case, first try to see if we already have a struct at
  281. // the beginning of the initializer queue.
  282. if (scalars.empty()) {
  283. // Keep splitting arrays
  284. while (tryToSplitConstantArray())
  285. ;
  286. const Expr *init = initializers.back();
  287. // We can only avoid decomposing and reconstructing when the type is
  288. // exactly the same.
  289. if (type.getCanonicalType() == init->getType().getCanonicalType()) {
  290. initializers.pop_back();
  291. return theEmitter.loadIfGLValue(init);
  292. }
  293. // Otherwise, if the next initializer is a struct, it is not of the same
  294. // type as we expected. Split it. Just need to do one iteration since a
  295. // field in the next struct initializer may be of the same struct type as
  296. // a field we are about the construct.
  297. tryToSplitStruct();
  298. }
  299. llvm::SmallVector<uint32_t, 4> fields;
  300. const RecordDecl *structDecl = type->getAsStructureType()->getDecl();
  301. for (const auto *field : structDecl->fields()) {
  302. fields.push_back(createInitForType(field->getType(), field->getLocation()));
  303. if (!fields.back())
  304. return 0;
  305. }
  306. const uint32_t typeId = typeTranslator.translateType(type);
  307. // TODO: use OpConstantComposite when all components are constants
  308. return theBuilder.createCompositeConstruct(typeId, fields);
  309. }
  310. uint32_t
  311. InitListHandler::createInitForConstantArrayType(QualType type,
  312. SourceLocation srcLoc) {
  313. assert(type->isConstantArrayType());
  314. // Same as the vector case, first try to see if we already have an array at
  315. // the beginning of the initializer queue.
  316. if (scalars.empty()) {
  317. // Keep splitting structs
  318. while (tryToSplitStruct())
  319. ;
  320. const Expr *init = initializers.back();
  321. // We can only avoid decomposing and reconstructing when the type is
  322. // exactly the same.
  323. if (type.getCanonicalType() == init->getType().getCanonicalType()) {
  324. initializers.pop_back();
  325. return theEmitter.loadIfGLValue(init);
  326. }
  327. // Otherwise, if the next initializer is an array, it is not of the same
  328. // type as we expected. Split it. Just need to do one iteration since the
  329. // next array initializer may have the same element type as the one we
  330. // are about to construct but with different size.
  331. tryToSplitConstantArray();
  332. }
  333. const auto *arrType = theEmitter.getASTContext().getAsConstantArrayType(type);
  334. const auto elemType = arrType->getElementType();
  335. // TODO: handle (unlikely) extra large array size?
  336. const auto size = static_cast<uint32_t>(arrType->getSize().getZExtValue());
  337. llvm::SmallVector<uint32_t, 4> elements;
  338. for (uint32_t i = 0; i < size; ++i)
  339. elements.push_back(createInitForType(elemType, srcLoc));
  340. const uint32_t typeId = typeTranslator.translateType(type);
  341. // TODO: use OpConstantComposite when all components are constants
  342. return theBuilder.createCompositeConstruct(typeId, elements);
  343. }
  344. uint32_t InitListHandler::createInitForSamplerImageType(QualType type,
  345. SourceLocation srcLoc) {
  346. assert(TypeTranslator::isOpaqueType(type));
  347. // Samplers, (RW)Buffers, and (RW)Textures are translated into OpTypeSampler
  348. // and OpTypeImage. They should be treated similar as builtin types.
  349. if (!scalars.empty()) {
  350. const auto init = scalars.front();
  351. scalars.pop_front();
  352. // Require exact type match between the initializer and the target component
  353. if (init.second.getCanonicalType() != type.getCanonicalType()) {
  354. emitError("cannot cast initializer type %0 into variable type %1", srcLoc)
  355. << init.second << type;
  356. return 0;
  357. }
  358. return init.first;
  359. }
  360. // Keep splitting structs or arrays
  361. while (tryToSplitStruct() || tryToSplitConstantArray())
  362. ;
  363. const Expr *init = initializers.back();
  364. initializers.pop_back();
  365. if (init->getType().getCanonicalType() != type.getCanonicalType()) {
  366. init->dump();
  367. emitError("cannot cast initializer type %0 into variable type %1",
  368. init->getLocStart())
  369. << init->getType() << type;
  370. return 0;
  371. }
  372. return theEmitter.loadIfGLValue(init);
  373. }
  374. } // end namespace spirv
  375. } // end namespace clang