SPVRemapper.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. //
  2. // Copyright (C) 2015 LunarG, Inc.
  3. //
  4. // All rights reserved.
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions
  8. // are met:
  9. //
  10. // Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. //
  13. // Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following
  15. // disclaimer in the documentation and/or other materials provided
  16. // with the distribution.
  17. //
  18. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  19. // contributors may be used to endorse or promote products derived
  20. // from this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  25. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  26. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  27. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  28. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  29. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  30. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  31. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  32. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. // POSSIBILITY OF SUCH DAMAGE.
  34. //
  35. #include "SPVRemapper.h"
  36. #include "doc.h"
  37. #if !defined (use_cpp11)
  38. // ... not supported before C++11
  39. #else // defined (use_cpp11)
  40. #include <algorithm>
  41. #include <cassert>
  42. #include "../glslang/Include/Common.h"
  43. namespace spv {
  44. // By default, just abort on error. Can be overridden via RegisterErrorHandler
  45. spirvbin_t::errorfn_t spirvbin_t::errorHandler = [](const std::string&) { exit(5); };
  46. // By default, eat log messages. Can be overridden via RegisterLogHandler
  47. spirvbin_t::logfn_t spirvbin_t::logHandler = [](const std::string&) { };
  48. // This can be overridden to provide other message behavior if needed
  49. void spirvbin_t::msg(int minVerbosity, int indent, const std::string& txt) const
  50. {
  51. if (verbose >= minVerbosity)
  52. logHandler(std::string(indent, ' ') + txt);
  53. }
  54. // hash opcode, with special handling for OpExtInst
  55. std::uint32_t spirvbin_t::asOpCodeHash(unsigned word)
  56. {
  57. const spv::Op opCode = asOpCode(word);
  58. std::uint32_t offset = 0;
  59. switch (opCode) {
  60. case spv::OpExtInst:
  61. offset += asId(word + 4); break;
  62. default:
  63. break;
  64. }
  65. return opCode * 19 + offset; // 19 = small prime
  66. }
  67. spirvbin_t::range_t spirvbin_t::literalRange(spv::Op opCode) const
  68. {
  69. static const int maxCount = 1<<30;
  70. switch (opCode) {
  71. case spv::OpTypeFloat: // fall through...
  72. case spv::OpTypePointer: return range_t(2, 3);
  73. case spv::OpTypeInt: return range_t(2, 4);
  74. // TODO: case spv::OpTypeImage:
  75. // TODO: case spv::OpTypeSampledImage:
  76. case spv::OpTypeSampler: return range_t(3, 8);
  77. case spv::OpTypeVector: // fall through
  78. case spv::OpTypeMatrix: // ...
  79. case spv::OpTypePipe: return range_t(3, 4);
  80. case spv::OpConstant: return range_t(3, maxCount);
  81. default: return range_t(0, 0);
  82. }
  83. }
  84. spirvbin_t::range_t spirvbin_t::typeRange(spv::Op opCode) const
  85. {
  86. static const int maxCount = 1<<30;
  87. if (isConstOp(opCode))
  88. return range_t(1, 2);
  89. switch (opCode) {
  90. case spv::OpTypeVector: // fall through
  91. case spv::OpTypeMatrix: // ...
  92. case spv::OpTypeSampler: // ...
  93. case spv::OpTypeArray: // ...
  94. case spv::OpTypeRuntimeArray: // ...
  95. case spv::OpTypePipe: return range_t(2, 3);
  96. case spv::OpTypeStruct: // fall through
  97. case spv::OpTypeFunction: return range_t(2, maxCount);
  98. case spv::OpTypePointer: return range_t(3, 4);
  99. default: return range_t(0, 0);
  100. }
  101. }
  102. spirvbin_t::range_t spirvbin_t::constRange(spv::Op opCode) const
  103. {
  104. static const int maxCount = 1<<30;
  105. switch (opCode) {
  106. case spv::OpTypeArray: // fall through...
  107. case spv::OpTypeRuntimeArray: return range_t(3, 4);
  108. case spv::OpConstantComposite: return range_t(3, maxCount);
  109. default: return range_t(0, 0);
  110. }
  111. }
  112. // Return the size of a type in 32-bit words. This currently only
  113. // handles ints and floats, and is only invoked by queries which must be
  114. // integer types. If ever needed, it can be generalized.
  115. unsigned spirvbin_t::typeSizeInWords(spv::Id id) const
  116. {
  117. const unsigned typeStart = idPos(id);
  118. const spv::Op opCode = asOpCode(typeStart);
  119. if (errorLatch)
  120. return 0;
  121. switch (opCode) {
  122. case spv::OpTypeInt: // fall through...
  123. case spv::OpTypeFloat: return (spv[typeStart+2]+31)/32;
  124. default:
  125. return 0;
  126. }
  127. }
  128. // Looks up the type of a given const or variable ID, and
  129. // returns its size in 32-bit words.
  130. unsigned spirvbin_t::idTypeSizeInWords(spv::Id id) const
  131. {
  132. const auto tid_it = idTypeSizeMap.find(id);
  133. if (tid_it == idTypeSizeMap.end()) {
  134. error("type size for ID not found");
  135. return 0;
  136. }
  137. return tid_it->second;
  138. }
  139. // Is this an opcode we should remove when using --strip?
  140. bool spirvbin_t::isStripOp(spv::Op opCode) const
  141. {
  142. switch (opCode) {
  143. case spv::OpSource:
  144. case spv::OpSourceExtension:
  145. case spv::OpName:
  146. case spv::OpMemberName:
  147. case spv::OpLine: return true;
  148. default: return false;
  149. }
  150. }
  151. // Return true if this opcode is flow control
  152. bool spirvbin_t::isFlowCtrl(spv::Op opCode) const
  153. {
  154. switch (opCode) {
  155. case spv::OpBranchConditional:
  156. case spv::OpBranch:
  157. case spv::OpSwitch:
  158. case spv::OpLoopMerge:
  159. case spv::OpSelectionMerge:
  160. case spv::OpLabel:
  161. case spv::OpFunction:
  162. case spv::OpFunctionEnd: return true;
  163. default: return false;
  164. }
  165. }
  166. // Return true if this opcode defines a type
  167. bool spirvbin_t::isTypeOp(spv::Op opCode) const
  168. {
  169. switch (opCode) {
  170. case spv::OpTypeVoid:
  171. case spv::OpTypeBool:
  172. case spv::OpTypeInt:
  173. case spv::OpTypeFloat:
  174. case spv::OpTypeVector:
  175. case spv::OpTypeMatrix:
  176. case spv::OpTypeImage:
  177. case spv::OpTypeSampler:
  178. case spv::OpTypeArray:
  179. case spv::OpTypeRuntimeArray:
  180. case spv::OpTypeStruct:
  181. case spv::OpTypeOpaque:
  182. case spv::OpTypePointer:
  183. case spv::OpTypeFunction:
  184. case spv::OpTypeEvent:
  185. case spv::OpTypeDeviceEvent:
  186. case spv::OpTypeReserveId:
  187. case spv::OpTypeQueue:
  188. case spv::OpTypeSampledImage:
  189. case spv::OpTypePipe: return true;
  190. default: return false;
  191. }
  192. }
  193. // Return true if this opcode defines a constant
  194. bool spirvbin_t::isConstOp(spv::Op opCode) const
  195. {
  196. switch (opCode) {
  197. case spv::OpConstantSampler:
  198. error("unimplemented constant type");
  199. return true;
  200. case spv::OpConstantNull:
  201. case spv::OpConstantTrue:
  202. case spv::OpConstantFalse:
  203. case spv::OpConstantComposite:
  204. case spv::OpConstant:
  205. return true;
  206. default:
  207. return false;
  208. }
  209. }
  210. const auto inst_fn_nop = [](spv::Op, unsigned) { return false; };
  211. const auto op_fn_nop = [](spv::Id&) { };
  212. // g++ doesn't like these defined in the class proper in an anonymous namespace.
  213. // Dunno why. Also MSVC doesn't like the constexpr keyword. Also dunno why.
  214. // Defining them externally seems to please both compilers, so, here they are.
  215. const spv::Id spirvbin_t::unmapped = spv::Id(-10000);
  216. const spv::Id spirvbin_t::unused = spv::Id(-10001);
  217. const int spirvbin_t::header_size = 5;
  218. spv::Id spirvbin_t::nextUnusedId(spv::Id id)
  219. {
  220. while (isNewIdMapped(id)) // search for an unused ID
  221. ++id;
  222. return id;
  223. }
  224. spv::Id spirvbin_t::localId(spv::Id id, spv::Id newId)
  225. {
  226. //assert(id != spv::NoResult && newId != spv::NoResult);
  227. if (id > bound()) {
  228. error(std::string("ID out of range: ") + std::to_string(id));
  229. return spirvbin_t::unused;
  230. }
  231. if (id >= idMapL.size())
  232. idMapL.resize(id+1, unused);
  233. if (newId != unmapped && newId != unused) {
  234. if (isOldIdUnused(id)) {
  235. error(std::string("ID unused in module: ") + std::to_string(id));
  236. return spirvbin_t::unused;
  237. }
  238. if (!isOldIdUnmapped(id)) {
  239. error(std::string("ID already mapped: ") + std::to_string(id) + " -> "
  240. + std::to_string(localId(id)));
  241. return spirvbin_t::unused;
  242. }
  243. if (isNewIdMapped(newId)) {
  244. error(std::string("ID already used in module: ") + std::to_string(newId));
  245. return spirvbin_t::unused;
  246. }
  247. msg(4, 4, std::string("map: ") + std::to_string(id) + " -> " + std::to_string(newId));
  248. setMapped(newId);
  249. largestNewId = std::max(largestNewId, newId);
  250. }
  251. return idMapL[id] = newId;
  252. }
  253. // Parse a literal string from the SPIR binary and return it as an std::string
  254. // Due to C++11 RValue references, this doesn't copy the result string.
  255. std::string spirvbin_t::literalString(unsigned word) const
  256. {
  257. std::string literal;
  258. literal.reserve(16);
  259. const char* bytes = reinterpret_cast<const char*>(spv.data() + word);
  260. while (bytes && *bytes)
  261. literal += *bytes++;
  262. return literal;
  263. }
  264. void spirvbin_t::applyMap()
  265. {
  266. msg(3, 2, std::string("Applying map: "));
  267. // Map local IDs through the ID map
  268. process(inst_fn_nop, // ignore instructions
  269. [this](spv::Id& id) {
  270. id = localId(id);
  271. if (errorLatch)
  272. return;
  273. assert(id != unused && id != unmapped);
  274. }
  275. );
  276. }
  277. // Find free IDs for anything we haven't mapped
  278. void spirvbin_t::mapRemainder()
  279. {
  280. msg(3, 2, std::string("Remapping remainder: "));
  281. spv::Id unusedId = 1; // can't use 0: that's NoResult
  282. spirword_t maxBound = 0;
  283. for (spv::Id id = 0; id < idMapL.size(); ++id) {
  284. if (isOldIdUnused(id))
  285. continue;
  286. // Find a new mapping for any used but unmapped IDs
  287. if (isOldIdUnmapped(id)) {
  288. localId(id, unusedId = nextUnusedId(unusedId));
  289. if (errorLatch)
  290. return;
  291. }
  292. if (isOldIdUnmapped(id)) {
  293. error(std::string("old ID not mapped: ") + std::to_string(id));
  294. return;
  295. }
  296. // Track max bound
  297. maxBound = std::max(maxBound, localId(id) + 1);
  298. if (errorLatch)
  299. return;
  300. }
  301. bound(maxBound); // reset header ID bound to as big as it now needs to be
  302. }
  303. // Mark debug instructions for stripping
  304. void spirvbin_t::stripDebug()
  305. {
  306. // Strip instructions in the stripOp set: debug info.
  307. process(
  308. [&](spv::Op opCode, unsigned start) {
  309. // remember opcodes we want to strip later
  310. if (isStripOp(opCode))
  311. stripInst(start);
  312. return true;
  313. },
  314. op_fn_nop);
  315. }
  316. // Mark instructions that refer to now-removed IDs for stripping
  317. void spirvbin_t::stripDeadRefs()
  318. {
  319. process(
  320. [&](spv::Op opCode, unsigned start) {
  321. // strip opcodes pointing to removed data
  322. switch (opCode) {
  323. case spv::OpName:
  324. case spv::OpMemberName:
  325. case spv::OpDecorate:
  326. case spv::OpMemberDecorate:
  327. if (idPosR.find(asId(start+1)) == idPosR.end())
  328. stripInst(start);
  329. break;
  330. default:
  331. break; // leave it alone
  332. }
  333. return true;
  334. },
  335. op_fn_nop);
  336. strip();
  337. }
  338. // Update local maps of ID, type, etc positions
  339. void spirvbin_t::buildLocalMaps()
  340. {
  341. msg(2, 2, std::string("build local maps: "));
  342. mapped.clear();
  343. idMapL.clear();
  344. // preserve nameMap, so we don't clear that.
  345. fnPos.clear();
  346. fnCalls.clear();
  347. typeConstPos.clear();
  348. idPosR.clear();
  349. entryPoint = spv::NoResult;
  350. largestNewId = 0;
  351. idMapL.resize(bound(), unused);
  352. int fnStart = 0;
  353. spv::Id fnRes = spv::NoResult;
  354. // build local Id and name maps
  355. process(
  356. [&](spv::Op opCode, unsigned start) {
  357. unsigned word = start+1;
  358. spv::Id typeId = spv::NoResult;
  359. if (spv::InstructionDesc[opCode].hasType())
  360. typeId = asId(word++);
  361. // If there's a result ID, remember the size of its type
  362. if (spv::InstructionDesc[opCode].hasResult()) {
  363. const spv::Id resultId = asId(word++);
  364. idPosR[resultId] = start;
  365. if (typeId != spv::NoResult) {
  366. const unsigned idTypeSize = typeSizeInWords(typeId);
  367. if (errorLatch)
  368. return false;
  369. if (idTypeSize != 0)
  370. idTypeSizeMap[resultId] = idTypeSize;
  371. }
  372. }
  373. if (opCode == spv::Op::OpName) {
  374. const spv::Id target = asId(start+1);
  375. const std::string name = literalString(start+2);
  376. nameMap[name] = target;
  377. } else if (opCode == spv::Op::OpFunctionCall) {
  378. ++fnCalls[asId(start + 3)];
  379. } else if (opCode == spv::Op::OpEntryPoint) {
  380. entryPoint = asId(start + 2);
  381. } else if (opCode == spv::Op::OpFunction) {
  382. if (fnStart != 0) {
  383. error("nested function found");
  384. return false;
  385. }
  386. fnStart = start;
  387. fnRes = asId(start + 2);
  388. } else if (opCode == spv::Op::OpFunctionEnd) {
  389. assert(fnRes != spv::NoResult);
  390. if (fnStart == 0) {
  391. error("function end without function start");
  392. return false;
  393. }
  394. fnPos[fnRes] = range_t(fnStart, start + asWordCount(start));
  395. fnStart = 0;
  396. } else if (isConstOp(opCode)) {
  397. if (errorLatch)
  398. return false;
  399. assert(asId(start + 2) != spv::NoResult);
  400. typeConstPos.insert(start);
  401. } else if (isTypeOp(opCode)) {
  402. assert(asId(start + 1) != spv::NoResult);
  403. typeConstPos.insert(start);
  404. }
  405. return false;
  406. },
  407. [this](spv::Id& id) { localId(id, unmapped); }
  408. );
  409. }
  410. // Validate the SPIR header
  411. void spirvbin_t::validate() const
  412. {
  413. msg(2, 2, std::string("validating: "));
  414. if (spv.size() < header_size) {
  415. error("file too short: ");
  416. return;
  417. }
  418. if (magic() != spv::MagicNumber) {
  419. error("bad magic number");
  420. return;
  421. }
  422. // field 1 = version
  423. // field 2 = generator magic
  424. // field 3 = result <id> bound
  425. if (schemaNum() != 0) {
  426. error("bad schema, must be 0");
  427. return;
  428. }
  429. }
  430. int spirvbin_t::processInstruction(unsigned word, instfn_t instFn, idfn_t idFn)
  431. {
  432. const auto instructionStart = word;
  433. const unsigned wordCount = asWordCount(instructionStart);
  434. const int nextInst = word++ + wordCount;
  435. spv::Op opCode = asOpCode(instructionStart);
  436. if (nextInst > int(spv.size())) {
  437. error("spir instruction terminated too early");
  438. return -1;
  439. }
  440. // Base for computing number of operands; will be updated as more is learned
  441. unsigned numOperands = wordCount - 1;
  442. if (instFn(opCode, instructionStart))
  443. return nextInst;
  444. // Read type and result ID from instruction desc table
  445. if (spv::InstructionDesc[opCode].hasType()) {
  446. idFn(asId(word++));
  447. --numOperands;
  448. }
  449. if (spv::InstructionDesc[opCode].hasResult()) {
  450. idFn(asId(word++));
  451. --numOperands;
  452. }
  453. // Extended instructions: currently, assume everything is an ID.
  454. // TODO: add whatever data we need for exceptions to that
  455. if (opCode == spv::OpExtInst) {
  456. word += 2; // instruction set, and instruction from set
  457. numOperands -= 2;
  458. for (unsigned op=0; op < numOperands; ++op)
  459. idFn(asId(word++)); // ID
  460. return nextInst;
  461. }
  462. // Circular buffer so we can look back at previous unmapped values during the mapping pass.
  463. static const unsigned idBufferSize = 4;
  464. spv::Id idBuffer[idBufferSize];
  465. unsigned idBufferPos = 0;
  466. // Store IDs from instruction in our map
  467. for (int op = 0; numOperands > 0; ++op, --numOperands) {
  468. // SpecConstantOp is special: it includes the operands of another opcode which is
  469. // given as a literal in the 3rd word. We will switch over to pretending that the
  470. // opcode being processed is the literal opcode value of the SpecConstantOp. See the
  471. // SPIRV spec for details. This way we will handle IDs and literals as appropriate for
  472. // the embedded op.
  473. if (opCode == spv::OpSpecConstantOp) {
  474. if (op == 0) {
  475. opCode = asOpCode(word++); // this is the opcode embedded in the SpecConstantOp.
  476. --numOperands;
  477. }
  478. }
  479. switch (spv::InstructionDesc[opCode].operands.getClass(op)) {
  480. case spv::OperandId:
  481. case spv::OperandScope:
  482. case spv::OperandMemorySemantics:
  483. idBuffer[idBufferPos] = asId(word);
  484. idBufferPos = (idBufferPos + 1) % idBufferSize;
  485. idFn(asId(word++));
  486. break;
  487. case spv::OperandVariableIds:
  488. for (unsigned i = 0; i < numOperands; ++i)
  489. idFn(asId(word++));
  490. return nextInst;
  491. case spv::OperandVariableLiterals:
  492. // for clarity
  493. // if (opCode == spv::OpDecorate && asDecoration(word - 1) == spv::DecorationBuiltIn) {
  494. // ++word;
  495. // --numOperands;
  496. // }
  497. // word += numOperands;
  498. return nextInst;
  499. case spv::OperandVariableLiteralId: {
  500. if (opCode == OpSwitch) {
  501. // word-2 is the position of the selector ID. OpSwitch Literals match its type.
  502. // In case the IDs are currently being remapped, we get the word[-2] ID from
  503. // the circular idBuffer.
  504. const unsigned literalSizePos = (idBufferPos+idBufferSize-2) % idBufferSize;
  505. const unsigned literalSize = idTypeSizeInWords(idBuffer[literalSizePos]);
  506. const unsigned numLiteralIdPairs = (nextInst-word) / (1+literalSize);
  507. if (errorLatch)
  508. return -1;
  509. for (unsigned arg=0; arg<numLiteralIdPairs; ++arg) {
  510. word += literalSize; // literal
  511. idFn(asId(word++)); // label
  512. }
  513. } else {
  514. assert(0); // currentely, only OpSwitch uses OperandVariableLiteralId
  515. }
  516. return nextInst;
  517. }
  518. case spv::OperandLiteralString: {
  519. const int stringWordCount = literalStringWords(literalString(word));
  520. word += stringWordCount;
  521. numOperands -= (stringWordCount-1); // -1 because for() header post-decrements
  522. break;
  523. }
  524. // Execution mode might have extra literal operands. Skip them.
  525. case spv::OperandExecutionMode:
  526. return nextInst;
  527. // Single word operands we simply ignore, as they hold no IDs
  528. case spv::OperandLiteralNumber:
  529. case spv::OperandSource:
  530. case spv::OperandExecutionModel:
  531. case spv::OperandAddressing:
  532. case spv::OperandMemory:
  533. case spv::OperandStorage:
  534. case spv::OperandDimensionality:
  535. case spv::OperandSamplerAddressingMode:
  536. case spv::OperandSamplerFilterMode:
  537. case spv::OperandSamplerImageFormat:
  538. case spv::OperandImageChannelOrder:
  539. case spv::OperandImageChannelDataType:
  540. case spv::OperandImageOperands:
  541. case spv::OperandFPFastMath:
  542. case spv::OperandFPRoundingMode:
  543. case spv::OperandLinkageType:
  544. case spv::OperandAccessQualifier:
  545. case spv::OperandFuncParamAttr:
  546. case spv::OperandDecoration:
  547. case spv::OperandBuiltIn:
  548. case spv::OperandSelect:
  549. case spv::OperandLoop:
  550. case spv::OperandFunction:
  551. case spv::OperandMemoryAccess:
  552. case spv::OperandGroupOperation:
  553. case spv::OperandKernelEnqueueFlags:
  554. case spv::OperandKernelProfilingInfo:
  555. case spv::OperandCapability:
  556. ++word;
  557. break;
  558. default:
  559. assert(0 && "Unhandled Operand Class");
  560. break;
  561. }
  562. }
  563. return nextInst;
  564. }
  565. // Make a pass over all the instructions and process them given appropriate functions
  566. spirvbin_t& spirvbin_t::process(instfn_t instFn, idfn_t idFn, unsigned begin, unsigned end)
  567. {
  568. // For efficiency, reserve name map space. It can grow if needed.
  569. nameMap.reserve(32);
  570. // If begin or end == 0, use defaults
  571. begin = (begin == 0 ? header_size : begin);
  572. end = (end == 0 ? unsigned(spv.size()) : end);
  573. // basic parsing and InstructionDesc table borrowed from SpvDisassemble.cpp...
  574. unsigned nextInst = unsigned(spv.size());
  575. for (unsigned word = begin; word < end; word = nextInst) {
  576. nextInst = processInstruction(word, instFn, idFn);
  577. if (errorLatch)
  578. return *this;
  579. }
  580. return *this;
  581. }
  582. // Apply global name mapping to a single module
  583. void spirvbin_t::mapNames()
  584. {
  585. static const std::uint32_t softTypeIdLimit = 3011; // small prime. TODO: get from options
  586. static const std::uint32_t firstMappedID = 3019; // offset into ID space
  587. for (const auto& name : nameMap) {
  588. std::uint32_t hashval = 1911;
  589. for (const char c : name.first)
  590. hashval = hashval * 1009 + c;
  591. if (isOldIdUnmapped(name.second)) {
  592. localId(name.second, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  593. if (errorLatch)
  594. return;
  595. }
  596. }
  597. }
  598. // Map fn contents to IDs of similar functions in other modules
  599. void spirvbin_t::mapFnBodies()
  600. {
  601. static const std::uint32_t softTypeIdLimit = 19071; // small prime. TODO: get from options
  602. static const std::uint32_t firstMappedID = 6203; // offset into ID space
  603. // Initial approach: go through some high priority opcodes first and assign them
  604. // hash values.
  605. spv::Id fnId = spv::NoResult;
  606. std::vector<unsigned> instPos;
  607. instPos.reserve(unsigned(spv.size()) / 16); // initial estimate; can grow if needed.
  608. // Build local table of instruction start positions
  609. process(
  610. [&](spv::Op, unsigned start) { instPos.push_back(start); return true; },
  611. op_fn_nop);
  612. if (errorLatch)
  613. return;
  614. // Window size for context-sensitive canonicalization values
  615. // Empirical best size from a single data set. TODO: Would be a good tunable.
  616. // We essentially perform a little convolution around each instruction,
  617. // to capture the flavor of nearby code, to hopefully match to similar
  618. // code in other modules.
  619. static const unsigned windowSize = 2;
  620. for (unsigned entry = 0; entry < unsigned(instPos.size()); ++entry) {
  621. const unsigned start = instPos[entry];
  622. const spv::Op opCode = asOpCode(start);
  623. if (opCode == spv::OpFunction)
  624. fnId = asId(start + 2);
  625. if (opCode == spv::OpFunctionEnd)
  626. fnId = spv::NoResult;
  627. if (fnId != spv::NoResult) { // if inside a function
  628. if (spv::InstructionDesc[opCode].hasResult()) {
  629. const unsigned word = start + (spv::InstructionDesc[opCode].hasType() ? 2 : 1);
  630. const spv::Id resId = asId(word);
  631. std::uint32_t hashval = fnId * 17; // small prime
  632. for (unsigned i = entry-1; i >= entry-windowSize; --i) {
  633. if (asOpCode(instPos[i]) == spv::OpFunction)
  634. break;
  635. hashval = hashval * 30103 + asOpCodeHash(instPos[i]); // 30103 = semiarbitrary prime
  636. }
  637. for (unsigned i = entry; i <= entry + windowSize; ++i) {
  638. if (asOpCode(instPos[i]) == spv::OpFunctionEnd)
  639. break;
  640. hashval = hashval * 30103 + asOpCodeHash(instPos[i]); // 30103 = semiarbitrary prime
  641. }
  642. if (isOldIdUnmapped(resId)) {
  643. localId(resId, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  644. if (errorLatch)
  645. return;
  646. }
  647. }
  648. }
  649. }
  650. spv::Op thisOpCode(spv::OpNop);
  651. std::unordered_map<int, int> opCounter;
  652. int idCounter(0);
  653. fnId = spv::NoResult;
  654. process(
  655. [&](spv::Op opCode, unsigned start) {
  656. switch (opCode) {
  657. case spv::OpFunction:
  658. // Reset counters at each function
  659. idCounter = 0;
  660. opCounter.clear();
  661. fnId = asId(start + 2);
  662. break;
  663. case spv::OpImageSampleImplicitLod:
  664. case spv::OpImageSampleExplicitLod:
  665. case spv::OpImageSampleDrefImplicitLod:
  666. case spv::OpImageSampleDrefExplicitLod:
  667. case spv::OpImageSampleProjImplicitLod:
  668. case spv::OpImageSampleProjExplicitLod:
  669. case spv::OpImageSampleProjDrefImplicitLod:
  670. case spv::OpImageSampleProjDrefExplicitLod:
  671. case spv::OpDot:
  672. case spv::OpCompositeExtract:
  673. case spv::OpCompositeInsert:
  674. case spv::OpVectorShuffle:
  675. case spv::OpLabel:
  676. case spv::OpVariable:
  677. case spv::OpAccessChain:
  678. case spv::OpLoad:
  679. case spv::OpStore:
  680. case spv::OpCompositeConstruct:
  681. case spv::OpFunctionCall:
  682. ++opCounter[opCode];
  683. idCounter = 0;
  684. thisOpCode = opCode;
  685. break;
  686. default:
  687. thisOpCode = spv::OpNop;
  688. }
  689. return false;
  690. },
  691. [&](spv::Id& id) {
  692. if (thisOpCode != spv::OpNop) {
  693. ++idCounter;
  694. const std::uint32_t hashval = opCounter[thisOpCode] * thisOpCode * 50047 + idCounter + fnId * 117;
  695. if (isOldIdUnmapped(id))
  696. localId(id, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  697. }
  698. });
  699. }
  700. // EXPERIMENTAL: forward IO and uniform load/stores into operands
  701. // This produces invalid Schema-0 SPIRV
  702. void spirvbin_t::forwardLoadStores()
  703. {
  704. idset_t fnLocalVars; // set of function local vars
  705. idmap_t idMap; // Map of load result IDs to what they load
  706. // EXPERIMENTAL: Forward input and access chain loads into consumptions
  707. process(
  708. [&](spv::Op opCode, unsigned start) {
  709. // Add inputs and uniforms to the map
  710. if ((opCode == spv::OpVariable && asWordCount(start) == 4) &&
  711. (spv[start+3] == spv::StorageClassUniform ||
  712. spv[start+3] == spv::StorageClassUniformConstant ||
  713. spv[start+3] == spv::StorageClassInput))
  714. fnLocalVars.insert(asId(start+2));
  715. if (opCode == spv::OpAccessChain && fnLocalVars.count(asId(start+3)) > 0)
  716. fnLocalVars.insert(asId(start+2));
  717. if (opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0) {
  718. idMap[asId(start+2)] = asId(start+3);
  719. stripInst(start);
  720. }
  721. return false;
  722. },
  723. [&](spv::Id& id) { if (idMap.find(id) != idMap.end()) id = idMap[id]; }
  724. );
  725. if (errorLatch)
  726. return;
  727. // EXPERIMENTAL: Implicit output stores
  728. fnLocalVars.clear();
  729. idMap.clear();
  730. process(
  731. [&](spv::Op opCode, unsigned start) {
  732. // Add inputs and uniforms to the map
  733. if ((opCode == spv::OpVariable && asWordCount(start) == 4) &&
  734. (spv[start+3] == spv::StorageClassOutput))
  735. fnLocalVars.insert(asId(start+2));
  736. if (opCode == spv::OpStore && fnLocalVars.count(asId(start+1)) > 0) {
  737. idMap[asId(start+2)] = asId(start+1);
  738. stripInst(start);
  739. }
  740. return false;
  741. },
  742. op_fn_nop);
  743. if (errorLatch)
  744. return;
  745. process(
  746. inst_fn_nop,
  747. [&](spv::Id& id) { if (idMap.find(id) != idMap.end()) id = idMap[id]; }
  748. );
  749. if (errorLatch)
  750. return;
  751. strip(); // strip out data we decided to eliminate
  752. }
  753. // optimize loads and stores
  754. void spirvbin_t::optLoadStore()
  755. {
  756. idset_t fnLocalVars; // candidates for removal (only locals)
  757. idmap_t idMap; // Map of load result IDs to what they load
  758. blockmap_t blockMap; // Map of IDs to blocks they first appear in
  759. int blockNum = 0; // block count, to avoid crossing flow control
  760. // Find all the function local pointers stored at most once, and not via access chains
  761. process(
  762. [&](spv::Op opCode, unsigned start) {
  763. const int wordCount = asWordCount(start);
  764. // Count blocks, so we can avoid crossing flow control
  765. if (isFlowCtrl(opCode))
  766. ++blockNum;
  767. // Add local variables to the map
  768. if ((opCode == spv::OpVariable && spv[start+3] == spv::StorageClassFunction && asWordCount(start) == 4)) {
  769. fnLocalVars.insert(asId(start+2));
  770. return true;
  771. }
  772. // Ignore process vars referenced via access chain
  773. if ((opCode == spv::OpAccessChain || opCode == spv::OpInBoundsAccessChain) && fnLocalVars.count(asId(start+3)) > 0) {
  774. fnLocalVars.erase(asId(start+3));
  775. idMap.erase(asId(start+3));
  776. return true;
  777. }
  778. if (opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0) {
  779. const spv::Id varId = asId(start+3);
  780. // Avoid loads before stores
  781. if (idMap.find(varId) == idMap.end()) {
  782. fnLocalVars.erase(varId);
  783. idMap.erase(varId);
  784. }
  785. // don't do for volatile references
  786. if (wordCount > 4 && (spv[start+4] & spv::MemoryAccessVolatileMask)) {
  787. fnLocalVars.erase(varId);
  788. idMap.erase(varId);
  789. }
  790. // Handle flow control
  791. if (blockMap.find(varId) == blockMap.end()) {
  792. blockMap[varId] = blockNum; // track block we found it in.
  793. } else if (blockMap[varId] != blockNum) {
  794. fnLocalVars.erase(varId); // Ignore if crosses flow control
  795. idMap.erase(varId);
  796. }
  797. return true;
  798. }
  799. if (opCode == spv::OpStore && fnLocalVars.count(asId(start+1)) > 0) {
  800. const spv::Id varId = asId(start+1);
  801. if (idMap.find(varId) == idMap.end()) {
  802. idMap[varId] = asId(start+2);
  803. } else {
  804. // Remove if it has more than one store to the same pointer
  805. fnLocalVars.erase(varId);
  806. idMap.erase(varId);
  807. }
  808. // don't do for volatile references
  809. if (wordCount > 3 && (spv[start+3] & spv::MemoryAccessVolatileMask)) {
  810. fnLocalVars.erase(asId(start+3));
  811. idMap.erase(asId(start+3));
  812. }
  813. // Handle flow control
  814. if (blockMap.find(varId) == blockMap.end()) {
  815. blockMap[varId] = blockNum; // track block we found it in.
  816. } else if (blockMap[varId] != blockNum) {
  817. fnLocalVars.erase(varId); // Ignore if crosses flow control
  818. idMap.erase(varId);
  819. }
  820. return true;
  821. }
  822. return false;
  823. },
  824. // If local var id used anywhere else, don't eliminate
  825. [&](spv::Id& id) {
  826. if (fnLocalVars.count(id) > 0) {
  827. fnLocalVars.erase(id);
  828. idMap.erase(id);
  829. }
  830. }
  831. );
  832. if (errorLatch)
  833. return;
  834. process(
  835. [&](spv::Op opCode, unsigned start) {
  836. if (opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0)
  837. idMap[asId(start+2)] = idMap[asId(start+3)];
  838. return false;
  839. },
  840. op_fn_nop);
  841. if (errorLatch)
  842. return;
  843. // Chase replacements to their origins, in case there is a chain such as:
  844. // 2 = store 1
  845. // 3 = load 2
  846. // 4 = store 3
  847. // 5 = load 4
  848. // We want to replace uses of 5 with 1.
  849. for (const auto& idPair : idMap) {
  850. spv::Id id = idPair.first;
  851. while (idMap.find(id) != idMap.end()) // Chase to end of chain
  852. id = idMap[id];
  853. idMap[idPair.first] = id; // replace with final result
  854. }
  855. // Remove the load/store/variables for the ones we've discovered
  856. process(
  857. [&](spv::Op opCode, unsigned start) {
  858. if ((opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0) ||
  859. (opCode == spv::OpStore && fnLocalVars.count(asId(start+1)) > 0) ||
  860. (opCode == spv::OpVariable && fnLocalVars.count(asId(start+2)) > 0)) {
  861. stripInst(start);
  862. return true;
  863. }
  864. return false;
  865. },
  866. [&](spv::Id& id) {
  867. if (idMap.find(id) != idMap.end()) id = idMap[id];
  868. }
  869. );
  870. if (errorLatch)
  871. return;
  872. strip(); // strip out data we decided to eliminate
  873. }
  874. // remove bodies of uncalled functions
  875. void spirvbin_t::dceFuncs()
  876. {
  877. msg(3, 2, std::string("Removing Dead Functions: "));
  878. // TODO: There are more efficient ways to do this.
  879. bool changed = true;
  880. while (changed) {
  881. changed = false;
  882. for (auto fn = fnPos.begin(); fn != fnPos.end(); ) {
  883. if (fn->first == entryPoint) { // don't DCE away the entry point!
  884. ++fn;
  885. continue;
  886. }
  887. const auto call_it = fnCalls.find(fn->first);
  888. if (call_it == fnCalls.end() || call_it->second == 0) {
  889. changed = true;
  890. stripRange.push_back(fn->second);
  891. // decrease counts of called functions
  892. process(
  893. [&](spv::Op opCode, unsigned start) {
  894. if (opCode == spv::Op::OpFunctionCall) {
  895. const auto call_it = fnCalls.find(asId(start + 3));
  896. if (call_it != fnCalls.end()) {
  897. if (--call_it->second <= 0)
  898. fnCalls.erase(call_it);
  899. }
  900. }
  901. return true;
  902. },
  903. op_fn_nop,
  904. fn->second.first,
  905. fn->second.second);
  906. if (errorLatch)
  907. return;
  908. fn = fnPos.erase(fn);
  909. } else ++fn;
  910. }
  911. }
  912. }
  913. // remove unused function variables + decorations
  914. void spirvbin_t::dceVars()
  915. {
  916. msg(3, 2, std::string("DCE Vars: "));
  917. std::unordered_map<spv::Id, int> varUseCount;
  918. // Count function variable use
  919. process(
  920. [&](spv::Op opCode, unsigned start) {
  921. if (opCode == spv::OpVariable) {
  922. ++varUseCount[asId(start+2)];
  923. return true;
  924. } else if (opCode == spv::OpEntryPoint) {
  925. const int wordCount = asWordCount(start);
  926. for (int i = 4; i < wordCount; i++) {
  927. ++varUseCount[asId(start+i)];
  928. }
  929. return true;
  930. } else
  931. return false;
  932. },
  933. [&](spv::Id& id) { if (varUseCount[id]) ++varUseCount[id]; }
  934. );
  935. if (errorLatch)
  936. return;
  937. // Remove single-use function variables + associated decorations and names
  938. process(
  939. [&](spv::Op opCode, unsigned start) {
  940. spv::Id id = spv::NoResult;
  941. if (opCode == spv::OpVariable)
  942. id = asId(start+2);
  943. if (opCode == spv::OpDecorate || opCode == spv::OpName)
  944. id = asId(start+1);
  945. if (id != spv::NoResult && varUseCount[id] == 1)
  946. stripInst(start);
  947. return true;
  948. },
  949. op_fn_nop);
  950. }
  951. // remove unused types
  952. void spirvbin_t::dceTypes()
  953. {
  954. std::vector<bool> isType(bound(), false);
  955. // for speed, make O(1) way to get to type query (map is log(n))
  956. for (const auto typeStart : typeConstPos)
  957. isType[asTypeConstId(typeStart)] = true;
  958. std::unordered_map<spv::Id, int> typeUseCount;
  959. // This is not the most efficient algorithm, but this is an offline tool, and
  960. // it's easy to write this way. Can be improved opportunistically if needed.
  961. bool changed = true;
  962. while (changed) {
  963. changed = false;
  964. strip();
  965. typeUseCount.clear();
  966. // Count total type usage
  967. process(inst_fn_nop,
  968. [&](spv::Id& id) { if (isType[id]) ++typeUseCount[id]; }
  969. );
  970. if (errorLatch)
  971. return;
  972. // Remove single reference types
  973. for (const auto typeStart : typeConstPos) {
  974. const spv::Id typeId = asTypeConstId(typeStart);
  975. if (typeUseCount[typeId] == 1) {
  976. changed = true;
  977. --typeUseCount[typeId];
  978. stripInst(typeStart);
  979. }
  980. }
  981. if (errorLatch)
  982. return;
  983. }
  984. }
  985. #ifdef NOTDEF
  986. bool spirvbin_t::matchType(const spirvbin_t::globaltypes_t& globalTypes, spv::Id lt, spv::Id gt) const
  987. {
  988. // Find the local type id "lt" and global type id "gt"
  989. const auto lt_it = typeConstPosR.find(lt);
  990. if (lt_it == typeConstPosR.end())
  991. return false;
  992. const auto typeStart = lt_it->second;
  993. // Search for entry in global table
  994. const auto gtype = globalTypes.find(gt);
  995. if (gtype == globalTypes.end())
  996. return false;
  997. const auto& gdata = gtype->second;
  998. // local wordcount and opcode
  999. const int wordCount = asWordCount(typeStart);
  1000. const spv::Op opCode = asOpCode(typeStart);
  1001. // no type match if opcodes don't match, or operand count doesn't match
  1002. if (opCode != opOpCode(gdata[0]) || wordCount != opWordCount(gdata[0]))
  1003. return false;
  1004. const unsigned numOperands = wordCount - 2; // all types have a result
  1005. const auto cmpIdRange = [&](range_t range) {
  1006. for (int x=range.first; x<std::min(range.second, wordCount); ++x)
  1007. if (!matchType(globalTypes, asId(typeStart+x), gdata[x]))
  1008. return false;
  1009. return true;
  1010. };
  1011. const auto cmpConst = [&]() { return cmpIdRange(constRange(opCode)); };
  1012. const auto cmpSubType = [&]() { return cmpIdRange(typeRange(opCode)); };
  1013. // Compare literals in range [start,end)
  1014. const auto cmpLiteral = [&]() {
  1015. const auto range = literalRange(opCode);
  1016. return std::equal(spir.begin() + typeStart + range.first,
  1017. spir.begin() + typeStart + std::min(range.second, wordCount),
  1018. gdata.begin() + range.first);
  1019. };
  1020. assert(isTypeOp(opCode) || isConstOp(opCode));
  1021. switch (opCode) {
  1022. case spv::OpTypeOpaque: // TODO: disable until we compare the literal strings.
  1023. case spv::OpTypeQueue: return false;
  1024. case spv::OpTypeEvent: // fall through...
  1025. case spv::OpTypeDeviceEvent: // ...
  1026. case spv::OpTypeReserveId: return false;
  1027. // for samplers, we don't handle the optional parameters yet
  1028. case spv::OpTypeSampler: return cmpLiteral() && cmpConst() && cmpSubType() && wordCount == 8;
  1029. default: return cmpLiteral() && cmpConst() && cmpSubType();
  1030. }
  1031. }
  1032. // Look for an equivalent type in the globalTypes map
  1033. spv::Id spirvbin_t::findType(const spirvbin_t::globaltypes_t& globalTypes, spv::Id lt) const
  1034. {
  1035. // Try a recursive type match on each in turn, and return a match if we find one
  1036. for (const auto& gt : globalTypes)
  1037. if (matchType(globalTypes, lt, gt.first))
  1038. return gt.first;
  1039. return spv::NoType;
  1040. }
  1041. #endif // NOTDEF
  1042. // Return start position in SPV of given Id. error if not found.
  1043. unsigned spirvbin_t::idPos(spv::Id id) const
  1044. {
  1045. const auto tid_it = idPosR.find(id);
  1046. if (tid_it == idPosR.end()) {
  1047. error("ID not found");
  1048. return 0;
  1049. }
  1050. return tid_it->second;
  1051. }
  1052. // Hash types to canonical values. This can return ID collisions (it's a bit
  1053. // inevitable): it's up to the caller to handle that gracefully.
  1054. std::uint32_t spirvbin_t::hashType(unsigned typeStart) const
  1055. {
  1056. const unsigned wordCount = asWordCount(typeStart);
  1057. const spv::Op opCode = asOpCode(typeStart);
  1058. switch (opCode) {
  1059. case spv::OpTypeVoid: return 0;
  1060. case spv::OpTypeBool: return 1;
  1061. case spv::OpTypeInt: return 3 + (spv[typeStart+3]);
  1062. case spv::OpTypeFloat: return 5;
  1063. case spv::OpTypeVector:
  1064. return 6 + hashType(idPos(spv[typeStart+2])) * (spv[typeStart+3] - 1);
  1065. case spv::OpTypeMatrix:
  1066. return 30 + hashType(idPos(spv[typeStart+2])) * (spv[typeStart+3] - 1);
  1067. case spv::OpTypeImage:
  1068. return 120 + hashType(idPos(spv[typeStart+2])) +
  1069. spv[typeStart+3] + // dimensionality
  1070. spv[typeStart+4] * 8 * 16 + // depth
  1071. spv[typeStart+5] * 4 * 16 + // arrayed
  1072. spv[typeStart+6] * 2 * 16 + // multisampled
  1073. spv[typeStart+7] * 1 * 16; // format
  1074. case spv::OpTypeSampler:
  1075. return 500;
  1076. case spv::OpTypeSampledImage:
  1077. return 502;
  1078. case spv::OpTypeArray:
  1079. return 501 + hashType(idPos(spv[typeStart+2])) * spv[typeStart+3];
  1080. case spv::OpTypeRuntimeArray:
  1081. return 5000 + hashType(idPos(spv[typeStart+2]));
  1082. case spv::OpTypeStruct:
  1083. {
  1084. std::uint32_t hash = 10000;
  1085. for (unsigned w=2; w < wordCount; ++w)
  1086. hash += w * hashType(idPos(spv[typeStart+w]));
  1087. return hash;
  1088. }
  1089. case spv::OpTypeOpaque: return 6000 + spv[typeStart+2];
  1090. case spv::OpTypePointer: return 100000 + hashType(idPos(spv[typeStart+3]));
  1091. case spv::OpTypeFunction:
  1092. {
  1093. std::uint32_t hash = 200000;
  1094. for (unsigned w=2; w < wordCount; ++w)
  1095. hash += w * hashType(idPos(spv[typeStart+w]));
  1096. return hash;
  1097. }
  1098. case spv::OpTypeEvent: return 300000;
  1099. case spv::OpTypeDeviceEvent: return 300001;
  1100. case spv::OpTypeReserveId: return 300002;
  1101. case spv::OpTypeQueue: return 300003;
  1102. case spv::OpTypePipe: return 300004;
  1103. case spv::OpConstantTrue: return 300007;
  1104. case spv::OpConstantFalse: return 300008;
  1105. case spv::OpConstantComposite:
  1106. {
  1107. std::uint32_t hash = 300011 + hashType(idPos(spv[typeStart+1]));
  1108. for (unsigned w=3; w < wordCount; ++w)
  1109. hash += w * hashType(idPos(spv[typeStart+w]));
  1110. return hash;
  1111. }
  1112. case spv::OpConstant:
  1113. {
  1114. std::uint32_t hash = 400011 + hashType(idPos(spv[typeStart+1]));
  1115. for (unsigned w=3; w < wordCount; ++w)
  1116. hash += w * spv[typeStart+w];
  1117. return hash;
  1118. }
  1119. case spv::OpConstantNull:
  1120. {
  1121. std::uint32_t hash = 500009 + hashType(idPos(spv[typeStart+1]));
  1122. return hash;
  1123. }
  1124. case spv::OpConstantSampler:
  1125. {
  1126. std::uint32_t hash = 600011 + hashType(idPos(spv[typeStart+1]));
  1127. for (unsigned w=3; w < wordCount; ++w)
  1128. hash += w * spv[typeStart+w];
  1129. return hash;
  1130. }
  1131. default:
  1132. error("unknown type opcode");
  1133. return 0;
  1134. }
  1135. }
  1136. void spirvbin_t::mapTypeConst()
  1137. {
  1138. globaltypes_t globalTypeMap;
  1139. msg(3, 2, std::string("Remapping Consts & Types: "));
  1140. static const std::uint32_t softTypeIdLimit = 3011; // small prime. TODO: get from options
  1141. static const std::uint32_t firstMappedID = 8; // offset into ID space
  1142. for (auto& typeStart : typeConstPos) {
  1143. const spv::Id resId = asTypeConstId(typeStart);
  1144. const std::uint32_t hashval = hashType(typeStart);
  1145. if (errorLatch)
  1146. return;
  1147. if (isOldIdUnmapped(resId)) {
  1148. localId(resId, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  1149. if (errorLatch)
  1150. return;
  1151. }
  1152. }
  1153. }
  1154. // Strip a single binary by removing ranges given in stripRange
  1155. void spirvbin_t::strip()
  1156. {
  1157. if (stripRange.empty()) // nothing to do
  1158. return;
  1159. // Sort strip ranges in order of traversal
  1160. std::sort(stripRange.begin(), stripRange.end());
  1161. // Allocate a new binary big enough to hold old binary
  1162. // We'll step this iterator through the strip ranges as we go through the binary
  1163. auto strip_it = stripRange.begin();
  1164. int strippedPos = 0;
  1165. for (unsigned word = 0; word < unsigned(spv.size()); ++word) {
  1166. while (strip_it != stripRange.end() && word >= strip_it->second)
  1167. ++strip_it;
  1168. if (strip_it == stripRange.end() || word < strip_it->first || word >= strip_it->second)
  1169. spv[strippedPos++] = spv[word];
  1170. }
  1171. spv.resize(strippedPos);
  1172. stripRange.clear();
  1173. buildLocalMaps();
  1174. }
  1175. // Strip a single binary by removing ranges given in stripRange
  1176. void spirvbin_t::remap(std::uint32_t opts)
  1177. {
  1178. options = opts;
  1179. // Set up opcode tables from SpvDoc
  1180. spv::Parameterize();
  1181. validate(); // validate header
  1182. buildLocalMaps(); // build ID maps
  1183. msg(3, 4, std::string("ID bound: ") + std::to_string(bound()));
  1184. if (options & STRIP) stripDebug();
  1185. if (errorLatch) return;
  1186. strip(); // strip out data we decided to eliminate
  1187. if (errorLatch) return;
  1188. if (options & OPT_LOADSTORE) optLoadStore();
  1189. if (errorLatch) return;
  1190. if (options & OPT_FWD_LS) forwardLoadStores();
  1191. if (errorLatch) return;
  1192. if (options & DCE_FUNCS) dceFuncs();
  1193. if (errorLatch) return;
  1194. if (options & DCE_VARS) dceVars();
  1195. if (errorLatch) return;
  1196. if (options & DCE_TYPES) dceTypes();
  1197. if (errorLatch) return;
  1198. strip(); // strip out data we decided to eliminate
  1199. if (errorLatch) return;
  1200. stripDeadRefs(); // remove references to things we DCEed
  1201. if (errorLatch) return;
  1202. // after the last strip, we must clean any debug info referring to now-deleted data
  1203. if (options & MAP_TYPES) mapTypeConst();
  1204. if (errorLatch) return;
  1205. if (options & MAP_NAMES) mapNames();
  1206. if (errorLatch) return;
  1207. if (options & MAP_FUNCS) mapFnBodies();
  1208. if (errorLatch) return;
  1209. if (options & MAP_ALL) {
  1210. mapRemainder(); // map any unmapped IDs
  1211. if (errorLatch) return;
  1212. applyMap(); // Now remap each shader to the new IDs we've come up with
  1213. if (errorLatch) return;
  1214. }
  1215. }
  1216. // remap from a memory image
  1217. void spirvbin_t::remap(std::vector<std::uint32_t>& in_spv, std::uint32_t opts)
  1218. {
  1219. spv.swap(in_spv);
  1220. remap(opts);
  1221. spv.swap(in_spv);
  1222. }
  1223. } // namespace SPV
  1224. #endif // defined (use_cpp11)