2 // Copyright (C) 2015 LunarG, Inc.
4 // All rights reserved.
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions
10 // Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
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.
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.
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.
36 #ifndef SPIRVREMAPPER_H
37 #define SPIRVREMAPPER_H
46 // MSVC defines __cplusplus as an older value, even when it supports almost all of 11.
47 // We handle that here by making our own symbol.
48 #if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1700)
64 OPT_LOADSTORE = (1<<7),
65 OPT_FWD_LS = (1<<8), // EXPERIMENTAL: PRODUCES INVALID SCHEMA-0 SPIRV
66 MAP_ALL = (MAP_TYPES | MAP_NAMES | MAP_FUNCS),
67 DCE_ALL = (DCE_FUNCS | DCE_VARS | DCE_TYPES),
68 OPT_ALL = (OPT_LOADSTORE),
70 ALL_BUT_STRIP = (MAP_ALL | DCE_ALL | OPT_ALL),
71 DO_EVERYTHING = (STRIP | ALL_BUT_STRIP)
77 #if !defined (use_cpp11)
82 class spirvbin_t : public spirvbin_base_t
85 spirvbin_t(int /*verbose = 0*/) { }
87 void remap(std::vector<std::uint32_t>& /*spv*/, unsigned int /*opts = 0*/)
89 printf("Tool not compiled for C++11, which is required for SPIR-V remapping.\n");
96 #else // defined (use_cpp11)
100 #include <unordered_map>
101 #include <unordered_set>
111 // class to hold SPIR-V binary data for remapping, DCE, and debug stripping
112 class spirvbin_t : public spirvbin_base_t
115 spirvbin_t(int verbose = 0) : entryPoint(spv::NoResult), largestNewId(0), verbose(verbose), errorLatch(false)
118 virtual ~spirvbin_t() { }
120 // remap on an existing binary in memory
121 void remap(std::vector<std::uint32_t>& spv, const std::vector<std::string>& whiteListStrings,
122 std::uint32_t opts = DO_EVERYTHING);
124 // remap on an existing binary in memory - legacy interface without white list
125 void remap(std::vector<std::uint32_t>& spv, std::uint32_t opts = DO_EVERYTHING);
127 // Type for error/log handler functions
128 typedef std::function<void(const std::string&)> errorfn_t;
129 typedef std::function<void(const std::string&)> logfn_t;
131 // Register error/log handling functions (can be lambda fn / functor / etc)
132 static void registerErrorHandler(errorfn_t handler) { errorHandler = handler; }
133 static void registerLogHandler(logfn_t handler) { logHandler = handler; }
136 // This can be overridden to provide other message behavior if needed
137 virtual void msg(int minVerbosity, int indent, const std::string& txt) const;
140 // Local to global, or global to local ID map
141 typedef std::unordered_map<spv::Id, spv::Id> idmap_t;
142 typedef std::unordered_set<spv::Id> idset_t;
143 typedef std::unordered_map<spv::Id, int> blockmap_t;
145 void remap(std::uint32_t opts = DO_EVERYTHING);
147 // Map of names to IDs
148 typedef std::unordered_map<std::string, spv::Id> namemap_t;
150 typedef std::uint32_t spirword_t;
152 typedef std::pair<unsigned, unsigned> range_t;
153 typedef std::function<void(spv::Id&)> idfn_t;
154 typedef std::function<bool(spv::Op, unsigned start)> instfn_t;
156 // Special Values for ID map:
157 static const spv::Id unmapped; // unchanged from default value
158 static const spv::Id unused; // unused ID
159 static const int header_size; // SPIR header = 5 words
163 // For mapping type entries between different shaders
164 typedef std::vector<spirword_t> typeentry_t;
165 typedef std::map<spv::Id, typeentry_t> globaltypes_t;
167 // A set that preserves position order, and a reverse map
168 typedef std::set<int> posmap_t;
169 typedef std::unordered_map<spv::Id, int> posmap_rev_t;
171 // Maps and ID to the size of its base type, if known.
172 typedef std::unordered_map<spv::Id, unsigned> typesize_map_t;
175 void error(const std::string& txt) const { errorLatch = true; errorHandler(txt); }
177 bool isConstOp(spv::Op opCode) const;
178 bool isTypeOp(spv::Op opCode) const;
179 bool isStripOp(spv::Op opCode) const;
180 bool isFlowCtrl(spv::Op opCode) const;
181 range_t literalRange(spv::Op opCode) const;
182 range_t typeRange(spv::Op opCode) const;
183 range_t constRange(spv::Op opCode) const;
184 unsigned typeSizeInWords(spv::Id id) const;
185 unsigned idTypeSizeInWords(spv::Id id) const;
187 bool isStripOp(spv::Op opCode, unsigned start) const;
189 spv::Id& asId(unsigned word) { return spv[word]; }
190 const spv::Id& asId(unsigned word) const { return spv[word]; }
191 spv::Op asOpCode(unsigned word) const { return opOpCode(spv[word]); }
192 std::uint32_t asOpCodeHash(unsigned word);
193 spv::Decoration asDecoration(unsigned word) const { return spv::Decoration(spv[word]); }
194 unsigned asWordCount(unsigned word) const { return opWordCount(spv[word]); }
195 spv::Id asTypeConstId(unsigned word) const { return asId(word + (isTypeOp(asOpCode(word)) ? 1 : 2)); }
196 unsigned idPos(spv::Id id) const;
198 static unsigned opWordCount(spirword_t data) { return data >> spv::WordCountShift; }
199 static spv::Op opOpCode(spirword_t data) { return spv::Op(data & spv::OpCodeMask); }
201 // Header access & set methods
202 spirword_t magic() const { return spv[0]; } // return magic number
203 spirword_t bound() const { return spv[3]; } // return Id bound from header
204 spirword_t bound(spirword_t b) { return spv[3] = b; }
205 spirword_t genmagic() const { return spv[2]; } // generator magic
206 spirword_t genmagic(spirword_t m) { return spv[2] = m; }
207 spirword_t schemaNum() const { return spv[4]; } // schema number from header
210 spv::Id localId(spv::Id id) const { return idMapL[id]; }
213 inline spv::Id localId(spv::Id id, spv::Id newId);
214 void countIds(spv::Id id);
216 // Return next unused new local ID.
217 // NOTE: boost::dynamic_bitset would be more efficient due to find_next(),
218 // which std::vector<bool> doens't have.
219 inline spv::Id nextUnusedId(spv::Id id);
221 void buildLocalMaps();
222 std::string literalString(unsigned word) const; // Return literal as a std::string
223 int literalStringWords(const std::string& str) const { return (int(str.size())+4)/4; }
225 bool isNewIdMapped(spv::Id newId) const { return isMapped(newId); }
226 bool isOldIdUnmapped(spv::Id oldId) const { return localId(oldId) == unmapped; }
227 bool isOldIdUnused(spv::Id oldId) const { return localId(oldId) == unused; }
228 bool isOldIdMapped(spv::Id oldId) const { return !isOldIdUnused(oldId) && !isOldIdUnmapped(oldId); }
229 bool isFunction(spv::Id oldId) const { return fnPos.find(oldId) != fnPos.end(); }
231 // bool matchType(const globaltypes_t& globalTypes, spv::Id lt, spv::Id gt) const;
232 // spv::Id findType(const globaltypes_t& globalTypes, spv::Id lt) const;
233 std::uint32_t hashType(unsigned typeStart) const;
235 spirvbin_t& process(instfn_t, idfn_t, unsigned begin = 0, unsigned end = 0);
236 int processInstruction(unsigned word, instfn_t, idfn_t);
238 void validate() const;
246 void foldIds(); // fold IDs to smallest space
247 void forwardLoadStores(); // load store forwarding (EXPERIMENTAL)
248 void offsetIds(); // create relative offset IDs
250 void applyMap(); // remap per local name map
251 void mapRemainder(); // map any IDs we haven't touched yet
252 void stripDebug(); // strip all debug info
253 void stripDeadRefs(); // strips debug info for now-dead references after DCE
254 void strip(); // remove debug symbols
256 std::vector<spirword_t> spv; // SPIR words
258 std::vector<std::string> stripWhiteList;
260 namemap_t nameMap; // ID names from OpName
262 // Since we want to also do binary ops, we can't use std::vector<bool>. we could use
263 // boost::dynamic_bitset, but we're trying to avoid a boost dependency.
264 typedef std::uint64_t bits_t;
265 std::vector<bits_t> mapped; // which new IDs have been mapped
266 static const int mBits = sizeof(bits_t) * 4;
268 bool isMapped(spv::Id id) const { return id < maxMappedId() && ((mapped[id/mBits] & (1LL<<(id%mBits))) != 0); }
269 void setMapped(spv::Id id) { resizeMapped(id); mapped[id/mBits] |= (1LL<<(id%mBits)); }
270 void resizeMapped(spv::Id id) { if (id >= maxMappedId()) mapped.resize(id/mBits+1, 0); }
271 size_t maxMappedId() const { return mapped.size() * mBits; }
273 // Add a strip range for a given instruction starting at 'start'
274 // Note: avoiding brace initializers to please older versions os MSVC.
275 void stripInst(unsigned start) { stripRange.push_back(range_t(start, start + asWordCount(start))); }
277 // Function start and end. use unordered_map because we'll have
278 // many fewer functions than IDs.
279 std::unordered_map<spv::Id, range_t> fnPos;
281 // Which functions are called, anywhere in the module, with a call count
282 std::unordered_map<spv::Id, int> fnCalls;
284 posmap_t typeConstPos; // word positions that define types & consts (ordered)
285 posmap_rev_t idPosR; // reverse map from IDs to positions
286 typesize_map_t idTypeSizeMap; // maps each ID to its type size, if known.
288 std::vector<spv::Id> idMapL; // ID {M}ap from {L}ocal to {G}lobal IDs
290 spv::Id entryPoint; // module entry point
291 spv::Id largestNewId; // biggest new ID we have mapped anything to
293 // Sections of the binary to strip, given as [begin,end)
294 std::vector<range_t> stripRange;
296 // processing options:
297 std::uint32_t options;
298 int verbose; // verbosity level
300 // Error latch: this is set if the error handler is ever executed. It would be better to
301 // use a try/catch block and throw, but that's not desired for certain environments, so
302 // this is the alternative.
303 mutable bool errorLatch;
305 static errorfn_t errorHandler;
306 static logfn_t logHandler;
311 #endif // defined (use_cpp11)
312 #endif // SPIRVREMAPPER_H