SPVRemapper.cpp 53 KB

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