SPVRemapper.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. #ifndef SPIRVREMAPPER_H
  36. #define SPIRVREMAPPER_H
  37. #include <string>
  38. #include <vector>
  39. #include <cstdlib>
  40. #include <exception>
  41. namespace spv {
  42. // MSVC defines __cplusplus as an older value, even when it supports almost all of 11.
  43. // We handle that here by making our own symbol.
  44. #if __cplusplus >= 201103L || _MSC_VER >= 1700
  45. # define use_cpp11 1
  46. #endif
  47. class spirvbin_base_t
  48. {
  49. public:
  50. enum Options {
  51. NONE = 0,
  52. STRIP = (1<<0),
  53. MAP_TYPES = (1<<1),
  54. MAP_NAMES = (1<<2),
  55. MAP_FUNCS = (1<<3),
  56. DCE_FUNCS = (1<<4),
  57. DCE_VARS = (1<<5),
  58. DCE_TYPES = (1<<6),
  59. OPT_LOADSTORE = (1<<7),
  60. OPT_FWD_LS = (1<<8), // EXPERIMENTAL: PRODUCES INVALID SCHEMA-0 SPIRV
  61. MAP_ALL = (MAP_TYPES | MAP_NAMES | MAP_FUNCS),
  62. DCE_ALL = (DCE_FUNCS | DCE_VARS | DCE_TYPES),
  63. OPT_ALL = (OPT_LOADSTORE),
  64. ALL_BUT_STRIP = (MAP_ALL | DCE_ALL | OPT_ALL),
  65. DO_EVERYTHING = (STRIP | ALL_BUT_STRIP)
  66. };
  67. };
  68. } // namespace SPV
  69. #if !defined (use_cpp11)
  70. #include <cstdio>
  71. #include <cstdint>
  72. namespace spv {
  73. class spirvbin_t : public spirvbin_base_t
  74. {
  75. public:
  76. spirvbin_t(int /*verbose = 0*/) { }
  77. void remap(std::vector<std::uint32_t>& /*spv*/, unsigned int /*opts = 0*/)
  78. {
  79. printf("Tool not compiled for C++11, which is required for SPIR-V remapping.\n");
  80. exit(5);
  81. }
  82. };
  83. } // namespace SPV
  84. #else // defined (use_cpp11)
  85. #include <functional>
  86. #include <cstdint>
  87. #include <unordered_map>
  88. #include <unordered_set>
  89. #include <map>
  90. #include <set>
  91. #include <cassert>
  92. #include "spirv.hpp"
  93. #include "spvIR.h"
  94. namespace spv {
  95. // class to hold SPIR-V binary data for remapping, DCE, and debug stripping
  96. class spirvbin_t : public spirvbin_base_t
  97. {
  98. public:
  99. spirvbin_t(int verbose = 0) : entryPoint(spv::NoResult), largestNewId(0), verbose(verbose), errorLatch(false)
  100. { }
  101. virtual ~spirvbin_t() { }
  102. // remap on an existing binary in memory
  103. void remap(std::vector<std::uint32_t>& spv, std::uint32_t opts = DO_EVERYTHING);
  104. // Type for error/log handler functions
  105. typedef std::function<void(const std::string&)> errorfn_t;
  106. typedef std::function<void(const std::string&)> logfn_t;
  107. // Register error/log handling functions (can be lambda fn / functor / etc)
  108. static void registerErrorHandler(errorfn_t handler) { errorHandler = handler; }
  109. static void registerLogHandler(logfn_t handler) { logHandler = handler; }
  110. protected:
  111. // This can be overridden to provide other message behavior if needed
  112. virtual void msg(int minVerbosity, int indent, const std::string& txt) const;
  113. private:
  114. // Local to global, or global to local ID map
  115. typedef std::unordered_map<spv::Id, spv::Id> idmap_t;
  116. typedef std::unordered_set<spv::Id> idset_t;
  117. typedef std::unordered_map<spv::Id, int> blockmap_t;
  118. void remap(std::uint32_t opts = DO_EVERYTHING);
  119. // Map of names to IDs
  120. typedef std::unordered_map<std::string, spv::Id> namemap_t;
  121. typedef std::uint32_t spirword_t;
  122. typedef std::pair<unsigned, unsigned> range_t;
  123. typedef std::function<void(spv::Id&)> idfn_t;
  124. typedef std::function<bool(spv::Op, unsigned start)> instfn_t;
  125. // Special Values for ID map:
  126. static const spv::Id unmapped; // unchanged from default value
  127. static const spv::Id unused; // unused ID
  128. static const int header_size; // SPIR header = 5 words
  129. class id_iterator_t;
  130. // For mapping type entries between different shaders
  131. typedef std::vector<spirword_t> typeentry_t;
  132. typedef std::map<spv::Id, typeentry_t> globaltypes_t;
  133. // A set that preserves position order, and a reverse map
  134. typedef std::set<int> posmap_t;
  135. typedef std::unordered_map<spv::Id, int> posmap_rev_t;
  136. // Maps and ID to the size of its base type, if known.
  137. typedef std::unordered_map<spv::Id, unsigned> typesize_map_t;
  138. // handle error
  139. void error(const std::string& txt) const { errorLatch = true; errorHandler(txt); }
  140. bool isConstOp(spv::Op opCode) const;
  141. bool isTypeOp(spv::Op opCode) const;
  142. bool isStripOp(spv::Op opCode) const;
  143. bool isFlowCtrl(spv::Op opCode) const;
  144. range_t literalRange(spv::Op opCode) const;
  145. range_t typeRange(spv::Op opCode) const;
  146. range_t constRange(spv::Op opCode) const;
  147. unsigned typeSizeInWords(spv::Id id) const;
  148. unsigned idTypeSizeInWords(spv::Id id) const;
  149. spv::Id& asId(unsigned word) { return spv[word]; }
  150. const spv::Id& asId(unsigned word) const { return spv[word]; }
  151. spv::Op asOpCode(unsigned word) const { return opOpCode(spv[word]); }
  152. std::uint32_t asOpCodeHash(unsigned word);
  153. spv::Decoration asDecoration(unsigned word) const { return spv::Decoration(spv[word]); }
  154. unsigned asWordCount(unsigned word) const { return opWordCount(spv[word]); }
  155. spv::Id asTypeConstId(unsigned word) const { return asId(word + (isTypeOp(asOpCode(word)) ? 1 : 2)); }
  156. unsigned idPos(spv::Id id) const;
  157. static unsigned opWordCount(spirword_t data) { return data >> spv::WordCountShift; }
  158. static spv::Op opOpCode(spirword_t data) { return spv::Op(data & spv::OpCodeMask); }
  159. // Header access & set methods
  160. spirword_t magic() const { return spv[0]; } // return magic number
  161. spirword_t bound() const { return spv[3]; } // return Id bound from header
  162. spirword_t bound(spirword_t b) { return spv[3] = b; };
  163. spirword_t genmagic() const { return spv[2]; } // generator magic
  164. spirword_t genmagic(spirword_t m) { return spv[2] = m; }
  165. spirword_t schemaNum() const { return spv[4]; } // schema number from header
  166. // Mapping fns: get
  167. spv::Id localId(spv::Id id) const { return idMapL[id]; }
  168. // Mapping fns: set
  169. inline spv::Id localId(spv::Id id, spv::Id newId);
  170. void countIds(spv::Id id);
  171. // Return next unused new local ID.
  172. // NOTE: boost::dynamic_bitset would be more efficient due to find_next(),
  173. // which std::vector<bool> doens't have.
  174. inline spv::Id nextUnusedId(spv::Id id);
  175. void buildLocalMaps();
  176. std::string literalString(unsigned word) const; // Return literal as a std::string
  177. int literalStringWords(const std::string& str) const { return (int(str.size())+4)/4; }
  178. bool isNewIdMapped(spv::Id newId) const { return isMapped(newId); }
  179. bool isOldIdUnmapped(spv::Id oldId) const { return localId(oldId) == unmapped; }
  180. bool isOldIdUnused(spv::Id oldId) const { return localId(oldId) == unused; }
  181. bool isOldIdMapped(spv::Id oldId) const { return !isOldIdUnused(oldId) && !isOldIdUnmapped(oldId); }
  182. bool isFunction(spv::Id oldId) const { return fnPos.find(oldId) != fnPos.end(); }
  183. // bool matchType(const globaltypes_t& globalTypes, spv::Id lt, spv::Id gt) const;
  184. // spv::Id findType(const globaltypes_t& globalTypes, spv::Id lt) const;
  185. std::uint32_t hashType(unsigned typeStart) const;
  186. spirvbin_t& process(instfn_t, idfn_t, unsigned begin = 0, unsigned end = 0);
  187. int processInstruction(unsigned word, instfn_t, idfn_t);
  188. void validate() const;
  189. void mapTypeConst();
  190. void mapFnBodies();
  191. void optLoadStore();
  192. void dceFuncs();
  193. void dceVars();
  194. void dceTypes();
  195. void mapNames();
  196. void foldIds(); // fold IDs to smallest space
  197. void forwardLoadStores(); // load store forwarding (EXPERIMENTAL)
  198. void offsetIds(); // create relative offset IDs
  199. void applyMap(); // remap per local name map
  200. void mapRemainder(); // map any IDs we haven't touched yet
  201. void stripDebug(); // strip all debug info
  202. void stripDeadRefs(); // strips debug info for now-dead references after DCE
  203. void strip(); // remove debug symbols
  204. std::vector<spirword_t> spv; // SPIR words
  205. namemap_t nameMap; // ID names from OpName
  206. // Since we want to also do binary ops, we can't use std::vector<bool>. we could use
  207. // boost::dynamic_bitset, but we're trying to avoid a boost dependency.
  208. typedef std::uint64_t bits_t;
  209. std::vector<bits_t> mapped; // which new IDs have been mapped
  210. static const int mBits = sizeof(bits_t) * 4;
  211. bool isMapped(spv::Id id) const { return id < maxMappedId() && ((mapped[id/mBits] & (1LL<<(id%mBits))) != 0); }
  212. void setMapped(spv::Id id) { resizeMapped(id); mapped[id/mBits] |= (1LL<<(id%mBits)); }
  213. void resizeMapped(spv::Id id) { if (id >= maxMappedId()) mapped.resize(id/mBits+1, 0); }
  214. size_t maxMappedId() const { return mapped.size() * mBits; }
  215. // Add a strip range for a given instruction starting at 'start'
  216. // Note: avoiding brace initializers to please older versions os MSVC.
  217. void stripInst(unsigned start) { stripRange.push_back(range_t(start, start + asWordCount(start))); }
  218. // Function start and end. use unordered_map because we'll have
  219. // many fewer functions than IDs.
  220. std::unordered_map<spv::Id, range_t> fnPos;
  221. // Which functions are called, anywhere in the module, with a call count
  222. std::unordered_map<spv::Id, int> fnCalls;
  223. posmap_t typeConstPos; // word positions that define types & consts (ordered)
  224. posmap_rev_t idPosR; // reverse map from IDs to positions
  225. typesize_map_t idTypeSizeMap; // maps each ID to its type size, if known.
  226. std::vector<spv::Id> idMapL; // ID {M}ap from {L}ocal to {G}lobal IDs
  227. spv::Id entryPoint; // module entry point
  228. spv::Id largestNewId; // biggest new ID we have mapped anything to
  229. // Sections of the binary to strip, given as [begin,end)
  230. std::vector<range_t> stripRange;
  231. // processing options:
  232. std::uint32_t options;
  233. int verbose; // verbosity level
  234. // Error latch: this is set if the error handler is ever executed. It would be better to
  235. // use a try/catch block and throw, but that's not desired for certain environments, so
  236. // this is the alternative.
  237. mutable bool errorLatch;
  238. static errorfn_t errorHandler;
  239. static logfn_t logHandler;
  240. };
  241. } // namespace SPV
  242. #endif // defined (use_cpp11)
  243. #endif // SPIRVREMAPPER_H