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