ModuleBuilder.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. //===--- ModuleBuilder.cpp - SPIR-V builder implementation ----*- 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. #include "clang/SPIRV/ModuleBuilder.h"
  10. #include "TypeTranslator.h"
  11. #include "spirv/unified1//spirv.hpp11"
  12. #include "clang/SPIRV/BitwiseCast.h"
  13. #include "clang/SPIRV/InstBuilder.h"
  14. #include "llvm/llvm_assert/assert.h"
  15. namespace clang {
  16. namespace spirv {
  17. ModuleBuilder::ModuleBuilder(SPIRVContext *C, FeatureManager *features,
  18. bool reflect)
  19. : theContext(*C), featureManager(features), allowReflect(reflect),
  20. theModule(), theFunction(nullptr), insertPoint(nullptr),
  21. instBuilder(nullptr), glslExtSetId(0) {
  22. instBuilder.setConsumer([this](std::vector<uint32_t> &&words) {
  23. this->constructSite = std::move(words);
  24. });
  25. // Set the SPIR-V version if needed.
  26. if (featureManager && featureManager->getTargetEnv() == SPV_ENV_VULKAN_1_1)
  27. theModule.setVersion(0x00010300);
  28. }
  29. std::vector<uint32_t> ModuleBuilder::takeModule() {
  30. theModule.setBound(theContext.getNextId());
  31. std::vector<uint32_t> binary;
  32. auto ib = InstBuilder([&binary](std::vector<uint32_t> &&words) {
  33. binary.insert(binary.end(), words.begin(), words.end());
  34. });
  35. theModule.take(&ib);
  36. return binary;
  37. }
  38. uint32_t ModuleBuilder::beginFunction(uint32_t funcType, uint32_t returnType,
  39. llvm::StringRef funcName, uint32_t fId) {
  40. if (theFunction) {
  41. assert(false && "found nested function");
  42. return 0;
  43. }
  44. // If the caller doesn't supply a function <result-id>, we need to get one.
  45. if (!fId)
  46. fId = theContext.takeNextId();
  47. theFunction = llvm::make_unique<Function>(
  48. returnType, fId, spv::FunctionControlMask::MaskNone, funcType);
  49. theModule.addDebugName(fId, funcName);
  50. return fId;
  51. }
  52. uint32_t ModuleBuilder::addFnParam(uint32_t ptrType, llvm::StringRef name) {
  53. assert(theFunction && "found detached parameter");
  54. const uint32_t paramId = theContext.takeNextId();
  55. theFunction->addParameter(ptrType, paramId);
  56. theModule.addDebugName(paramId, name);
  57. return paramId;
  58. }
  59. uint32_t ModuleBuilder::addFnVar(uint32_t varType, llvm::StringRef name,
  60. llvm::Optional<uint32_t> init) {
  61. assert(theFunction && "found detached local variable");
  62. const uint32_t ptrType = getPointerType(varType, spv::StorageClass::Function);
  63. const uint32_t varId = theContext.takeNextId();
  64. theFunction->addVariable(ptrType, varId, init);
  65. theModule.addDebugName(varId, name);
  66. return varId;
  67. }
  68. bool ModuleBuilder::endFunction() {
  69. if (theFunction == nullptr) {
  70. assert(false && "no active function");
  71. return false;
  72. }
  73. // Move all basic blocks into the current function.
  74. // TODO: we should adjust the order the basic blocks according to
  75. // SPIR-V validation rules.
  76. for (auto &bb : basicBlocks) {
  77. theFunction->addBasicBlock(std::move(bb.second));
  78. }
  79. basicBlocks.clear();
  80. theModule.addFunction(std::move(theFunction));
  81. theFunction.reset(nullptr);
  82. insertPoint = nullptr;
  83. return true;
  84. }
  85. uint32_t ModuleBuilder::createBasicBlock(llvm::StringRef name) {
  86. if (theFunction == nullptr) {
  87. assert(false && "found detached basic block");
  88. return 0;
  89. }
  90. const uint32_t labelId = theContext.takeNextId();
  91. basicBlocks[labelId] = llvm::make_unique<BasicBlock>(labelId, name);
  92. return labelId;
  93. }
  94. void ModuleBuilder::addSuccessor(uint32_t successorLabel) {
  95. assert(insertPoint && "null insert point");
  96. insertPoint->addSuccessor(getBasicBlock(successorLabel));
  97. }
  98. void ModuleBuilder::setMergeTarget(uint32_t mergeLabel) {
  99. assert(insertPoint && "null insert point");
  100. insertPoint->setMergeTarget(getBasicBlock(mergeLabel));
  101. }
  102. void ModuleBuilder::setContinueTarget(uint32_t continueLabel) {
  103. assert(insertPoint && "null insert point");
  104. insertPoint->setContinueTarget(getBasicBlock(continueLabel));
  105. }
  106. void ModuleBuilder::setInsertPoint(uint32_t labelId) {
  107. insertPoint = getBasicBlock(labelId);
  108. }
  109. uint32_t
  110. ModuleBuilder::createCompositeConstruct(uint32_t resultType,
  111. llvm::ArrayRef<uint32_t> constituents) {
  112. assert(insertPoint && "null insert point");
  113. const uint32_t resultId = theContext.takeNextId();
  114. instBuilder.opCompositeConstruct(resultType, resultId, constituents).x();
  115. insertPoint->appendInstruction(std::move(constructSite));
  116. return resultId;
  117. }
  118. uint32_t
  119. ModuleBuilder::createCompositeExtract(uint32_t resultType, uint32_t composite,
  120. llvm::ArrayRef<uint32_t> indexes) {
  121. assert(insertPoint && "null insert point");
  122. const uint32_t resultId = theContext.takeNextId();
  123. instBuilder.opCompositeExtract(resultType, resultId, composite, indexes).x();
  124. insertPoint->appendInstruction(std::move(constructSite));
  125. return resultId;
  126. }
  127. uint32_t ModuleBuilder::createCompositeInsert(uint32_t resultType,
  128. uint32_t composite,
  129. llvm::ArrayRef<uint32_t> indices,
  130. uint32_t object) {
  131. assert(insertPoint && "null insert point");
  132. const uint32_t resultId = theContext.takeNextId();
  133. instBuilder
  134. .opCompositeInsert(resultType, resultId, object, composite, indices)
  135. .x();
  136. insertPoint->appendInstruction(std::move(constructSite));
  137. return resultId;
  138. }
  139. uint32_t
  140. ModuleBuilder::createVectorShuffle(uint32_t resultType, uint32_t vector1,
  141. uint32_t vector2,
  142. llvm::ArrayRef<uint32_t> selectors) {
  143. assert(insertPoint && "null insert point");
  144. const uint32_t resultId = theContext.takeNextId();
  145. instBuilder.opVectorShuffle(resultType, resultId, vector1, vector2, selectors)
  146. .x();
  147. insertPoint->appendInstruction(std::move(constructSite));
  148. return resultId;
  149. }
  150. uint32_t ModuleBuilder::createLoad(uint32_t resultType, uint32_t pointer) {
  151. assert(insertPoint && "null insert point");
  152. const uint32_t resultId = theContext.takeNextId();
  153. instBuilder.opLoad(resultType, resultId, pointer, llvm::None).x();
  154. insertPoint->appendInstruction(std::move(constructSite));
  155. return resultId;
  156. }
  157. void ModuleBuilder::createStore(uint32_t address, uint32_t value) {
  158. assert(insertPoint && "null insert point");
  159. instBuilder.opStore(address, value, llvm::None).x();
  160. insertPoint->appendInstruction(std::move(constructSite));
  161. }
  162. uint32_t ModuleBuilder::createFunctionCall(uint32_t returnType,
  163. uint32_t functionId,
  164. llvm::ArrayRef<uint32_t> params) {
  165. assert(insertPoint && "null insert point");
  166. const uint32_t id = theContext.takeNextId();
  167. instBuilder.opFunctionCall(returnType, id, functionId, params).x();
  168. insertPoint->appendInstruction(std::move(constructSite));
  169. return id;
  170. }
  171. uint32_t ModuleBuilder::createAccessChain(uint32_t resultType, uint32_t base,
  172. llvm::ArrayRef<uint32_t> indexes) {
  173. assert(insertPoint && "null insert point");
  174. const uint32_t id = theContext.takeNextId();
  175. instBuilder.opAccessChain(resultType, id, base, indexes).x();
  176. insertPoint->appendInstruction(std::move(constructSite));
  177. return id;
  178. }
  179. uint32_t ModuleBuilder::createUnaryOp(spv::Op op, uint32_t resultType,
  180. uint32_t operand) {
  181. assert(insertPoint && "null insert point");
  182. const uint32_t id = theContext.takeNextId();
  183. instBuilder.unaryOp(op, resultType, id, operand).x();
  184. insertPoint->appendInstruction(std::move(constructSite));
  185. switch (op) {
  186. case spv::Op::OpImageQuerySize:
  187. case spv::Op::OpImageQueryLevels:
  188. case spv::Op::OpImageQuerySamples:
  189. requireCapability(spv::Capability::ImageQuery);
  190. break;
  191. }
  192. return id;
  193. }
  194. uint32_t ModuleBuilder::createBinaryOp(spv::Op op, uint32_t resultType,
  195. uint32_t lhs, uint32_t rhs) {
  196. assert(insertPoint && "null insert point");
  197. const uint32_t id = theContext.takeNextId();
  198. instBuilder.binaryOp(op, resultType, id, lhs, rhs).x();
  199. insertPoint->appendInstruction(std::move(constructSite));
  200. switch (op) {
  201. case spv::Op::OpImageQueryLod:
  202. case spv::Op::OpImageQuerySizeLod:
  203. requireCapability(spv::Capability::ImageQuery);
  204. break;
  205. }
  206. return id;
  207. }
  208. uint32_t ModuleBuilder::createSpecConstantBinaryOp(spv::Op op,
  209. uint32_t resultType,
  210. uint32_t lhs, uint32_t rhs) {
  211. const uint32_t id = theContext.takeNextId();
  212. instBuilder.specConstantBinaryOp(op, resultType, id, lhs, rhs).x();
  213. theModule.addVariable(std::move(constructSite));
  214. return id;
  215. }
  216. uint32_t ModuleBuilder::createGroupNonUniformOp(spv::Op op, uint32_t resultType,
  217. uint32_t execScope) {
  218. assert(insertPoint && "null insert point");
  219. const uint32_t id = theContext.takeNextId();
  220. instBuilder.groupNonUniformOp(op, resultType, id, execScope).x();
  221. insertPoint->appendInstruction(std::move(constructSite));
  222. return id;
  223. }
  224. uint32_t ModuleBuilder::createGroupNonUniformUnaryOp(
  225. spv::Op op, uint32_t resultType, uint32_t execScope, uint32_t operand,
  226. llvm::Optional<spv::GroupOperation> groupOp) {
  227. assert(insertPoint && "null insert point");
  228. const uint32_t id = theContext.takeNextId();
  229. instBuilder
  230. .groupNonUniformUnaryOp(op, resultType, id, execScope, groupOp, operand)
  231. .x();
  232. insertPoint->appendInstruction(std::move(constructSite));
  233. return id;
  234. }
  235. uint32_t ModuleBuilder::createGroupNonUniformBinaryOp(spv::Op op,
  236. uint32_t resultType,
  237. uint32_t execScope,
  238. uint32_t operand1,
  239. uint32_t operand2) {
  240. assert(insertPoint && "null insert point");
  241. const uint32_t id = theContext.takeNextId();
  242. instBuilder
  243. .groupNonUniformBinaryOp(op, resultType, id, execScope, operand1,
  244. operand2)
  245. .x();
  246. insertPoint->appendInstruction(std::move(constructSite));
  247. return id;
  248. }
  249. uint32_t ModuleBuilder::createAtomicOp(spv::Op opcode, uint32_t resultType,
  250. uint32_t orignalValuePtr,
  251. uint32_t scopeId,
  252. uint32_t memorySemanticsId,
  253. uint32_t valueToOp) {
  254. assert(insertPoint && "null insert point");
  255. const uint32_t id = theContext.takeNextId();
  256. switch (opcode) {
  257. case spv::Op::OpAtomicIAdd:
  258. instBuilder.opAtomicIAdd(resultType, id, orignalValuePtr, scopeId,
  259. memorySemanticsId, valueToOp);
  260. break;
  261. case spv::Op::OpAtomicISub:
  262. instBuilder.opAtomicISub(resultType, id, orignalValuePtr, scopeId,
  263. memorySemanticsId, valueToOp);
  264. break;
  265. case spv::Op::OpAtomicAnd:
  266. instBuilder.opAtomicAnd(resultType, id, orignalValuePtr, scopeId,
  267. memorySemanticsId, valueToOp);
  268. break;
  269. case spv::Op::OpAtomicOr:
  270. instBuilder.opAtomicOr(resultType, id, orignalValuePtr, scopeId,
  271. memorySemanticsId, valueToOp);
  272. break;
  273. case spv::Op::OpAtomicXor:
  274. instBuilder.opAtomicXor(resultType, id, orignalValuePtr, scopeId,
  275. memorySemanticsId, valueToOp);
  276. break;
  277. case spv::Op::OpAtomicUMax:
  278. instBuilder.opAtomicUMax(resultType, id, orignalValuePtr, scopeId,
  279. memorySemanticsId, valueToOp);
  280. break;
  281. case spv::Op::OpAtomicUMin:
  282. instBuilder.opAtomicUMin(resultType, id, orignalValuePtr, scopeId,
  283. memorySemanticsId, valueToOp);
  284. break;
  285. case spv::Op::OpAtomicSMax:
  286. instBuilder.opAtomicSMax(resultType, id, orignalValuePtr, scopeId,
  287. memorySemanticsId, valueToOp);
  288. break;
  289. case spv::Op::OpAtomicSMin:
  290. instBuilder.opAtomicSMin(resultType, id, orignalValuePtr, scopeId,
  291. memorySemanticsId, valueToOp);
  292. break;
  293. case spv::Op::OpAtomicExchange:
  294. instBuilder.opAtomicExchange(resultType, id, orignalValuePtr, scopeId,
  295. memorySemanticsId, valueToOp);
  296. break;
  297. default:
  298. assert(false && "unimplemented atomic opcode");
  299. }
  300. instBuilder.x();
  301. insertPoint->appendInstruction(std::move(constructSite));
  302. return id;
  303. }
  304. uint32_t ModuleBuilder::createAtomicCompareExchange(
  305. uint32_t resultType, uint32_t orignalValuePtr, uint32_t scopeId,
  306. uint32_t equalMemorySemanticsId, uint32_t unequalMemorySemanticsId,
  307. uint32_t valueToOp, uint32_t comparator) {
  308. assert(insertPoint && "null insert point");
  309. const uint32_t id = theContext.takeNextId();
  310. instBuilder.opAtomicCompareExchange(
  311. resultType, id, orignalValuePtr, scopeId, equalMemorySemanticsId,
  312. unequalMemorySemanticsId, valueToOp, comparator);
  313. instBuilder.x();
  314. insertPoint->appendInstruction(std::move(constructSite));
  315. return id;
  316. }
  317. spv::ImageOperandsMask ModuleBuilder::composeImageOperandsMask(
  318. uint32_t bias, uint32_t lod, const std::pair<uint32_t, uint32_t> &grad,
  319. uint32_t constOffset, uint32_t varOffset, uint32_t constOffsets,
  320. uint32_t sample, uint32_t minLod,
  321. llvm::SmallVectorImpl<uint32_t> *orderedParams) {
  322. using spv::ImageOperandsMask;
  323. // SPIR-V Image Operands from least significant bit to most significant bit
  324. // Bias, Lod, Grad, ConstOffset, Offset, ConstOffsets, Sample, MinLod
  325. auto mask = ImageOperandsMask::MaskNone;
  326. orderedParams->clear();
  327. if (bias) {
  328. mask = mask | ImageOperandsMask::Bias;
  329. orderedParams->push_back(bias);
  330. }
  331. if (lod) {
  332. mask = mask | ImageOperandsMask::Lod;
  333. orderedParams->push_back(lod);
  334. }
  335. if (grad.first && grad.second) {
  336. mask = mask | ImageOperandsMask::Grad;
  337. orderedParams->push_back(grad.first);
  338. orderedParams->push_back(grad.second);
  339. }
  340. if (constOffset) {
  341. mask = mask | ImageOperandsMask::ConstOffset;
  342. orderedParams->push_back(constOffset);
  343. }
  344. if (varOffset) {
  345. mask = mask | ImageOperandsMask::Offset;
  346. requireCapability(spv::Capability::ImageGatherExtended);
  347. orderedParams->push_back(varOffset);
  348. }
  349. if (constOffsets) {
  350. mask = mask | ImageOperandsMask::ConstOffsets;
  351. orderedParams->push_back(constOffsets);
  352. }
  353. if (sample) {
  354. mask = mask | ImageOperandsMask::Sample;
  355. orderedParams->push_back(sample);
  356. }
  357. if (minLod) {
  358. requireCapability(spv::Capability::MinLod);
  359. mask = mask | ImageOperandsMask::MinLod;
  360. orderedParams->push_back(minLod);
  361. }
  362. return mask;
  363. }
  364. uint32_t
  365. ModuleBuilder::createImageSparseTexelsResident(uint32_t resident_code) {
  366. assert(insertPoint && "null insert point");
  367. // Result type must be a boolean
  368. const uint32_t result_type = getBoolType();
  369. const uint32_t id = theContext.takeNextId();
  370. instBuilder.opImageSparseTexelsResident(result_type, id, resident_code).x();
  371. insertPoint->appendInstruction(std::move(constructSite));
  372. return id;
  373. }
  374. uint32_t ModuleBuilder::createImageTexelPointer(uint32_t resultType,
  375. uint32_t imageId,
  376. uint32_t coordinate,
  377. uint32_t sample) {
  378. assert(insertPoint && "null insert point");
  379. const uint32_t id = theContext.takeNextId();
  380. instBuilder.opImageTexelPointer(resultType, id, imageId, coordinate, sample)
  381. .x();
  382. insertPoint->appendInstruction(std::move(constructSite));
  383. return id;
  384. }
  385. uint32_t ModuleBuilder::createImageSample(
  386. uint32_t texelType, uint32_t imageType, uint32_t image, uint32_t sampler,
  387. uint32_t coordinate, uint32_t compareVal, uint32_t bias, uint32_t lod,
  388. std::pair<uint32_t, uint32_t> grad, uint32_t constOffset,
  389. uint32_t varOffset, uint32_t constOffsets, uint32_t sample, uint32_t minLod,
  390. uint32_t residencyCodeId) {
  391. assert(insertPoint && "null insert point");
  392. // The Lod and Grad image operands requires explicit-lod instructions.
  393. // Otherwise we use implicit-lod instructions.
  394. const bool isExplicit = lod || (grad.first && grad.second);
  395. const bool isSparse = (residencyCodeId != 0);
  396. // minLod is only valid with Implicit instructions and Grad instructions.
  397. // This means that we cannot have Lod and minLod together because Lod requires
  398. // explicit insturctions. So either lod or minLod or both must be zero.
  399. assert(lod == 0 || minLod == 0);
  400. uint32_t retType = texelType;
  401. if (isSparse) {
  402. requireCapability(spv::Capability::SparseResidency);
  403. retType = getSparseResidencyStructType(texelType);
  404. }
  405. // An OpSampledImage is required to do the image sampling.
  406. const uint32_t sampledImgId = theContext.takeNextId();
  407. const uint32_t sampledImgTy = getSampledImageType(imageType);
  408. instBuilder.opSampledImage(sampledImgTy, sampledImgId, image, sampler).x();
  409. insertPoint->appendInstruction(std::move(constructSite));
  410. uint32_t texelId = theContext.takeNextId();
  411. llvm::SmallVector<uint32_t, 4> params;
  412. const auto mask =
  413. composeImageOperandsMask(bias, lod, grad, constOffset, varOffset,
  414. constOffsets, sample, minLod, &params);
  415. instBuilder.opImageSample(retType, texelId, sampledImgId, coordinate,
  416. compareVal, mask, isExplicit, isSparse);
  417. for (const auto param : params)
  418. instBuilder.idRef(param);
  419. instBuilder.x();
  420. insertPoint->appendInstruction(std::move(constructSite));
  421. if (isSparse) {
  422. // Write the Residency Code
  423. const auto status = createCompositeExtract(getUint32Type(), texelId, {0});
  424. createStore(residencyCodeId, status);
  425. // Extract the real result from the struct
  426. texelId = createCompositeExtract(texelType, texelId, {1});
  427. }
  428. return texelId;
  429. }
  430. void ModuleBuilder::createImageWrite(QualType imageType, uint32_t imageId,
  431. uint32_t coordId, uint32_t texelId) {
  432. assert(insertPoint && "null insert point");
  433. requireCapability(
  434. TypeTranslator::getCapabilityForStorageImageReadWrite(imageType));
  435. instBuilder.opImageWrite(imageId, coordId, texelId, llvm::None).x();
  436. insertPoint->appendInstruction(std::move(constructSite));
  437. }
  438. uint32_t ModuleBuilder::createImageFetchOrRead(
  439. bool doImageFetch, uint32_t texelType, QualType imageType, uint32_t image,
  440. uint32_t coordinate, uint32_t lod, uint32_t constOffset, uint32_t varOffset,
  441. uint32_t constOffsets, uint32_t sample, uint32_t residencyCodeId) {
  442. assert(insertPoint && "null insert point");
  443. llvm::SmallVector<uint32_t, 2> params;
  444. const auto mask =
  445. llvm::Optional<spv::ImageOperandsMask>(composeImageOperandsMask(
  446. /*bias*/ 0, lod, std::make_pair(0, 0), constOffset, varOffset,
  447. constOffsets, sample, /*minLod*/ 0, &params));
  448. const bool isSparse = (residencyCodeId != 0);
  449. uint32_t retType = texelType;
  450. if (isSparse) {
  451. requireCapability(spv::Capability::SparseResidency);
  452. retType = getSparseResidencyStructType(texelType);
  453. }
  454. if (!doImageFetch) {
  455. requireCapability(
  456. TypeTranslator::getCapabilityForStorageImageReadWrite(imageType));
  457. }
  458. uint32_t texelId = theContext.takeNextId();
  459. instBuilder.opImageFetchRead(retType, texelId, image, coordinate, mask,
  460. doImageFetch, isSparse);
  461. for (const auto param : params)
  462. instBuilder.idRef(param);
  463. instBuilder.x();
  464. insertPoint->appendInstruction(std::move(constructSite));
  465. if (isSparse) {
  466. // Write the Residency Code
  467. const auto status = createCompositeExtract(getUint32Type(), texelId, {0});
  468. createStore(residencyCodeId, status);
  469. // Extract the real result from the struct
  470. texelId = createCompositeExtract(texelType, texelId, {1});
  471. }
  472. return texelId;
  473. }
  474. uint32_t ModuleBuilder::createImageGather(
  475. uint32_t texelType, uint32_t imageType, uint32_t image, uint32_t sampler,
  476. uint32_t coordinate, uint32_t component, uint32_t compareVal,
  477. uint32_t constOffset, uint32_t varOffset, uint32_t constOffsets,
  478. uint32_t sample, uint32_t residencyCodeId) {
  479. assert(insertPoint && "null insert point");
  480. uint32_t sparseRetType = 0;
  481. if (residencyCodeId) {
  482. requireCapability(spv::Capability::SparseResidency);
  483. sparseRetType = getSparseResidencyStructType(texelType);
  484. }
  485. // An OpSampledImage is required to do the image sampling.
  486. const uint32_t sampledImgId = theContext.takeNextId();
  487. const uint32_t sampledImgTy = getSampledImageType(imageType);
  488. instBuilder.opSampledImage(sampledImgTy, sampledImgId, image, sampler).x();
  489. insertPoint->appendInstruction(std::move(constructSite));
  490. llvm::SmallVector<uint32_t, 2> params;
  491. // TODO: Update ImageGather to accept minLod if necessary.
  492. const auto mask =
  493. llvm::Optional<spv::ImageOperandsMask>(composeImageOperandsMask(
  494. /*bias*/ 0, /*lod*/ 0, std::make_pair(0, 0), constOffset, varOffset,
  495. constOffsets, sample, /*minLod*/ 0, &params));
  496. uint32_t texelId = theContext.takeNextId();
  497. if (compareVal) {
  498. if (residencyCodeId) {
  499. // Note: OpImageSparseDrefGather does not take the component parameter.
  500. instBuilder.opImageSparseDrefGather(sparseRetType, texelId, sampledImgId,
  501. coordinate, compareVal, mask);
  502. } else {
  503. // Note: OpImageDrefGather does not take the component parameter.
  504. instBuilder.opImageDrefGather(texelType, texelId, sampledImgId,
  505. coordinate, compareVal, mask);
  506. }
  507. } else {
  508. if (residencyCodeId) {
  509. instBuilder.opImageSparseGather(sparseRetType, texelId, sampledImgId,
  510. coordinate, component, mask);
  511. } else {
  512. instBuilder.opImageGather(texelType, texelId, sampledImgId, coordinate,
  513. component, mask);
  514. }
  515. }
  516. for (const auto param : params)
  517. instBuilder.idRef(param);
  518. instBuilder.x();
  519. insertPoint->appendInstruction(std::move(constructSite));
  520. if (residencyCodeId) {
  521. // Write the Residency Code
  522. const auto status = createCompositeExtract(getUint32Type(), texelId, {0});
  523. createStore(residencyCodeId, status);
  524. // Extract the real result from the struct
  525. texelId = createCompositeExtract(texelType, texelId, {1});
  526. }
  527. return texelId;
  528. }
  529. uint32_t ModuleBuilder::createSelect(uint32_t resultType, uint32_t condition,
  530. uint32_t trueValue, uint32_t falseValue) {
  531. assert(insertPoint && "null insert point");
  532. const uint32_t id = theContext.takeNextId();
  533. instBuilder.opSelect(resultType, id, condition, trueValue, falseValue).x();
  534. insertPoint->appendInstruction(std::move(constructSite));
  535. return id;
  536. }
  537. void ModuleBuilder::createSwitch(
  538. uint32_t mergeLabel, uint32_t selector, uint32_t defaultLabel,
  539. llvm::ArrayRef<std::pair<uint32_t, uint32_t>> target) {
  540. assert(insertPoint && "null insert point");
  541. // Create the OpSelectioMerege.
  542. instBuilder.opSelectionMerge(mergeLabel, spv::SelectionControlMask::MaskNone)
  543. .x();
  544. insertPoint->appendInstruction(std::move(constructSite));
  545. // Create the OpSwitch.
  546. instBuilder.opSwitch(selector, defaultLabel, target).x();
  547. insertPoint->appendInstruction(std::move(constructSite));
  548. }
  549. void ModuleBuilder::createKill() {
  550. assert(insertPoint && "null insert point");
  551. assert(!isCurrentBasicBlockTerminated());
  552. instBuilder.opKill().x();
  553. insertPoint->appendInstruction(std::move(constructSite));
  554. }
  555. void ModuleBuilder::createBranch(uint32_t targetLabel, uint32_t mergeBB,
  556. uint32_t continueBB,
  557. spv::LoopControlMask loopControl) {
  558. assert(insertPoint && "null insert point");
  559. if (mergeBB && continueBB) {
  560. instBuilder.opLoopMerge(mergeBB, continueBB, loopControl).x();
  561. insertPoint->appendInstruction(std::move(constructSite));
  562. }
  563. instBuilder.opBranch(targetLabel).x();
  564. insertPoint->appendInstruction(std::move(constructSite));
  565. }
  566. void ModuleBuilder::createConditionalBranch(
  567. uint32_t condition, uint32_t trueLabel, uint32_t falseLabel,
  568. uint32_t mergeLabel, uint32_t continueLabel,
  569. spv::SelectionControlMask selectionControl,
  570. spv::LoopControlMask loopControl) {
  571. assert(insertPoint && "null insert point");
  572. if (mergeLabel) {
  573. if (continueLabel) {
  574. instBuilder.opLoopMerge(mergeLabel, continueLabel, loopControl).x();
  575. insertPoint->appendInstruction(std::move(constructSite));
  576. } else {
  577. instBuilder.opSelectionMerge(mergeLabel, selectionControl).x();
  578. insertPoint->appendInstruction(std::move(constructSite));
  579. }
  580. }
  581. instBuilder.opBranchConditional(condition, trueLabel, falseLabel, {}).x();
  582. insertPoint->appendInstruction(std::move(constructSite));
  583. }
  584. void ModuleBuilder::createReturn() {
  585. assert(insertPoint && "null insert point");
  586. instBuilder.opReturn().x();
  587. insertPoint->appendInstruction(std::move(constructSite));
  588. }
  589. void ModuleBuilder::createReturnValue(uint32_t value) {
  590. assert(insertPoint && "null insert point");
  591. instBuilder.opReturnValue(value).x();
  592. insertPoint->appendInstruction(std::move(constructSite));
  593. }
  594. uint32_t ModuleBuilder::createExtInst(uint32_t resultType, uint32_t setId,
  595. uint32_t instId,
  596. llvm::ArrayRef<uint32_t> operands) {
  597. assert(insertPoint && "null insert point");
  598. uint32_t resultId = theContext.takeNextId();
  599. instBuilder.opExtInst(resultType, resultId, setId, instId, operands).x();
  600. insertPoint->appendInstruction(std::move(constructSite));
  601. return resultId;
  602. }
  603. void ModuleBuilder::createBarrier(uint32_t execution, uint32_t memory,
  604. uint32_t semantics) {
  605. assert(insertPoint && "null insert point");
  606. if (execution)
  607. instBuilder.opControlBarrier(execution, memory, semantics).x();
  608. else
  609. instBuilder.opMemoryBarrier(memory, semantics).x();
  610. insertPoint->appendInstruction(std::move(constructSite));
  611. }
  612. uint32_t ModuleBuilder::createBitFieldExtract(uint32_t resultType,
  613. uint32_t base, uint32_t offset,
  614. uint32_t count, bool isSigned) {
  615. assert(insertPoint && "null insert point");
  616. uint32_t resultId = theContext.takeNextId();
  617. if (isSigned)
  618. instBuilder.opBitFieldSExtract(resultType, resultId, base, offset, count);
  619. else
  620. instBuilder.opBitFieldUExtract(resultType, resultId, base, offset, count);
  621. instBuilder.x();
  622. insertPoint->appendInstruction(std::move(constructSite));
  623. return resultId;
  624. }
  625. uint32_t ModuleBuilder::createBitFieldInsert(uint32_t resultType, uint32_t base,
  626. uint32_t insert, uint32_t offset,
  627. uint32_t count) {
  628. assert(insertPoint && "null insert point");
  629. uint32_t resultId = theContext.takeNextId();
  630. instBuilder
  631. .opBitFieldInsert(resultType, resultId, base, insert, offset, count)
  632. .x();
  633. insertPoint->appendInstruction(std::move(constructSite));
  634. return resultId;
  635. }
  636. void ModuleBuilder::createEmitVertex() {
  637. assert(insertPoint && "null insert point");
  638. instBuilder.opEmitVertex().x();
  639. insertPoint->appendInstruction(std::move(constructSite));
  640. }
  641. void ModuleBuilder::createEndPrimitive() {
  642. assert(insertPoint && "null insert point");
  643. instBuilder.opEndPrimitive().x();
  644. insertPoint->appendInstruction(std::move(constructSite));
  645. }
  646. void ModuleBuilder::addExecutionMode(uint32_t entryPointId,
  647. spv::ExecutionMode em,
  648. llvm::ArrayRef<uint32_t> params) {
  649. instBuilder.opExecutionMode(entryPointId, em);
  650. for (const auto &param : params) {
  651. instBuilder.literalInteger(param);
  652. }
  653. instBuilder.x();
  654. theModule.addExecutionMode(std::move(constructSite));
  655. }
  656. void ModuleBuilder::addExtension(Extension ext, llvm::StringRef target,
  657. SourceLocation srcLoc) {
  658. assert(featureManager);
  659. featureManager->requestExtension(ext, target, srcLoc);
  660. // Do not emit OpExtension if the given extension is natively supported in the
  661. // target environment.
  662. if (featureManager->isExtensionRequiredForTargetEnv(ext))
  663. theModule.addExtension(featureManager->getExtensionName(ext));
  664. }
  665. uint32_t ModuleBuilder::getGLSLExtInstSet() {
  666. if (glslExtSetId == 0) {
  667. glslExtSetId = theContext.takeNextId();
  668. theModule.addExtInstSet(glslExtSetId, "GLSL.std.450");
  669. }
  670. return glslExtSetId;
  671. }
  672. uint32_t ModuleBuilder::addStageIOVar(uint32_t type,
  673. spv::StorageClass storageClass,
  674. std::string name) {
  675. const uint32_t pointerType = getPointerType(type, storageClass);
  676. const uint32_t varId = theContext.takeNextId();
  677. instBuilder.opVariable(pointerType, varId, storageClass, llvm::None).x();
  678. theModule.addVariable(std::move(constructSite));
  679. theModule.addDebugName(varId, name);
  680. return varId;
  681. }
  682. uint32_t ModuleBuilder::addStageBuiltinVar(uint32_t type, spv::StorageClass sc,
  683. spv::BuiltIn builtin) {
  684. const uint32_t pointerType = getPointerType(type, sc);
  685. const uint32_t varId = theContext.takeNextId();
  686. instBuilder.opVariable(pointerType, varId, sc, llvm::None).x();
  687. theModule.addVariable(std::move(constructSite));
  688. // Decorate with the specified Builtin
  689. const Decoration *d = Decoration::getBuiltIn(theContext, builtin);
  690. theModule.addDecoration(d, varId);
  691. return varId;
  692. }
  693. uint32_t ModuleBuilder::addModuleVar(uint32_t type, spv::StorageClass sc,
  694. llvm::StringRef name,
  695. llvm::Optional<uint32_t> init) {
  696. assert(sc != spv::StorageClass::Function);
  697. // TODO: basically duplicated code of addFileVar()
  698. const uint32_t pointerType = getPointerType(type, sc);
  699. const uint32_t varId = theContext.takeNextId();
  700. instBuilder.opVariable(pointerType, varId, sc, init).x();
  701. theModule.addVariable(std::move(constructSite));
  702. theModule.addDebugName(varId, name);
  703. return varId;
  704. }
  705. void ModuleBuilder::decorateDSetBinding(uint32_t targetId, uint32_t setNumber,
  706. uint32_t bindingNumber) {
  707. const auto *d = Decoration::getDescriptorSet(theContext, setNumber);
  708. theModule.addDecoration(d, targetId);
  709. d = Decoration::getBinding(theContext, bindingNumber);
  710. theModule.addDecoration(d, targetId);
  711. }
  712. void ModuleBuilder::decorateInputAttachmentIndex(uint32_t targetId,
  713. uint32_t indexNumber) {
  714. const auto *d = Decoration::getInputAttachmentIndex(theContext, indexNumber);
  715. theModule.addDecoration(d, targetId);
  716. }
  717. void ModuleBuilder::decorateCounterBufferId(uint32_t mainBufferId,
  718. uint32_t counterBufferId) {
  719. if (allowReflect) {
  720. addExtension(Extension::GOOGLE_hlsl_functionality1, "SPIR-V reflection",
  721. {});
  722. theModule.addDecoration(
  723. Decoration::getHlslCounterBufferGOOGLE(theContext, counterBufferId),
  724. mainBufferId);
  725. }
  726. }
  727. void ModuleBuilder::decorateHlslSemantic(uint32_t targetId,
  728. llvm::StringRef semantic,
  729. llvm::Optional<uint32_t> memberIdx) {
  730. if (allowReflect) {
  731. addExtension(Extension::GOOGLE_decorate_string, "SPIR-V reflection", {});
  732. addExtension(Extension::GOOGLE_hlsl_functionality1, "SPIR-V reflection",
  733. {});
  734. theModule.addDecoration(
  735. Decoration::getHlslSemanticGOOGLE(theContext, semantic, memberIdx),
  736. targetId);
  737. }
  738. }
  739. void ModuleBuilder::decorateLocation(uint32_t targetId, uint32_t location) {
  740. const Decoration *d =
  741. Decoration::getLocation(theContext, location, llvm::None);
  742. theModule.addDecoration(d, targetId);
  743. }
  744. void ModuleBuilder::decorateSpecId(uint32_t targetId, uint32_t specId) {
  745. const Decoration *d = Decoration::getSpecId(theContext, specId);
  746. theModule.addDecoration(d, targetId);
  747. }
  748. void ModuleBuilder::decorate(uint32_t targetId, spv::Decoration decoration) {
  749. const Decoration *d = nullptr;
  750. switch (decoration) {
  751. case spv::Decoration::Centroid:
  752. d = Decoration::getCentroid(theContext);
  753. break;
  754. case spv::Decoration::Flat:
  755. d = Decoration::getFlat(theContext);
  756. break;
  757. case spv::Decoration::NoPerspective:
  758. d = Decoration::getNoPerspective(theContext);
  759. break;
  760. case spv::Decoration::Sample:
  761. d = Decoration::getSample(theContext);
  762. break;
  763. case spv::Decoration::Block:
  764. d = Decoration::getBlock(theContext);
  765. break;
  766. case spv::Decoration::RelaxedPrecision:
  767. d = Decoration::getRelaxedPrecision(theContext);
  768. break;
  769. case spv::Decoration::Patch:
  770. d = Decoration::getPatch(theContext);
  771. break;
  772. }
  773. assert(d && "unimplemented decoration");
  774. theModule.addDecoration(d, targetId);
  775. }
  776. #define IMPL_GET_PRIMITIVE_TYPE(ty) \
  777. \
  778. uint32_t ModuleBuilder::get##ty##Type() { \
  779. const Type *type = Type::get##ty(theContext); \
  780. const uint32_t typeId = theContext.getResultIdForType(type); \
  781. theModule.addType(type, typeId); \
  782. return typeId; \
  783. }
  784. IMPL_GET_PRIMITIVE_TYPE(Void)
  785. IMPL_GET_PRIMITIVE_TYPE(Bool)
  786. IMPL_GET_PRIMITIVE_TYPE(Int32)
  787. IMPL_GET_PRIMITIVE_TYPE(Uint32)
  788. IMPL_GET_PRIMITIVE_TYPE(Float32)
  789. #undef IMPL_GET_PRIMITIVE_TYPE
  790. // Note: At the moment, Float16 capability should not be added for Vulkan 1.0.
  791. // It is not a required capability, and adding the SPV_AMD_gpu_half_float does
  792. // not enable this capability. Any driver that supports float16 in Vulkan 1.0
  793. // should accept this extension.
  794. #define IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(ty, cap) \
  795. \
  796. uint32_t ModuleBuilder::get##ty##Type() { \
  797. if (spv::Capability::cap == spv::Capability::Float16) \
  798. addExtension(Extension::AMD_gpu_shader_half_float, "16-bit float", {}); \
  799. else \
  800. requireCapability(spv::Capability::cap); \
  801. const Type *type = Type::get##ty(theContext); \
  802. const uint32_t typeId = theContext.getResultIdForType(type); \
  803. theModule.addType(type, typeId); \
  804. return typeId; \
  805. }
  806. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Int64, Int64)
  807. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Uint64, Int64)
  808. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Float64, Float64)
  809. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Int16, Int16)
  810. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Uint16, Int16)
  811. IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY(Float16, Float16)
  812. #undef IMPL_GET_PRIMITIVE_TYPE_WITH_CAPABILITY
  813. uint32_t ModuleBuilder::getVecType(uint32_t elemType, uint32_t elemCount) {
  814. const Type *type = nullptr;
  815. switch (elemCount) {
  816. case 2:
  817. type = Type::getVec2(theContext, elemType);
  818. break;
  819. case 3:
  820. type = Type::getVec3(theContext, elemType);
  821. break;
  822. case 4:
  823. type = Type::getVec4(theContext, elemType);
  824. break;
  825. default:
  826. assert(false && "unhandled vector size");
  827. // Error found. Return 0 as the <result-id> directly.
  828. return 0;
  829. }
  830. const uint32_t typeId = theContext.getResultIdForType(type);
  831. theModule.addType(type, typeId);
  832. return typeId;
  833. }
  834. uint32_t ModuleBuilder::getMatType(QualType elemType, uint32_t colType,
  835. uint32_t colCount,
  836. Type::DecorationSet decorations) {
  837. // NOTE: According to Item "Data rules" of SPIR-V Spec 2.16.1 "Universal
  838. // Validation Rules":
  839. // Matrix types can only be parameterized with floating-point types.
  840. //
  841. // So we need special handling of non-fp matrices. We emulate non-fp
  842. // matrices as an array of vectors.
  843. if (!elemType->isFloatingType())
  844. return getArrayType(colType, getConstantUint32(colCount), decorations);
  845. const Type *type = Type::getMatrix(theContext, colType, colCount);
  846. const uint32_t typeId = theContext.getResultIdForType(type);
  847. theModule.addType(type, typeId);
  848. return typeId;
  849. }
  850. uint32_t ModuleBuilder::getPointerType(uint32_t pointeeType,
  851. spv::StorageClass storageClass) {
  852. const Type *type = Type::getPointer(theContext, storageClass, pointeeType);
  853. const uint32_t typeId = theContext.getResultIdForType(type);
  854. theModule.addType(type, typeId);
  855. return typeId;
  856. }
  857. uint32_t
  858. ModuleBuilder::getStructType(llvm::ArrayRef<uint32_t> fieldTypes,
  859. llvm::StringRef structName,
  860. llvm::ArrayRef<llvm::StringRef> fieldNames,
  861. Type::DecorationSet decorations) {
  862. const Type *type = Type::getStruct(theContext, fieldTypes, decorations);
  863. bool isRegistered = false;
  864. const uint32_t typeId = theContext.getResultIdForType(type, &isRegistered);
  865. theModule.addType(type, typeId);
  866. if (!isRegistered) {
  867. theModule.addDebugName(typeId, structName);
  868. if (!fieldNames.empty()) {
  869. assert(fieldNames.size() == fieldTypes.size());
  870. for (uint32_t i = 0; i < fieldNames.size(); ++i)
  871. theModule.addDebugName(typeId, fieldNames[i],
  872. llvm::Optional<uint32_t>(i));
  873. }
  874. }
  875. return typeId;
  876. }
  877. uint32_t ModuleBuilder::getSparseResidencyStructType(uint32_t type) {
  878. const auto uintType = getUint32Type();
  879. return getStructType({uintType, type}, "SparseResidencyStruct",
  880. {"Residency.Code", "Result.Type"});
  881. }
  882. uint32_t ModuleBuilder::getArrayType(uint32_t elemType, uint32_t count,
  883. Type::DecorationSet decorations) {
  884. const Type *type = Type::getArray(theContext, elemType, count, decorations);
  885. const uint32_t typeId = theContext.getResultIdForType(type);
  886. theModule.addType(type, typeId);
  887. return typeId;
  888. }
  889. uint32_t ModuleBuilder::getRuntimeArrayType(uint32_t elemType,
  890. Type::DecorationSet decorations) {
  891. const Type *type = Type::getRuntimeArray(theContext, elemType, decorations);
  892. const uint32_t typeId = theContext.getResultIdForType(type);
  893. theModule.addType(type, typeId);
  894. return typeId;
  895. }
  896. uint32_t ModuleBuilder::getFunctionType(uint32_t returnType,
  897. llvm::ArrayRef<uint32_t> paramTypes) {
  898. const Type *type = Type::getFunction(theContext, returnType, paramTypes);
  899. const uint32_t typeId = theContext.getResultIdForType(type);
  900. theModule.addType(type, typeId);
  901. return typeId;
  902. }
  903. uint32_t ModuleBuilder::getImageType(uint32_t sampledType, spv::Dim dim,
  904. uint32_t depth, bool isArray, uint32_t ms,
  905. uint32_t sampled,
  906. spv::ImageFormat format) {
  907. const Type *type = Type::getImage(theContext, sampledType, dim, depth,
  908. isArray, ms, sampled, format);
  909. bool isRegistered = false;
  910. const uint32_t typeId = theContext.getResultIdForType(type, &isRegistered);
  911. theModule.addType(type, typeId);
  912. switch (format) {
  913. case spv::ImageFormat::Rg32f:
  914. case spv::ImageFormat::Rg16f:
  915. case spv::ImageFormat::R11fG11fB10f:
  916. case spv::ImageFormat::R16f:
  917. case spv::ImageFormat::Rgba16:
  918. case spv::ImageFormat::Rgb10A2:
  919. case spv::ImageFormat::Rg16:
  920. case spv::ImageFormat::Rg8:
  921. case spv::ImageFormat::R16:
  922. case spv::ImageFormat::R8:
  923. case spv::ImageFormat::Rgba16Snorm:
  924. case spv::ImageFormat::Rg16Snorm:
  925. case spv::ImageFormat::Rg8Snorm:
  926. case spv::ImageFormat::R16Snorm:
  927. case spv::ImageFormat::R8Snorm:
  928. case spv::ImageFormat::Rg32i:
  929. case spv::ImageFormat::Rg16i:
  930. case spv::ImageFormat::Rg8i:
  931. case spv::ImageFormat::R16i:
  932. case spv::ImageFormat::R8i:
  933. case spv::ImageFormat::Rgb10a2ui:
  934. case spv::ImageFormat::Rg32ui:
  935. case spv::ImageFormat::Rg16ui:
  936. case spv::ImageFormat::Rg8ui:
  937. case spv::ImageFormat::R16ui:
  938. case spv::ImageFormat::R8ui:
  939. requireCapability(spv::Capability::StorageImageExtendedFormats);
  940. }
  941. if (dim == spv::Dim::Dim1D) {
  942. if (sampled == 2u) {
  943. requireCapability(spv::Capability::Image1D);
  944. } else {
  945. requireCapability(spv::Capability::Sampled1D);
  946. }
  947. } else if (dim == spv::Dim::Buffer) {
  948. requireCapability(spv::Capability::SampledBuffer);
  949. } else if (dim == spv::Dim::SubpassData) {
  950. requireCapability(spv::Capability::InputAttachment);
  951. }
  952. if (isArray && ms) {
  953. requireCapability(spv::Capability::ImageMSArray);
  954. }
  955. // Skip constructing the debug name if we have already done it before.
  956. if (!isRegistered) {
  957. const char *dimStr = "";
  958. switch (dim) {
  959. case spv::Dim::Dim1D:
  960. dimStr = "1d.";
  961. break;
  962. case spv::Dim::Dim2D:
  963. dimStr = "2d.";
  964. break;
  965. case spv::Dim::Dim3D:
  966. dimStr = "3d.";
  967. break;
  968. case spv::Dim::Cube:
  969. dimStr = "cube.";
  970. break;
  971. case spv::Dim::Rect:
  972. dimStr = "rect.";
  973. break;
  974. case spv::Dim::Buffer:
  975. dimStr = "buffer.";
  976. break;
  977. case spv::Dim::SubpassData:
  978. dimStr = "subpass.";
  979. break;
  980. default:
  981. break;
  982. }
  983. std::string name =
  984. std::string("type.") + dimStr + "image" + (isArray ? ".array" : "");
  985. theModule.addDebugName(typeId, name);
  986. }
  987. return typeId;
  988. }
  989. uint32_t ModuleBuilder::getSamplerType() {
  990. const Type *type = Type::getSampler(theContext);
  991. const uint32_t typeId = theContext.getResultIdForType(type);
  992. theModule.addType(type, typeId);
  993. theModule.addDebugName(typeId, "type.sampler");
  994. return typeId;
  995. }
  996. uint32_t ModuleBuilder::getSampledImageType(uint32_t imageType) {
  997. const Type *type = Type::getSampledImage(theContext, imageType);
  998. const uint32_t typeId = theContext.getResultIdForType(type);
  999. theModule.addType(type, typeId);
  1000. theModule.addDebugName(typeId, "type.sampled.image");
  1001. return typeId;
  1002. }
  1003. uint32_t ModuleBuilder::getByteAddressBufferType(bool isRW) {
  1004. // Create a uint RuntimeArray with Array Stride of 4.
  1005. const uint32_t uintType = getUint32Type();
  1006. const auto *arrStride4 = Decoration::getArrayStride(theContext, 4u);
  1007. const Type *raType =
  1008. Type::getRuntimeArray(theContext, uintType, {arrStride4});
  1009. const uint32_t raTypeId = theContext.getResultIdForType(raType);
  1010. theModule.addType(raType, raTypeId);
  1011. // Create a struct containing the runtime array as its only member.
  1012. // The struct must also be decorated as BufferBlock. The offset decoration
  1013. // should also be applied to the first (only) member. NonWritable decoration
  1014. // should also be applied to the first member if isRW is true.
  1015. llvm::SmallVector<const Decoration *, 3> typeDecs;
  1016. typeDecs.push_back(Decoration::getBufferBlock(theContext));
  1017. typeDecs.push_back(Decoration::getOffset(theContext, 0, 0));
  1018. if (!isRW)
  1019. typeDecs.push_back(Decoration::getNonWritable(theContext, 0));
  1020. const Type *type = Type::getStruct(theContext, {raTypeId}, typeDecs);
  1021. const uint32_t typeId = theContext.getResultIdForType(type);
  1022. theModule.addType(type, typeId);
  1023. theModule.addDebugName(typeId, isRW ? "type.RWByteAddressBuffer"
  1024. : "type.ByteAddressBuffer");
  1025. return typeId;
  1026. }
  1027. uint32_t ModuleBuilder::getConstantBool(bool value, bool isSpecConst) {
  1028. if (isSpecConst) {
  1029. const uint32_t constId = theContext.takeNextId();
  1030. if (value) {
  1031. instBuilder.opSpecConstantTrue(getBoolType(), constId).x();
  1032. } else {
  1033. instBuilder.opSpecConstantFalse(getBoolType(), constId).x();
  1034. }
  1035. theModule.addVariable(std::move(constructSite));
  1036. return constId;
  1037. }
  1038. const uint32_t typeId = getBoolType();
  1039. const Constant *constant = value ? Constant::getTrue(theContext, typeId)
  1040. : Constant::getFalse(theContext, typeId);
  1041. const uint32_t constId = theContext.getResultIdForConstant(constant);
  1042. theModule.addConstant(constant, constId);
  1043. return constId;
  1044. }
  1045. #define IMPL_GET_PRIMITIVE_CONST(builderTy, cppTy) \
  1046. \
  1047. uint32_t ModuleBuilder::getConstant##builderTy(cppTy value) { \
  1048. const uint32_t typeId = get##builderTy##Type(); \
  1049. const Constant *constant = \
  1050. Constant::get##builderTy(theContext, typeId, value); \
  1051. const uint32_t constId = theContext.getResultIdForConstant(constant); \
  1052. theModule.addConstant(constant, constId); \
  1053. return constId; \
  1054. }
  1055. #define IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(builderTy, cppTy) \
  1056. \
  1057. uint32_t ModuleBuilder::getConstant##builderTy(cppTy value, \
  1058. bool isSpecConst) { \
  1059. if (isSpecConst) { \
  1060. const uint32_t constId = theContext.takeNextId(); \
  1061. instBuilder \
  1062. .opSpecConstant(get##builderTy##Type(), constId, \
  1063. cast::BitwiseCast<uint32_t>(value)) \
  1064. .x(); \
  1065. theModule.addVariable(std::move(constructSite)); \
  1066. return constId; \
  1067. } \
  1068. \
  1069. const uint32_t typeId = get##builderTy##Type(); \
  1070. const Constant *constant = \
  1071. Constant::get##builderTy(theContext, typeId, value); \
  1072. const uint32_t constId = theContext.getResultIdForConstant(constant); \
  1073. theModule.addConstant(constant, constId); \
  1074. return constId; \
  1075. }
  1076. IMPL_GET_PRIMITIVE_CONST(Int16, int16_t)
  1077. IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(Int32, int32_t)
  1078. IMPL_GET_PRIMITIVE_CONST(Uint16, uint16_t)
  1079. IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(Uint32, uint32_t)
  1080. IMPL_GET_PRIMITIVE_CONST(Float16, int16_t)
  1081. IMPL_GET_PRIMITIVE_CONST_SPEC_CONST(Float32, float)
  1082. IMPL_GET_PRIMITIVE_CONST(Float64, double)
  1083. IMPL_GET_PRIMITIVE_CONST(Int64, int64_t)
  1084. IMPL_GET_PRIMITIVE_CONST(Uint64, uint64_t)
  1085. #undef IMPL_GET_PRIMITIVE_CONST
  1086. #undef IMPL_GET_PRIMITIVE_CONST_SPEC_CONST
  1087. uint32_t
  1088. ModuleBuilder::getConstantComposite(uint32_t typeId,
  1089. llvm::ArrayRef<uint32_t> constituents) {
  1090. const Constant *constant =
  1091. Constant::getComposite(theContext, typeId, constituents);
  1092. const uint32_t constId = theContext.getResultIdForConstant(constant);
  1093. theModule.addConstant(constant, constId);
  1094. return constId;
  1095. }
  1096. uint32_t ModuleBuilder::getConstantNull(uint32_t typeId) {
  1097. const Constant *constant = Constant::getNull(theContext, typeId);
  1098. const uint32_t constId = theContext.getResultIdForConstant(constant);
  1099. theModule.addConstant(constant, constId);
  1100. return constId;
  1101. }
  1102. BasicBlock *ModuleBuilder::getBasicBlock(uint32_t labelId) {
  1103. auto it = basicBlocks.find(labelId);
  1104. if (it == basicBlocks.end()) {
  1105. assert(false && "invalid <label-id>");
  1106. return nullptr;
  1107. }
  1108. return it->second.get();
  1109. }
  1110. } // end namespace spirv
  1111. } // end namespace clang