SPVRemapper.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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. case spv::OperandVariableLiteralStrings:
  525. return nextInst;
  526. // Execution mode might have extra literal operands. Skip them.
  527. case spv::OperandExecutionMode:
  528. return nextInst;
  529. // Single word operands we simply ignore, as they hold no IDs
  530. case spv::OperandLiteralNumber:
  531. case spv::OperandSource:
  532. case spv::OperandExecutionModel:
  533. case spv::OperandAddressing:
  534. case spv::OperandMemory:
  535. case spv::OperandStorage:
  536. case spv::OperandDimensionality:
  537. case spv::OperandSamplerAddressingMode:
  538. case spv::OperandSamplerFilterMode:
  539. case spv::OperandSamplerImageFormat:
  540. case spv::OperandImageChannelOrder:
  541. case spv::OperandImageChannelDataType:
  542. case spv::OperandImageOperands:
  543. case spv::OperandFPFastMath:
  544. case spv::OperandFPRoundingMode:
  545. case spv::OperandLinkageType:
  546. case spv::OperandAccessQualifier:
  547. case spv::OperandFuncParamAttr:
  548. case spv::OperandDecoration:
  549. case spv::OperandBuiltIn:
  550. case spv::OperandSelect:
  551. case spv::OperandLoop:
  552. case spv::OperandFunction:
  553. case spv::OperandMemoryAccess:
  554. case spv::OperandGroupOperation:
  555. case spv::OperandKernelEnqueueFlags:
  556. case spv::OperandKernelProfilingInfo:
  557. case spv::OperandCapability:
  558. ++word;
  559. break;
  560. default:
  561. assert(0 && "Unhandled Operand Class");
  562. break;
  563. }
  564. }
  565. return nextInst;
  566. }
  567. // Make a pass over all the instructions and process them given appropriate functions
  568. spirvbin_t& spirvbin_t::process(instfn_t instFn, idfn_t idFn, unsigned begin, unsigned end)
  569. {
  570. // For efficiency, reserve name map space. It can grow if needed.
  571. nameMap.reserve(32);
  572. // If begin or end == 0, use defaults
  573. begin = (begin == 0 ? header_size : begin);
  574. end = (end == 0 ? unsigned(spv.size()) : end);
  575. // basic parsing and InstructionDesc table borrowed from SpvDisassemble.cpp...
  576. unsigned nextInst = unsigned(spv.size());
  577. for (unsigned word = begin; word < end; word = nextInst) {
  578. nextInst = processInstruction(word, instFn, idFn);
  579. if (errorLatch)
  580. return *this;
  581. }
  582. return *this;
  583. }
  584. // Apply global name mapping to a single module
  585. void spirvbin_t::mapNames()
  586. {
  587. static const std::uint32_t softTypeIdLimit = 3011; // small prime. TODO: get from options
  588. static const std::uint32_t firstMappedID = 3019; // offset into ID space
  589. for (const auto& name : nameMap) {
  590. std::uint32_t hashval = 1911;
  591. for (const char c : name.first)
  592. hashval = hashval * 1009 + c;
  593. if (isOldIdUnmapped(name.second)) {
  594. localId(name.second, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  595. if (errorLatch)
  596. return;
  597. }
  598. }
  599. }
  600. // Map fn contents to IDs of similar functions in other modules
  601. void spirvbin_t::mapFnBodies()
  602. {
  603. static const std::uint32_t softTypeIdLimit = 19071; // small prime. TODO: get from options
  604. static const std::uint32_t firstMappedID = 6203; // offset into ID space
  605. // Initial approach: go through some high priority opcodes first and assign them
  606. // hash values.
  607. spv::Id fnId = spv::NoResult;
  608. std::vector<unsigned> instPos;
  609. instPos.reserve(unsigned(spv.size()) / 16); // initial estimate; can grow if needed.
  610. // Build local table of instruction start positions
  611. process(
  612. [&](spv::Op, unsigned start) { instPos.push_back(start); return true; },
  613. op_fn_nop);
  614. if (errorLatch)
  615. return;
  616. // Window size for context-sensitive canonicalization values
  617. // Empirical best size from a single data set. TODO: Would be a good tunable.
  618. // We essentially perform a little convolution around each instruction,
  619. // to capture the flavor of nearby code, to hopefully match to similar
  620. // code in other modules.
  621. static const unsigned windowSize = 2;
  622. for (unsigned entry = 0; entry < unsigned(instPos.size()); ++entry) {
  623. const unsigned start = instPos[entry];
  624. const spv::Op opCode = asOpCode(start);
  625. if (opCode == spv::OpFunction)
  626. fnId = asId(start + 2);
  627. if (opCode == spv::OpFunctionEnd)
  628. fnId = spv::NoResult;
  629. if (fnId != spv::NoResult) { // if inside a function
  630. if (spv::InstructionDesc[opCode].hasResult()) {
  631. const unsigned word = start + (spv::InstructionDesc[opCode].hasType() ? 2 : 1);
  632. const spv::Id resId = asId(word);
  633. std::uint32_t hashval = fnId * 17; // small prime
  634. for (unsigned i = entry-1; i >= entry-windowSize; --i) {
  635. if (asOpCode(instPos[i]) == spv::OpFunction)
  636. break;
  637. hashval = hashval * 30103 + asOpCodeHash(instPos[i]); // 30103 = semiarbitrary prime
  638. }
  639. for (unsigned i = entry; i <= entry + windowSize; ++i) {
  640. if (asOpCode(instPos[i]) == spv::OpFunctionEnd)
  641. break;
  642. hashval = hashval * 30103 + asOpCodeHash(instPos[i]); // 30103 = semiarbitrary prime
  643. }
  644. if (isOldIdUnmapped(resId)) {
  645. localId(resId, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  646. if (errorLatch)
  647. return;
  648. }
  649. }
  650. }
  651. }
  652. spv::Op thisOpCode(spv::OpNop);
  653. std::unordered_map<int, int> opCounter;
  654. int idCounter(0);
  655. fnId = spv::NoResult;
  656. process(
  657. [&](spv::Op opCode, unsigned start) {
  658. switch (opCode) {
  659. case spv::OpFunction:
  660. // Reset counters at each function
  661. idCounter = 0;
  662. opCounter.clear();
  663. fnId = asId(start + 2);
  664. break;
  665. case spv::OpImageSampleImplicitLod:
  666. case spv::OpImageSampleExplicitLod:
  667. case spv::OpImageSampleDrefImplicitLod:
  668. case spv::OpImageSampleDrefExplicitLod:
  669. case spv::OpImageSampleProjImplicitLod:
  670. case spv::OpImageSampleProjExplicitLod:
  671. case spv::OpImageSampleProjDrefImplicitLod:
  672. case spv::OpImageSampleProjDrefExplicitLod:
  673. case spv::OpDot:
  674. case spv::OpCompositeExtract:
  675. case spv::OpCompositeInsert:
  676. case spv::OpVectorShuffle:
  677. case spv::OpLabel:
  678. case spv::OpVariable:
  679. case spv::OpAccessChain:
  680. case spv::OpLoad:
  681. case spv::OpStore:
  682. case spv::OpCompositeConstruct:
  683. case spv::OpFunctionCall:
  684. ++opCounter[opCode];
  685. idCounter = 0;
  686. thisOpCode = opCode;
  687. break;
  688. default:
  689. thisOpCode = spv::OpNop;
  690. }
  691. return false;
  692. },
  693. [&](spv::Id& id) {
  694. if (thisOpCode != spv::OpNop) {
  695. ++idCounter;
  696. const std::uint32_t hashval =
  697. // Explicitly cast operands to unsigned int to avoid integer
  698. // promotion to signed int followed by integer overflow,
  699. // which would result in undefined behavior.
  700. static_cast<unsigned int>(opCounter[thisOpCode])
  701. * thisOpCode
  702. * 50047
  703. + idCounter
  704. + static_cast<unsigned int>(fnId) * 117;
  705. if (isOldIdUnmapped(id))
  706. localId(id, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  707. }
  708. });
  709. }
  710. // EXPERIMENTAL: forward IO and uniform load/stores into operands
  711. // This produces invalid Schema-0 SPIRV
  712. void spirvbin_t::forwardLoadStores()
  713. {
  714. idset_t fnLocalVars; // set of function local vars
  715. idmap_t idMap; // Map of load result IDs to what they load
  716. // EXPERIMENTAL: Forward input and access chain loads into consumptions
  717. process(
  718. [&](spv::Op opCode, unsigned start) {
  719. // Add inputs and uniforms to the map
  720. if ((opCode == spv::OpVariable && asWordCount(start) == 4) &&
  721. (spv[start+3] == spv::StorageClassUniform ||
  722. spv[start+3] == spv::StorageClassUniformConstant ||
  723. spv[start+3] == spv::StorageClassInput))
  724. fnLocalVars.insert(asId(start+2));
  725. if (opCode == spv::OpAccessChain && fnLocalVars.count(asId(start+3)) > 0)
  726. fnLocalVars.insert(asId(start+2));
  727. if (opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0) {
  728. idMap[asId(start+2)] = asId(start+3);
  729. stripInst(start);
  730. }
  731. return false;
  732. },
  733. [&](spv::Id& id) { if (idMap.find(id) != idMap.end()) id = idMap[id]; }
  734. );
  735. if (errorLatch)
  736. return;
  737. // EXPERIMENTAL: Implicit output stores
  738. fnLocalVars.clear();
  739. idMap.clear();
  740. process(
  741. [&](spv::Op opCode, unsigned start) {
  742. // Add inputs and uniforms to the map
  743. if ((opCode == spv::OpVariable && asWordCount(start) == 4) &&
  744. (spv[start+3] == spv::StorageClassOutput))
  745. fnLocalVars.insert(asId(start+2));
  746. if (opCode == spv::OpStore && fnLocalVars.count(asId(start+1)) > 0) {
  747. idMap[asId(start+2)] = asId(start+1);
  748. stripInst(start);
  749. }
  750. return false;
  751. },
  752. op_fn_nop);
  753. if (errorLatch)
  754. return;
  755. process(
  756. inst_fn_nop,
  757. [&](spv::Id& id) { if (idMap.find(id) != idMap.end()) id = idMap[id]; }
  758. );
  759. if (errorLatch)
  760. return;
  761. strip(); // strip out data we decided to eliminate
  762. }
  763. // optimize loads and stores
  764. void spirvbin_t::optLoadStore()
  765. {
  766. idset_t fnLocalVars; // candidates for removal (only locals)
  767. idmap_t idMap; // Map of load result IDs to what they load
  768. blockmap_t blockMap; // Map of IDs to blocks they first appear in
  769. int blockNum = 0; // block count, to avoid crossing flow control
  770. // Find all the function local pointers stored at most once, and not via access chains
  771. process(
  772. [&](spv::Op opCode, unsigned start) {
  773. const int wordCount = asWordCount(start);
  774. // Count blocks, so we can avoid crossing flow control
  775. if (isFlowCtrl(opCode))
  776. ++blockNum;
  777. // Add local variables to the map
  778. if ((opCode == spv::OpVariable && spv[start+3] == spv::StorageClassFunction && asWordCount(start) == 4)) {
  779. fnLocalVars.insert(asId(start+2));
  780. return true;
  781. }
  782. // Ignore process vars referenced via access chain
  783. if ((opCode == spv::OpAccessChain || opCode == spv::OpInBoundsAccessChain) && fnLocalVars.count(asId(start+3)) > 0) {
  784. fnLocalVars.erase(asId(start+3));
  785. idMap.erase(asId(start+3));
  786. return true;
  787. }
  788. if (opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0) {
  789. const spv::Id varId = asId(start+3);
  790. // Avoid loads before stores
  791. if (idMap.find(varId) == idMap.end()) {
  792. fnLocalVars.erase(varId);
  793. idMap.erase(varId);
  794. }
  795. // don't do for volatile references
  796. if (wordCount > 4 && (spv[start+4] & spv::MemoryAccessVolatileMask)) {
  797. fnLocalVars.erase(varId);
  798. idMap.erase(varId);
  799. }
  800. // Handle flow control
  801. if (blockMap.find(varId) == blockMap.end()) {
  802. blockMap[varId] = blockNum; // track block we found it in.
  803. } else if (blockMap[varId] != blockNum) {
  804. fnLocalVars.erase(varId); // Ignore if crosses flow control
  805. idMap.erase(varId);
  806. }
  807. return true;
  808. }
  809. if (opCode == spv::OpStore && fnLocalVars.count(asId(start+1)) > 0) {
  810. const spv::Id varId = asId(start+1);
  811. if (idMap.find(varId) == idMap.end()) {
  812. idMap[varId] = asId(start+2);
  813. } else {
  814. // Remove if it has more than one store to the same pointer
  815. fnLocalVars.erase(varId);
  816. idMap.erase(varId);
  817. }
  818. // don't do for volatile references
  819. if (wordCount > 3 && (spv[start+3] & spv::MemoryAccessVolatileMask)) {
  820. fnLocalVars.erase(asId(start+3));
  821. idMap.erase(asId(start+3));
  822. }
  823. // Handle flow control
  824. if (blockMap.find(varId) == blockMap.end()) {
  825. blockMap[varId] = blockNum; // track block we found it in.
  826. } else if (blockMap[varId] != blockNum) {
  827. fnLocalVars.erase(varId); // Ignore if crosses flow control
  828. idMap.erase(varId);
  829. }
  830. return true;
  831. }
  832. return false;
  833. },
  834. // If local var id used anywhere else, don't eliminate
  835. [&](spv::Id& id) {
  836. if (fnLocalVars.count(id) > 0) {
  837. fnLocalVars.erase(id);
  838. idMap.erase(id);
  839. }
  840. }
  841. );
  842. if (errorLatch)
  843. return;
  844. process(
  845. [&](spv::Op opCode, unsigned start) {
  846. if (opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0)
  847. idMap[asId(start+2)] = idMap[asId(start+3)];
  848. return false;
  849. },
  850. op_fn_nop);
  851. if (errorLatch)
  852. return;
  853. // Chase replacements to their origins, in case there is a chain such as:
  854. // 2 = store 1
  855. // 3 = load 2
  856. // 4 = store 3
  857. // 5 = load 4
  858. // We want to replace uses of 5 with 1.
  859. for (const auto& idPair : idMap) {
  860. spv::Id id = idPair.first;
  861. while (idMap.find(id) != idMap.end()) // Chase to end of chain
  862. id = idMap[id];
  863. idMap[idPair.first] = id; // replace with final result
  864. }
  865. // Remove the load/store/variables for the ones we've discovered
  866. process(
  867. [&](spv::Op opCode, unsigned start) {
  868. if ((opCode == spv::OpLoad && fnLocalVars.count(asId(start+3)) > 0) ||
  869. (opCode == spv::OpStore && fnLocalVars.count(asId(start+1)) > 0) ||
  870. (opCode == spv::OpVariable && fnLocalVars.count(asId(start+2)) > 0)) {
  871. stripInst(start);
  872. return true;
  873. }
  874. return false;
  875. },
  876. [&](spv::Id& id) {
  877. if (idMap.find(id) != idMap.end()) id = idMap[id];
  878. }
  879. );
  880. if (errorLatch)
  881. return;
  882. strip(); // strip out data we decided to eliminate
  883. }
  884. // remove bodies of uncalled functions
  885. void spirvbin_t::dceFuncs()
  886. {
  887. msg(3, 2, std::string("Removing Dead Functions: "));
  888. // TODO: There are more efficient ways to do this.
  889. bool changed = true;
  890. while (changed) {
  891. changed = false;
  892. for (auto fn = fnPos.begin(); fn != fnPos.end(); ) {
  893. if (fn->first == entryPoint) { // don't DCE away the entry point!
  894. ++fn;
  895. continue;
  896. }
  897. const auto call_it = fnCalls.find(fn->first);
  898. if (call_it == fnCalls.end() || call_it->second == 0) {
  899. changed = true;
  900. stripRange.push_back(fn->second);
  901. // decrease counts of called functions
  902. process(
  903. [&](spv::Op opCode, unsigned start) {
  904. if (opCode == spv::Op::OpFunctionCall) {
  905. const auto call_it = fnCalls.find(asId(start + 3));
  906. if (call_it != fnCalls.end()) {
  907. if (--call_it->second <= 0)
  908. fnCalls.erase(call_it);
  909. }
  910. }
  911. return true;
  912. },
  913. op_fn_nop,
  914. fn->second.first,
  915. fn->second.second);
  916. if (errorLatch)
  917. return;
  918. fn = fnPos.erase(fn);
  919. } else ++fn;
  920. }
  921. }
  922. }
  923. // remove unused function variables + decorations
  924. void spirvbin_t::dceVars()
  925. {
  926. msg(3, 2, std::string("DCE Vars: "));
  927. std::unordered_map<spv::Id, int> varUseCount;
  928. // Count function variable use
  929. process(
  930. [&](spv::Op opCode, unsigned start) {
  931. if (opCode == spv::OpVariable) {
  932. ++varUseCount[asId(start+2)];
  933. return true;
  934. } else if (opCode == spv::OpEntryPoint) {
  935. const int wordCount = asWordCount(start);
  936. for (int i = 4; i < wordCount; i++) {
  937. ++varUseCount[asId(start+i)];
  938. }
  939. return true;
  940. } else
  941. return false;
  942. },
  943. [&](spv::Id& id) { if (varUseCount[id]) ++varUseCount[id]; }
  944. );
  945. if (errorLatch)
  946. return;
  947. // Remove single-use function variables + associated decorations and names
  948. process(
  949. [&](spv::Op opCode, unsigned start) {
  950. spv::Id id = spv::NoResult;
  951. if (opCode == spv::OpVariable)
  952. id = asId(start+2);
  953. if (opCode == spv::OpDecorate || opCode == spv::OpName)
  954. id = asId(start+1);
  955. if (id != spv::NoResult && varUseCount[id] == 1)
  956. stripInst(start);
  957. return true;
  958. },
  959. op_fn_nop);
  960. }
  961. // remove unused types
  962. void spirvbin_t::dceTypes()
  963. {
  964. std::vector<bool> isType(bound(), false);
  965. // for speed, make O(1) way to get to type query (map is log(n))
  966. for (const auto typeStart : typeConstPos)
  967. isType[asTypeConstId(typeStart)] = true;
  968. std::unordered_map<spv::Id, int> typeUseCount;
  969. // This is not the most efficient algorithm, but this is an offline tool, and
  970. // it's easy to write this way. Can be improved opportunistically if needed.
  971. bool changed = true;
  972. while (changed) {
  973. changed = false;
  974. strip();
  975. typeUseCount.clear();
  976. // Count total type usage
  977. process(inst_fn_nop,
  978. [&](spv::Id& id) { if (isType[id]) ++typeUseCount[id]; }
  979. );
  980. if (errorLatch)
  981. return;
  982. // Remove single reference types
  983. for (const auto typeStart : typeConstPos) {
  984. const spv::Id typeId = asTypeConstId(typeStart);
  985. if (typeUseCount[typeId] == 1) {
  986. changed = true;
  987. --typeUseCount[typeId];
  988. stripInst(typeStart);
  989. }
  990. }
  991. if (errorLatch)
  992. return;
  993. }
  994. }
  995. #ifdef NOTDEF
  996. bool spirvbin_t::matchType(const spirvbin_t::globaltypes_t& globalTypes, spv::Id lt, spv::Id gt) const
  997. {
  998. // Find the local type id "lt" and global type id "gt"
  999. const auto lt_it = typeConstPosR.find(lt);
  1000. if (lt_it == typeConstPosR.end())
  1001. return false;
  1002. const auto typeStart = lt_it->second;
  1003. // Search for entry in global table
  1004. const auto gtype = globalTypes.find(gt);
  1005. if (gtype == globalTypes.end())
  1006. return false;
  1007. const auto& gdata = gtype->second;
  1008. // local wordcount and opcode
  1009. const int wordCount = asWordCount(typeStart);
  1010. const spv::Op opCode = asOpCode(typeStart);
  1011. // no type match if opcodes don't match, or operand count doesn't match
  1012. if (opCode != opOpCode(gdata[0]) || wordCount != opWordCount(gdata[0]))
  1013. return false;
  1014. const unsigned numOperands = wordCount - 2; // all types have a result
  1015. const auto cmpIdRange = [&](range_t range) {
  1016. for (int x=range.first; x<std::min(range.second, wordCount); ++x)
  1017. if (!matchType(globalTypes, asId(typeStart+x), gdata[x]))
  1018. return false;
  1019. return true;
  1020. };
  1021. const auto cmpConst = [&]() { return cmpIdRange(constRange(opCode)); };
  1022. const auto cmpSubType = [&]() { return cmpIdRange(typeRange(opCode)); };
  1023. // Compare literals in range [start,end)
  1024. const auto cmpLiteral = [&]() {
  1025. const auto range = literalRange(opCode);
  1026. return std::equal(spir.begin() + typeStart + range.first,
  1027. spir.begin() + typeStart + std::min(range.second, wordCount),
  1028. gdata.begin() + range.first);
  1029. };
  1030. assert(isTypeOp(opCode) || isConstOp(opCode));
  1031. switch (opCode) {
  1032. case spv::OpTypeOpaque: // TODO: disable until we compare the literal strings.
  1033. case spv::OpTypeQueue: return false;
  1034. case spv::OpTypeEvent: // fall through...
  1035. case spv::OpTypeDeviceEvent: // ...
  1036. case spv::OpTypeReserveId: return false;
  1037. // for samplers, we don't handle the optional parameters yet
  1038. case spv::OpTypeSampler: return cmpLiteral() && cmpConst() && cmpSubType() && wordCount == 8;
  1039. default: return cmpLiteral() && cmpConst() && cmpSubType();
  1040. }
  1041. }
  1042. // Look for an equivalent type in the globalTypes map
  1043. spv::Id spirvbin_t::findType(const spirvbin_t::globaltypes_t& globalTypes, spv::Id lt) const
  1044. {
  1045. // Try a recursive type match on each in turn, and return a match if we find one
  1046. for (const auto& gt : globalTypes)
  1047. if (matchType(globalTypes, lt, gt.first))
  1048. return gt.first;
  1049. return spv::NoType;
  1050. }
  1051. #endif // NOTDEF
  1052. // Return start position in SPV of given Id. error if not found.
  1053. unsigned spirvbin_t::idPos(spv::Id id) const
  1054. {
  1055. const auto tid_it = idPosR.find(id);
  1056. if (tid_it == idPosR.end()) {
  1057. error("ID not found");
  1058. return 0;
  1059. }
  1060. return tid_it->second;
  1061. }
  1062. // Hash types to canonical values. This can return ID collisions (it's a bit
  1063. // inevitable): it's up to the caller to handle that gracefully.
  1064. std::uint32_t spirvbin_t::hashType(unsigned typeStart) const
  1065. {
  1066. const unsigned wordCount = asWordCount(typeStart);
  1067. const spv::Op opCode = asOpCode(typeStart);
  1068. switch (opCode) {
  1069. case spv::OpTypeVoid: return 0;
  1070. case spv::OpTypeBool: return 1;
  1071. case spv::OpTypeInt: return 3 + (spv[typeStart+3]);
  1072. case spv::OpTypeFloat: return 5;
  1073. case spv::OpTypeVector:
  1074. return 6 + hashType(idPos(spv[typeStart+2])) * (spv[typeStart+3] - 1);
  1075. case spv::OpTypeMatrix:
  1076. return 30 + hashType(idPos(spv[typeStart+2])) * (spv[typeStart+3] - 1);
  1077. case spv::OpTypeImage:
  1078. return 120 + hashType(idPos(spv[typeStart+2])) +
  1079. spv[typeStart+3] + // dimensionality
  1080. spv[typeStart+4] * 8 * 16 + // depth
  1081. spv[typeStart+5] * 4 * 16 + // arrayed
  1082. spv[typeStart+6] * 2 * 16 + // multisampled
  1083. spv[typeStart+7] * 1 * 16; // format
  1084. case spv::OpTypeSampler:
  1085. return 500;
  1086. case spv::OpTypeSampledImage:
  1087. return 502;
  1088. case spv::OpTypeArray:
  1089. return 501 + hashType(idPos(spv[typeStart+2])) * spv[typeStart+3];
  1090. case spv::OpTypeRuntimeArray:
  1091. return 5000 + hashType(idPos(spv[typeStart+2]));
  1092. case spv::OpTypeStruct:
  1093. {
  1094. std::uint32_t hash = 10000;
  1095. for (unsigned w=2; w < wordCount; ++w)
  1096. hash += w * hashType(idPos(spv[typeStart+w]));
  1097. return hash;
  1098. }
  1099. case spv::OpTypeOpaque: return 6000 + spv[typeStart+2];
  1100. case spv::OpTypePointer: return 100000 + hashType(idPos(spv[typeStart+3]));
  1101. case spv::OpTypeFunction:
  1102. {
  1103. std::uint32_t hash = 200000;
  1104. for (unsigned w=2; w < wordCount; ++w)
  1105. hash += w * hashType(idPos(spv[typeStart+w]));
  1106. return hash;
  1107. }
  1108. case spv::OpTypeEvent: return 300000;
  1109. case spv::OpTypeDeviceEvent: return 300001;
  1110. case spv::OpTypeReserveId: return 300002;
  1111. case spv::OpTypeQueue: return 300003;
  1112. case spv::OpTypePipe: return 300004;
  1113. case spv::OpConstantTrue: return 300007;
  1114. case spv::OpConstantFalse: return 300008;
  1115. case spv::OpConstantComposite:
  1116. {
  1117. std::uint32_t hash = 300011 + hashType(idPos(spv[typeStart+1]));
  1118. for (unsigned w=3; w < wordCount; ++w)
  1119. hash += w * hashType(idPos(spv[typeStart+w]));
  1120. return hash;
  1121. }
  1122. case spv::OpConstant:
  1123. {
  1124. std::uint32_t hash = 400011 + hashType(idPos(spv[typeStart+1]));
  1125. for (unsigned w=3; w < wordCount; ++w)
  1126. hash += w * spv[typeStart+w];
  1127. return hash;
  1128. }
  1129. case spv::OpConstantNull:
  1130. {
  1131. std::uint32_t hash = 500009 + hashType(idPos(spv[typeStart+1]));
  1132. return hash;
  1133. }
  1134. case spv::OpConstantSampler:
  1135. {
  1136. std::uint32_t hash = 600011 + hashType(idPos(spv[typeStart+1]));
  1137. for (unsigned w=3; w < wordCount; ++w)
  1138. hash += w * spv[typeStart+w];
  1139. return hash;
  1140. }
  1141. default:
  1142. error("unknown type opcode");
  1143. return 0;
  1144. }
  1145. }
  1146. void spirvbin_t::mapTypeConst()
  1147. {
  1148. globaltypes_t globalTypeMap;
  1149. msg(3, 2, std::string("Remapping Consts & Types: "));
  1150. static const std::uint32_t softTypeIdLimit = 3011; // small prime. TODO: get from options
  1151. static const std::uint32_t firstMappedID = 8; // offset into ID space
  1152. for (auto& typeStart : typeConstPos) {
  1153. const spv::Id resId = asTypeConstId(typeStart);
  1154. const std::uint32_t hashval = hashType(typeStart);
  1155. if (errorLatch)
  1156. return;
  1157. if (isOldIdUnmapped(resId)) {
  1158. localId(resId, nextUnusedId(hashval % softTypeIdLimit + firstMappedID));
  1159. if (errorLatch)
  1160. return;
  1161. }
  1162. }
  1163. }
  1164. // Strip a single binary by removing ranges given in stripRange
  1165. void spirvbin_t::strip()
  1166. {
  1167. if (stripRange.empty()) // nothing to do
  1168. return;
  1169. // Sort strip ranges in order of traversal
  1170. std::sort(stripRange.begin(), stripRange.end());
  1171. // Allocate a new binary big enough to hold old binary
  1172. // We'll step this iterator through the strip ranges as we go through the binary
  1173. auto strip_it = stripRange.begin();
  1174. int strippedPos = 0;
  1175. for (unsigned word = 0; word < unsigned(spv.size()); ++word) {
  1176. while (strip_it != stripRange.end() && word >= strip_it->second)
  1177. ++strip_it;
  1178. if (strip_it == stripRange.end() || word < strip_it->first || word >= strip_it->second)
  1179. spv[strippedPos++] = spv[word];
  1180. }
  1181. spv.resize(strippedPos);
  1182. stripRange.clear();
  1183. buildLocalMaps();
  1184. }
  1185. // Strip a single binary by removing ranges given in stripRange
  1186. void spirvbin_t::remap(std::uint32_t opts)
  1187. {
  1188. options = opts;
  1189. // Set up opcode tables from SpvDoc
  1190. spv::Parameterize();
  1191. validate(); // validate header
  1192. buildLocalMaps(); // build ID maps
  1193. msg(3, 4, std::string("ID bound: ") + std::to_string(bound()));
  1194. if (options & STRIP) stripDebug();
  1195. if (errorLatch) return;
  1196. strip(); // strip out data we decided to eliminate
  1197. if (errorLatch) return;
  1198. if (options & OPT_LOADSTORE) optLoadStore();
  1199. if (errorLatch) return;
  1200. if (options & OPT_FWD_LS) forwardLoadStores();
  1201. if (errorLatch) return;
  1202. if (options & DCE_FUNCS) dceFuncs();
  1203. if (errorLatch) return;
  1204. if (options & DCE_VARS) dceVars();
  1205. if (errorLatch) return;
  1206. if (options & DCE_TYPES) dceTypes();
  1207. if (errorLatch) return;
  1208. strip(); // strip out data we decided to eliminate
  1209. if (errorLatch) return;
  1210. stripDeadRefs(); // remove references to things we DCEed
  1211. if (errorLatch) return;
  1212. // after the last strip, we must clean any debug info referring to now-deleted data
  1213. if (options & MAP_TYPES) mapTypeConst();
  1214. if (errorLatch) return;
  1215. if (options & MAP_NAMES) mapNames();
  1216. if (errorLatch) return;
  1217. if (options & MAP_FUNCS) mapFnBodies();
  1218. if (errorLatch) return;
  1219. if (options & MAP_ALL) {
  1220. mapRemainder(); // map any unmapped IDs
  1221. if (errorLatch) return;
  1222. applyMap(); // Now remap each shader to the new IDs we've come up with
  1223. if (errorLatch) return;
  1224. }
  1225. }
  1226. // remap from a memory image
  1227. void spirvbin_t::remap(std::vector<std::uint32_t>& in_spv, std::uint32_t opts)
  1228. {
  1229. spv.swap(in_spv);
  1230. remap(opts);
  1231. spv.swap(in_spv);
  1232. }
  1233. } // namespace SPV
  1234. #endif // defined (use_cpp11)