SpvBuilder.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. //
  2. // Copyright (C) 2014-2015 LunarG, Inc.
  3. // Copyright (C) 2015-2016 Google, Inc.
  4. // Copyright (C) 2017 ARM Limited.
  5. //
  6. // All rights reserved.
  7. //
  8. // Redistribution and use in source and binary forms, with or without
  9. // modification, are permitted provided that the following conditions
  10. // are met:
  11. //
  12. // Redistributions of source code must retain the above copyright
  13. // notice, this list of conditions and the following disclaimer.
  14. //
  15. // Redistributions in binary form must reproduce the above
  16. // copyright notice, this list of conditions and the following
  17. // disclaimer in the documentation and/or other materials provided
  18. // with the distribution.
  19. //
  20. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  21. // contributors may be used to endorse or promote products derived
  22. // from this software without specific prior written permission.
  23. //
  24. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  25. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  26. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  27. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  28. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  29. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  30. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  31. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  33. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  34. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  35. // POSSIBILITY OF SUCH DAMAGE.
  36. //
  37. // "Builder" is an interface to fully build SPIR-V IR. Allocate one of
  38. // these to build (a thread safe) internal SPIR-V representation (IR),
  39. // and then dump it as a binary stream according to the SPIR-V specification.
  40. //
  41. // A Builder has a 1:1 relationship with a SPIR-V module.
  42. //
  43. #pragma once
  44. #ifndef SpvBuilder_H
  45. #define SpvBuilder_H
  46. #include "Logger.h"
  47. #include "spirv.hpp"
  48. #include "spvIR.h"
  49. #include <algorithm>
  50. #include <map>
  51. #include <memory>
  52. #include <set>
  53. #include <sstream>
  54. #include <stack>
  55. #include <unordered_map>
  56. namespace spv {
  57. class Builder {
  58. public:
  59. Builder(unsigned int spvVersion, unsigned int userNumber, SpvBuildLogger* logger);
  60. virtual ~Builder();
  61. static const int maxMatrixSize = 4;
  62. unsigned int getSpvVersion() const { return spvVersion; }
  63. void setSource(spv::SourceLanguage lang, int version)
  64. {
  65. source = lang;
  66. sourceVersion = version;
  67. }
  68. void setSourceFile(const std::string& file)
  69. {
  70. Instruction* fileString = new Instruction(getUniqueId(), NoType, OpString);
  71. fileString->addStringOperand(file.c_str());
  72. sourceFileStringId = fileString->getResultId();
  73. strings.push_back(std::unique_ptr<Instruction>(fileString));
  74. }
  75. void setSourceText(const std::string& text) { sourceText = text; }
  76. void addSourceExtension(const char* ext) { sourceExtensions.push_back(ext); }
  77. void addModuleProcessed(const std::string& p) { moduleProcesses.push_back(p.c_str()); }
  78. void setEmitOpLines() { emitOpLines = true; }
  79. void addExtension(const char* ext) { extensions.insert(ext); }
  80. Id import(const char*);
  81. void setMemoryModel(spv::AddressingModel addr, spv::MemoryModel mem)
  82. {
  83. addressModel = addr;
  84. memoryModel = mem;
  85. }
  86. void addCapability(spv::Capability cap) { capabilities.insert(cap); }
  87. // To get a new <id> for anything needing a new one.
  88. Id getUniqueId() { return ++uniqueId; }
  89. // To get a set of new <id>s, e.g., for a set of function parameters
  90. Id getUniqueIds(int numIds)
  91. {
  92. Id id = uniqueId + 1;
  93. uniqueId += numIds;
  94. return id;
  95. }
  96. // Log the current line, and if different than the last one,
  97. // issue a new OpLine, using the current file name.
  98. void setLine(int line);
  99. // Low-level OpLine. See setLine() for a layered helper.
  100. void addLine(Id fileName, int line, int column);
  101. // For creating new types (will return old type if the requested one was already made).
  102. Id makeVoidType();
  103. Id makeBoolType();
  104. Id makePointer(StorageClass, Id type);
  105. Id makeIntegerType(int width, bool hasSign); // generic
  106. Id makeIntType(int width) { return makeIntegerType(width, true); }
  107. Id makeUintType(int width) { return makeIntegerType(width, false); }
  108. Id makeFloatType(int width);
  109. Id makeStructType(const std::vector<Id>& members, const char*);
  110. Id makeStructResultType(Id type0, Id type1);
  111. Id makeVectorType(Id component, int size);
  112. Id makeMatrixType(Id component, int cols, int rows);
  113. Id makeArrayType(Id element, Id sizeId, int stride); // 0 stride means no stride decoration
  114. Id makeRuntimeArray(Id element);
  115. Id makeFunctionType(Id returnType, const std::vector<Id>& paramTypes);
  116. Id makeImageType(Id sampledType, Dim, bool depth, bool arrayed, bool ms, unsigned sampled, ImageFormat format);
  117. Id makeSamplerType();
  118. Id makeSampledImageType(Id imageType);
  119. // For querying about types.
  120. Id getTypeId(Id resultId) const { return module.getTypeId(resultId); }
  121. Id getDerefTypeId(Id resultId) const;
  122. Op getOpCode(Id id) const { return module.getInstruction(id)->getOpCode(); }
  123. Op getTypeClass(Id typeId) const { return getOpCode(typeId); }
  124. Op getMostBasicTypeClass(Id typeId) const;
  125. int getNumComponents(Id resultId) const { return getNumTypeComponents(getTypeId(resultId)); }
  126. int getNumTypeConstituents(Id typeId) const;
  127. int getNumTypeComponents(Id typeId) const { return getNumTypeConstituents(typeId); }
  128. Id getScalarTypeId(Id typeId) const;
  129. Id getContainedTypeId(Id typeId) const;
  130. Id getContainedTypeId(Id typeId, int) const;
  131. StorageClass getTypeStorageClass(Id typeId) const { return module.getStorageClass(typeId); }
  132. ImageFormat getImageTypeFormat(Id typeId) const { return (ImageFormat)module.getInstruction(typeId)->getImmediateOperand(6); }
  133. bool isPointer(Id resultId) const { return isPointerType(getTypeId(resultId)); }
  134. bool isScalar(Id resultId) const { return isScalarType(getTypeId(resultId)); }
  135. bool isVector(Id resultId) const { return isVectorType(getTypeId(resultId)); }
  136. bool isMatrix(Id resultId) const { return isMatrixType(getTypeId(resultId)); }
  137. bool isAggregate(Id resultId) const { return isAggregateType(getTypeId(resultId)); }
  138. bool isSampledImage(Id resultId) const { return isSampledImageType(getTypeId(resultId)); }
  139. bool isBoolType(Id typeId) { return groupedTypes[OpTypeBool].size() > 0 && typeId == groupedTypes[OpTypeBool].back()->getResultId(); }
  140. bool isIntType(Id typeId) const { return getTypeClass(typeId) == OpTypeInt && module.getInstruction(typeId)->getImmediateOperand(1) != 0; }
  141. bool isUintType(Id typeId) const { return getTypeClass(typeId) == OpTypeInt && module.getInstruction(typeId)->getImmediateOperand(1) == 0; }
  142. bool isFloatType(Id typeId) const { return getTypeClass(typeId) == OpTypeFloat; }
  143. bool isPointerType(Id typeId) const { return getTypeClass(typeId) == OpTypePointer; }
  144. bool isScalarType(Id typeId) const { return getTypeClass(typeId) == OpTypeFloat || getTypeClass(typeId) == OpTypeInt || getTypeClass(typeId) == OpTypeBool; }
  145. bool isVectorType(Id typeId) const { return getTypeClass(typeId) == OpTypeVector; }
  146. bool isMatrixType(Id typeId) const { return getTypeClass(typeId) == OpTypeMatrix; }
  147. bool isStructType(Id typeId) const { return getTypeClass(typeId) == OpTypeStruct; }
  148. bool isArrayType(Id typeId) const { return getTypeClass(typeId) == OpTypeArray; }
  149. bool isAggregateType(Id typeId) const { return isArrayType(typeId) || isStructType(typeId); }
  150. bool isImageType(Id typeId) const { return getTypeClass(typeId) == OpTypeImage; }
  151. bool isSamplerType(Id typeId) const { return getTypeClass(typeId) == OpTypeSampler; }
  152. bool isSampledImageType(Id typeId) const { return getTypeClass(typeId) == OpTypeSampledImage; }
  153. bool containsType(Id typeId, Op typeOp, int width) const;
  154. bool isConstantOpCode(Op opcode) const;
  155. bool isSpecConstantOpCode(Op opcode) const;
  156. bool isConstant(Id resultId) const { return isConstantOpCode(getOpCode(resultId)); }
  157. bool isConstantScalar(Id resultId) const { return getOpCode(resultId) == OpConstant; }
  158. bool isSpecConstant(Id resultId) const { return isSpecConstantOpCode(getOpCode(resultId)); }
  159. unsigned int getConstantScalar(Id resultId) const { return module.getInstruction(resultId)->getImmediateOperand(0); }
  160. StorageClass getStorageClass(Id resultId) const { return getTypeStorageClass(getTypeId(resultId)); }
  161. int getScalarTypeWidth(Id typeId) const
  162. {
  163. Id scalarTypeId = getScalarTypeId(typeId);
  164. assert(getTypeClass(scalarTypeId) == OpTypeInt || getTypeClass(scalarTypeId) == OpTypeFloat);
  165. return module.getInstruction(scalarTypeId)->getImmediateOperand(0);
  166. }
  167. int getTypeNumColumns(Id typeId) const
  168. {
  169. assert(isMatrixType(typeId));
  170. return getNumTypeConstituents(typeId);
  171. }
  172. int getNumColumns(Id resultId) const { return getTypeNumColumns(getTypeId(resultId)); }
  173. int getTypeNumRows(Id typeId) const
  174. {
  175. assert(isMatrixType(typeId));
  176. return getNumTypeComponents(getContainedTypeId(typeId));
  177. }
  178. int getNumRows(Id resultId) const { return getTypeNumRows(getTypeId(resultId)); }
  179. Dim getTypeDimensionality(Id typeId) const
  180. {
  181. assert(isImageType(typeId));
  182. return (Dim)module.getInstruction(typeId)->getImmediateOperand(1);
  183. }
  184. Id getImageType(Id resultId) const
  185. {
  186. Id typeId = getTypeId(resultId);
  187. assert(isImageType(typeId) || isSampledImageType(typeId));
  188. return isSampledImageType(typeId) ? module.getInstruction(typeId)->getIdOperand(0) : typeId;
  189. }
  190. bool isArrayedImageType(Id typeId) const
  191. {
  192. assert(isImageType(typeId));
  193. return module.getInstruction(typeId)->getImmediateOperand(3) != 0;
  194. }
  195. // For making new constants (will return old constant if the requested one was already made).
  196. Id makeBoolConstant(bool b, bool specConstant = false);
  197. Id makeInt8Constant(int i, bool specConstant = false) { return makeIntConstant(makeIntType(8), (unsigned)i, specConstant); }
  198. Id makeUint8Constant(unsigned u, bool specConstant = false) { return makeIntConstant(makeUintType(8), u, specConstant); }
  199. Id makeInt16Constant(int i, bool specConstant = false) { return makeIntConstant(makeIntType(16), (unsigned)i, specConstant); }
  200. Id makeUint16Constant(unsigned u, bool specConstant = false) { return makeIntConstant(makeUintType(16), u, specConstant); }
  201. Id makeIntConstant(int i, bool specConstant = false) { return makeIntConstant(makeIntType(32), (unsigned)i, specConstant); }
  202. Id makeUintConstant(unsigned u, bool specConstant = false) { return makeIntConstant(makeUintType(32), u, specConstant); }
  203. Id makeInt64Constant(long long i, bool specConstant = false) { return makeInt64Constant(makeIntType(64), (unsigned long long)i, specConstant); }
  204. Id makeUint64Constant(unsigned long long u, bool specConstant = false) { return makeInt64Constant(makeUintType(64), u, specConstant); }
  205. Id makeFloatConstant(float f, bool specConstant = false);
  206. Id makeDoubleConstant(double d, bool specConstant = false);
  207. Id makeFloat16Constant(float f16, bool specConstant = false);
  208. Id makeFpConstant(Id type, double d, bool specConstant = false);
  209. // Turn the array of constants into a proper spv constant of the requested type.
  210. Id makeCompositeConstant(Id type, const std::vector<Id>& comps, bool specConst = false);
  211. // Methods for adding information outside the CFG.
  212. Instruction* addEntryPoint(ExecutionModel, Function*, const char* name);
  213. void addExecutionMode(Function*, ExecutionMode mode, int value1 = -1, int value2 = -1, int value3 = -1);
  214. void addName(Id, const char* name);
  215. void addMemberName(Id, int member, const char* name);
  216. void addDecoration(Id, Decoration, int num = -1);
  217. void addDecoration(Id, Decoration, const char*);
  218. void addDecorationId(Id id, Decoration, Id idDecoration);
  219. void addMemberDecoration(Id, unsigned int member, Decoration, int num = -1);
  220. void addMemberDecoration(Id, unsigned int member, Decoration, const char*);
  221. // At the end of what block do the next create*() instructions go?
  222. void setBuildPoint(Block* bp) { buildPoint = bp; }
  223. Block* getBuildPoint() const { return buildPoint; }
  224. // Make the entry-point function. The returned pointer is only valid
  225. // for the lifetime of this builder.
  226. Function* makeEntryPoint(const char*);
  227. // Make a shader-style function, and create its entry block if entry is non-zero.
  228. // Return the function, pass back the entry.
  229. // The returned pointer is only valid for the lifetime of this builder.
  230. Function* makeFunctionEntry(Decoration precision, Id returnType, const char* name, const std::vector<Id>& paramTypes,
  231. const std::vector<std::vector<Decoration>>& precisions, Block **entry = 0);
  232. // Create a return. An 'implicit' return is one not appearing in the source
  233. // code. In the case of an implicit return, no post-return block is inserted.
  234. void makeReturn(bool implicit, Id retVal = 0);
  235. // Generate all the code needed to finish up a function.
  236. void leaveFunction();
  237. // Create a discard.
  238. void makeDiscard();
  239. // Create a global or function local or IO variable.
  240. Id createVariable(StorageClass, Id type, const char* name = 0);
  241. // Create an intermediate with an undefined value.
  242. Id createUndefined(Id type);
  243. // Store into an Id and return the l-value
  244. void createStore(Id rValue, Id lValue, spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMaskNone, spv::Scope scope = spv::ScopeMax);
  245. // Load from an Id and return it
  246. Id createLoad(Id lValue, spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMaskNone, spv::Scope scope = spv::ScopeMax);
  247. // Create an OpAccessChain instruction
  248. Id createAccessChain(StorageClass, Id base, const std::vector<Id>& offsets);
  249. // Create an OpArrayLength instruction
  250. Id createArrayLength(Id base, unsigned int member);
  251. // Create an OpCompositeExtract instruction
  252. Id createCompositeExtract(Id composite, Id typeId, unsigned index);
  253. Id createCompositeExtract(Id composite, Id typeId, const std::vector<unsigned>& indexes);
  254. Id createCompositeInsert(Id object, Id composite, Id typeId, unsigned index);
  255. Id createCompositeInsert(Id object, Id composite, Id typeId, const std::vector<unsigned>& indexes);
  256. Id createVectorExtractDynamic(Id vector, Id typeId, Id componentIndex);
  257. Id createVectorInsertDynamic(Id vector, Id typeId, Id component, Id componentIndex);
  258. void createNoResultOp(Op);
  259. void createNoResultOp(Op, Id operand);
  260. void createNoResultOp(Op, const std::vector<Id>& operands);
  261. void createNoResultOp(Op, const std::vector<IdImmediate>& operands);
  262. void createControlBarrier(Scope execution, Scope memory, MemorySemanticsMask);
  263. void createMemoryBarrier(unsigned executionScope, unsigned memorySemantics);
  264. Id createUnaryOp(Op, Id typeId, Id operand);
  265. Id createBinOp(Op, Id typeId, Id operand1, Id operand2);
  266. Id createTriOp(Op, Id typeId, Id operand1, Id operand2, Id operand3);
  267. Id createOp(Op, Id typeId, const std::vector<Id>& operands);
  268. Id createOp(Op, Id typeId, const std::vector<IdImmediate>& operands);
  269. Id createFunctionCall(spv::Function*, const std::vector<spv::Id>&);
  270. Id createSpecConstantOp(Op, Id typeId, const std::vector<spv::Id>& operands, const std::vector<unsigned>& literals);
  271. // Take an rvalue (source) and a set of channels to extract from it to
  272. // make a new rvalue, which is returned.
  273. Id createRvalueSwizzle(Decoration precision, Id typeId, Id source, const std::vector<unsigned>& channels);
  274. // Take a copy of an lvalue (target) and a source of components, and set the
  275. // source components into the lvalue where the 'channels' say to put them.
  276. // An updated version of the target is returned.
  277. // (No true lvalue or stores are used.)
  278. Id createLvalueSwizzle(Id typeId, Id target, Id source, const std::vector<unsigned>& channels);
  279. // If both the id and precision are valid, the id
  280. // gets tagged with the requested precision.
  281. // The passed in id is always the returned id, to simplify use patterns.
  282. Id setPrecision(Id id, Decoration precision)
  283. {
  284. if (precision != NoPrecision && id != NoResult)
  285. addDecoration(id, precision);
  286. return id;
  287. }
  288. // Can smear a scalar to a vector for the following forms:
  289. // - promoteScalar(scalar, vector) // smear scalar to width of vector
  290. // - promoteScalar(vector, scalar) // smear scalar to width of vector
  291. // - promoteScalar(pointer, scalar) // smear scalar to width of what pointer points to
  292. // - promoteScalar(scalar, scalar) // do nothing
  293. // Other forms are not allowed.
  294. //
  295. // Generally, the type of 'scalar' does not need to be the same type as the components in 'vector'.
  296. // The type of the created vector is a vector of components of the same type as the scalar.
  297. //
  298. // Note: One of the arguments will change, with the result coming back that way rather than
  299. // through the return value.
  300. void promoteScalar(Decoration precision, Id& left, Id& right);
  301. // Make a value by smearing the scalar to fill the type.
  302. // vectorType should be the correct type for making a vector of scalarVal.
  303. // (No conversions are done.)
  304. Id smearScalar(Decoration precision, Id scalarVal, Id vectorType);
  305. // Create a call to a built-in function.
  306. Id createBuiltinCall(Id resultType, Id builtins, int entryPoint, const std::vector<Id>& args);
  307. // List of parameters used to create a texture operation
  308. struct TextureParameters {
  309. Id sampler;
  310. Id coords;
  311. Id bias;
  312. Id lod;
  313. Id Dref;
  314. Id offset;
  315. Id offsets;
  316. Id gradX;
  317. Id gradY;
  318. Id sample;
  319. Id component;
  320. Id texelOut;
  321. Id lodClamp;
  322. bool nonprivate;
  323. bool volatil;
  324. };
  325. // Select the correct texture operation based on all inputs, and emit the correct instruction
  326. Id createTextureCall(Decoration precision, Id resultType, bool sparse, bool fetch, bool proj, bool gather, bool noImplicit, const TextureParameters&);
  327. // Emit the OpTextureQuery* instruction that was passed in.
  328. // Figure out the right return value and type, and return it.
  329. Id createTextureQueryCall(Op, const TextureParameters&, bool isUnsignedResult);
  330. Id createSamplePositionCall(Decoration precision, Id, Id);
  331. Id createBitFieldExtractCall(Decoration precision, Id, Id, Id, bool isSigned);
  332. Id createBitFieldInsertCall(Decoration precision, Id, Id, Id, Id);
  333. // Reduction comparison for composites: For equal and not-equal resulting in a scalar.
  334. Id createCompositeCompare(Decoration precision, Id, Id, bool /* true if for equal, false if for not-equal */);
  335. // OpCompositeConstruct
  336. Id createCompositeConstruct(Id typeId, const std::vector<Id>& constituents);
  337. // vector or scalar constructor
  338. Id createConstructor(Decoration precision, const std::vector<Id>& sources, Id resultTypeId);
  339. // matrix constructor
  340. Id createMatrixConstructor(Decoration precision, const std::vector<Id>& sources, Id constructee);
  341. // Helper to use for building nested control flow with if-then-else.
  342. class If {
  343. public:
  344. If(Id condition, unsigned int ctrl, Builder& builder);
  345. ~If() {}
  346. void makeBeginElse();
  347. void makeEndIf();
  348. private:
  349. If(const If&);
  350. If& operator=(If&);
  351. Builder& builder;
  352. Id condition;
  353. unsigned int control;
  354. Function* function;
  355. Block* headerBlock;
  356. Block* thenBlock;
  357. Block* elseBlock;
  358. Block* mergeBlock;
  359. };
  360. // Make a switch statement. A switch has 'numSegments' of pieces of code, not containing
  361. // any case/default labels, all separated by one or more case/default labels. Each possible
  362. // case value v is a jump to the caseValues[v] segment. The defaultSegment is also in this
  363. // number space. How to compute the value is given by 'condition', as in switch(condition).
  364. //
  365. // The SPIR-V Builder will maintain the stack of post-switch merge blocks for nested switches.
  366. //
  367. // Use a defaultSegment < 0 if there is no default segment (to branch to post switch).
  368. //
  369. // Returns the right set of basic blocks to start each code segment with, so that the caller's
  370. // recursion stack can hold the memory for it.
  371. //
  372. void makeSwitch(Id condition, unsigned int control, int numSegments, const std::vector<int>& caseValues,
  373. const std::vector<int>& valueToSegment, int defaultSegment, std::vector<Block*>& segmentBB); // return argument
  374. // Add a branch to the innermost switch's merge block.
  375. void addSwitchBreak();
  376. // Move to the next code segment, passing in the return argument in makeSwitch()
  377. void nextSwitchSegment(std::vector<Block*>& segmentBB, int segment);
  378. // Finish off the innermost switch.
  379. void endSwitch(std::vector<Block*>& segmentBB);
  380. struct LoopBlocks {
  381. LoopBlocks(Block& head, Block& body, Block& merge, Block& continue_target) :
  382. head(head), body(body), merge(merge), continue_target(continue_target) { }
  383. Block &head, &body, &merge, &continue_target;
  384. private:
  385. LoopBlocks();
  386. LoopBlocks& operator=(const LoopBlocks&);
  387. };
  388. // Start a new loop and prepare the builder to generate code for it. Until
  389. // closeLoop() is called for this loop, createLoopContinue() and
  390. // createLoopExit() will target its corresponding blocks.
  391. LoopBlocks& makeNewLoop();
  392. // Create a new block in the function containing the build point. Memory is
  393. // owned by the function object.
  394. Block& makeNewBlock();
  395. // Add a branch to the continue_target of the current (innermost) loop.
  396. void createLoopContinue();
  397. // Add an exit (e.g. "break") from the innermost loop that we're currently
  398. // in.
  399. void createLoopExit();
  400. // Close the innermost loop that you're in
  401. void closeLoop();
  402. //
  403. // Access chain design for an R-Value vs. L-Value:
  404. //
  405. // There is a single access chain the builder is building at
  406. // any particular time. Such a chain can be used to either to a load or
  407. // a store, when desired.
  408. //
  409. // Expressions can be r-values, l-values, or both, or only r-values:
  410. // a[b.c].d = .... // l-value
  411. // ... = a[b.c].d; // r-value, that also looks like an l-value
  412. // ++a[b.c].d; // r-value and l-value
  413. // (x + y)[2]; // r-value only, can't possibly be l-value
  414. //
  415. // Computing an r-value means generating code. Hence,
  416. // r-values should only be computed when they are needed, not speculatively.
  417. //
  418. // Computing an l-value means saving away information for later use in the compiler,
  419. // no code is generated until the l-value is later dereferenced. It is okay
  420. // to speculatively generate an l-value, just not okay to speculatively dereference it.
  421. //
  422. // The base of the access chain (the left-most variable or expression
  423. // from which everything is based) can be set either as an l-value
  424. // or as an r-value. Most efficient would be to set an l-value if one
  425. // is available. If an expression was evaluated, the resulting r-value
  426. // can be set as the chain base.
  427. //
  428. // The users of this single access chain can save and restore if they
  429. // want to nest or manage multiple chains.
  430. //
  431. struct AccessChain {
  432. Id base; // for l-values, pointer to the base object, for r-values, the base object
  433. std::vector<Id> indexChain;
  434. Id instr; // cache the instruction that generates this access chain
  435. std::vector<unsigned> swizzle; // each std::vector element selects the next GLSL component number
  436. Id component; // a dynamic component index, can coexist with a swizzle, done after the swizzle, NoResult if not present
  437. Id preSwizzleBaseType; // dereferenced type, before swizzle or component is applied; NoType unless a swizzle or component is present
  438. bool isRValue; // true if 'base' is an r-value, otherwise, base is an l-value
  439. // Accumulate whether anything in the chain of structures has coherent decorations.
  440. struct CoherentFlags {
  441. unsigned coherent : 1;
  442. unsigned devicecoherent : 1;
  443. unsigned queuefamilycoherent : 1;
  444. unsigned workgroupcoherent : 1;
  445. unsigned subgroupcoherent : 1;
  446. unsigned nonprivate : 1;
  447. unsigned volatil : 1;
  448. unsigned isImage : 1;
  449. void clear() {
  450. coherent = 0;
  451. devicecoherent = 0;
  452. queuefamilycoherent = 0;
  453. workgroupcoherent = 0;
  454. subgroupcoherent = 0;
  455. nonprivate = 0;
  456. volatil = 0;
  457. isImage = 0;
  458. }
  459. CoherentFlags() { clear(); }
  460. CoherentFlags operator |=(const CoherentFlags &other) {
  461. coherent |= other.coherent;
  462. devicecoherent |= other.devicecoherent;
  463. queuefamilycoherent |= other.queuefamilycoherent;
  464. workgroupcoherent |= other.workgroupcoherent;
  465. subgroupcoherent |= other.subgroupcoherent;
  466. nonprivate |= other.nonprivate;
  467. volatil |= other.volatil;
  468. isImage |= other.isImage;
  469. return *this;
  470. }
  471. };
  472. CoherentFlags coherentFlags;
  473. };
  474. //
  475. // the SPIR-V builder maintains a single active chain that
  476. // the following methods operate on
  477. //
  478. // for external save and restore
  479. AccessChain getAccessChain() { return accessChain; }
  480. void setAccessChain(AccessChain newChain) { accessChain = newChain; }
  481. // clear accessChain
  482. void clearAccessChain();
  483. // set new base as an l-value base
  484. void setAccessChainLValue(Id lValue)
  485. {
  486. assert(isPointer(lValue));
  487. accessChain.base = lValue;
  488. }
  489. // set new base value as an r-value
  490. void setAccessChainRValue(Id rValue)
  491. {
  492. accessChain.isRValue = true;
  493. accessChain.base = rValue;
  494. }
  495. // push offset onto the end of the chain
  496. void accessChainPush(Id offset, AccessChain::CoherentFlags coherentFlags)
  497. {
  498. accessChain.indexChain.push_back(offset);
  499. accessChain.coherentFlags |= coherentFlags;
  500. }
  501. // push new swizzle onto the end of any existing swizzle, merging into a single swizzle
  502. void accessChainPushSwizzle(std::vector<unsigned>& swizzle, Id preSwizzleBaseType);
  503. // push a dynamic component selection onto the access chain, only applicable with a
  504. // non-trivial swizzle or no swizzle
  505. void accessChainPushComponent(Id component, Id preSwizzleBaseType)
  506. {
  507. if (accessChain.swizzle.size() != 1) {
  508. accessChain.component = component;
  509. if (accessChain.preSwizzleBaseType == NoType)
  510. accessChain.preSwizzleBaseType = preSwizzleBaseType;
  511. }
  512. }
  513. // use accessChain and swizzle to store value
  514. void accessChainStore(Id rvalue, spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMaskNone, spv::Scope scope = spv::ScopeMax);
  515. // use accessChain and swizzle to load an r-value
  516. Id accessChainLoad(Decoration precision, Decoration nonUniform, Id ResultType, spv::MemoryAccessMask memoryAccess = spv::MemoryAccessMaskNone, spv::Scope scope = spv::ScopeMax);
  517. // get the direct pointer for an l-value
  518. Id accessChainGetLValue();
  519. // Get the inferred SPIR-V type of the result of the current access chain,
  520. // based on the type of the base and the chain of dereferences.
  521. Id accessChainGetInferredType();
  522. // Add capabilities, extensions, remove unneeded decorations, etc.,
  523. // based on the resulting SPIR-V.
  524. void postProcess();
  525. // Hook to visit each instruction in a block in a function
  526. void postProcess(const Instruction&);
  527. // Hook to visit each instruction in a reachable block in a function.
  528. void postProcessReachable(const Instruction&);
  529. // Hook to visit each non-32-bit sized float/int operation in a block.
  530. void postProcessType(const Instruction&, spv::Id typeId);
  531. void dump(std::vector<unsigned int>&) const;
  532. void createBranch(Block* block);
  533. void createConditionalBranch(Id condition, Block* thenBlock, Block* elseBlock);
  534. void createLoopMerge(Block* mergeBlock, Block* continueBlock, unsigned int control, unsigned int dependencyLength);
  535. // Sets to generate opcode for specialization constants.
  536. void setToSpecConstCodeGenMode() { generatingOpCodeForSpecConst = true; }
  537. // Sets to generate opcode for non-specialization constants (normal mode).
  538. void setToNormalCodeGenMode() { generatingOpCodeForSpecConst = false; }
  539. // Check if the builder is generating code for spec constants.
  540. bool isInSpecConstCodeGenMode() { return generatingOpCodeForSpecConst; }
  541. protected:
  542. Id makeIntConstant(Id typeId, unsigned value, bool specConstant);
  543. Id makeInt64Constant(Id typeId, unsigned long long value, bool specConstant);
  544. Id findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned value);
  545. Id findScalarConstant(Op typeClass, Op opcode, Id typeId, unsigned v1, unsigned v2);
  546. Id findCompositeConstant(Op typeClass, const std::vector<Id>& comps);
  547. Id findStructConstant(Id typeId, const std::vector<Id>& comps);
  548. Id collapseAccessChain();
  549. void remapDynamicSwizzle();
  550. void transferAccessChainSwizzle(bool dynamic);
  551. void simplifyAccessChainSwizzle();
  552. void createAndSetNoPredecessorBlock(const char*);
  553. void createSelectionMerge(Block* mergeBlock, unsigned int control);
  554. void dumpSourceInstructions(std::vector<unsigned int>&) const;
  555. void dumpInstructions(std::vector<unsigned int>&, const std::vector<std::unique_ptr<Instruction> >&) const;
  556. void dumpModuleProcesses(std::vector<unsigned int>&) const;
  557. unsigned int spvVersion; // the version of SPIR-V to emit in the header
  558. SourceLanguage source;
  559. int sourceVersion;
  560. spv::Id sourceFileStringId;
  561. std::string sourceText;
  562. int currentLine;
  563. bool emitOpLines;
  564. std::set<std::string> extensions;
  565. std::vector<const char*> sourceExtensions;
  566. std::vector<const char*> moduleProcesses;
  567. AddressingModel addressModel;
  568. MemoryModel memoryModel;
  569. std::set<spv::Capability> capabilities;
  570. int builderNumber;
  571. Module module;
  572. Block* buildPoint;
  573. Id uniqueId;
  574. Function* entryPointFunction;
  575. bool generatingOpCodeForSpecConst;
  576. AccessChain accessChain;
  577. // special blocks of instructions for output
  578. std::vector<std::unique_ptr<Instruction> > strings;
  579. std::vector<std::unique_ptr<Instruction> > imports;
  580. std::vector<std::unique_ptr<Instruction> > entryPoints;
  581. std::vector<std::unique_ptr<Instruction> > executionModes;
  582. std::vector<std::unique_ptr<Instruction> > names;
  583. std::vector<std::unique_ptr<Instruction> > decorations;
  584. std::vector<std::unique_ptr<Instruction> > constantsTypesGlobals;
  585. std::vector<std::unique_ptr<Instruction> > externals;
  586. std::vector<std::unique_ptr<Function> > functions;
  587. // not output, internally used for quick & dirty canonical (unique) creation
  588. std::unordered_map<unsigned int, std::vector<Instruction*>> groupedConstants; // map type opcodes to constant inst.
  589. std::unordered_map<unsigned int, std::vector<Instruction*>> groupedStructConstants; // map struct-id to constant instructions
  590. std::unordered_map<unsigned int, std::vector<Instruction*>> groupedTypes; // map type opcodes to type instructions
  591. // stack of switches
  592. std::stack<Block*> switchMerges;
  593. // Our loop stack.
  594. std::stack<LoopBlocks> loops;
  595. // The stream for outputting warnings and errors.
  596. SpvBuildLogger* logger;
  597. }; // end Builder class
  598. }; // end spv namespace
  599. #endif // SpvBuilder_H