Path: blob/master/thirdparty/glslang/SPIRV/SPVRemapper.h
9903 views
//1// Copyright (C) 2015 LunarG, Inc.2//3// All rights reserved.4//5// Redistribution and use in source and binary forms, with or without6// modification, are permitted provided that the following conditions7// are met:8//9// Redistributions of source code must retain the above copyright10// notice, this list of conditions and the following disclaimer.11//12// Redistributions in binary form must reproduce the above13// copyright notice, this list of conditions and the following14// disclaimer in the documentation and/or other materials provided15// with the distribution.16//17// Neither the name of 3Dlabs Inc. Ltd. nor the names of its18// contributors may be used to endorse or promote products derived19// from this software without specific prior written permission.20//21// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS22// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT23// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS24// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE25// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,26// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,27// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;28// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER29// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT30// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN31// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE32// POSSIBILITY OF SUCH DAMAGE.33//3435#ifndef SPIRVREMAPPER_H36#define SPIRVREMAPPER_H3738#include <string>39#include <vector>40#include <cstdlib>41#include <exception>4243namespace spv {4445class spirvbin_base_t46{47public:48enum Options {49NONE = 0,50STRIP = (1<<0),51MAP_TYPES = (1<<1),52MAP_NAMES = (1<<2),53MAP_FUNCS = (1<<3),54DCE_FUNCS = (1<<4),55DCE_VARS = (1<<5),56DCE_TYPES = (1<<6),57OPT_LOADSTORE = (1<<7),58OPT_FWD_LS = (1<<8), // EXPERIMENTAL: PRODUCES INVALID SCHEMA-0 SPIRV59MAP_ALL = (MAP_TYPES | MAP_NAMES | MAP_FUNCS),60DCE_ALL = (DCE_FUNCS | DCE_VARS | DCE_TYPES),61OPT_ALL = (OPT_LOADSTORE),6263ALL_BUT_STRIP = (MAP_ALL | DCE_ALL | OPT_ALL),64DO_EVERYTHING = (STRIP | ALL_BUT_STRIP)65};66};6768} // namespace SPV6970#include <functional>71#include <cstdint>72#include <unordered_map>73#include <unordered_set>74#include <map>75#include <set>76#include <cassert>7778#include "spirv.hpp"7980namespace spv {81const Id NoResult = 0;8283// class to hold SPIR-V binary data for remapping, DCE, and debug stripping84class spirvbin_t : public spirvbin_base_t85{86public:87spirvbin_t(int verbose = 0) : entryPoint(spv::NoResult), largestNewId(0), verbose(verbose), errorLatch(false)88{ }8990virtual ~spirvbin_t() { }9192// remap on an existing binary in memory93void remap(std::vector<std::uint32_t>& spv, const std::vector<std::string>& whiteListStrings,94std::uint32_t opts = DO_EVERYTHING);9596// remap on an existing binary in memory - legacy interface without white list97void remap(std::vector<std::uint32_t>& spv, std::uint32_t opts = DO_EVERYTHING);9899// Type for error/log handler functions100typedef std::function<void(const std::string&)> errorfn_t;101typedef std::function<void(const std::string&)> logfn_t;102103// Register error/log handling functions (can be lambda fn / functor / etc)104static void registerErrorHandler(errorfn_t handler) { errorHandler = handler; }105static void registerLogHandler(logfn_t handler) { logHandler = handler; }106107protected:108// This can be overridden to provide other message behavior if needed109virtual void msg(int minVerbosity, int indent, const std::string& txt) const;110111private:112// Local to global, or global to local ID map113typedef std::unordered_map<spv::Id, spv::Id> idmap_t;114typedef std::unordered_set<spv::Id> idset_t;115typedef std::unordered_map<spv::Id, int> blockmap_t;116117void remap(std::uint32_t opts = DO_EVERYTHING);118119// Map of names to IDs120typedef std::unordered_map<std::string, spv::Id> namemap_t;121122typedef std::uint32_t spirword_t;123124typedef std::pair<unsigned, unsigned> range_t;125typedef std::function<void(spv::Id&)> idfn_t;126typedef std::function<bool(spv::Op, unsigned start)> instfn_t;127128// Special Values for ID map:129static const spv::Id unmapped; // unchanged from default value130static const spv::Id unused; // unused ID131static const int header_size; // SPIR header = 5 words132133class id_iterator_t;134135// For mapping type entries between different shaders136typedef std::vector<spirword_t> typeentry_t;137typedef std::map<spv::Id, typeentry_t> globaltypes_t;138139// A set that preserves position order, and a reverse map140typedef std::set<int> posmap_t;141typedef std::unordered_map<spv::Id, int> posmap_rev_t;142143// Maps and ID to the size of its base type, if known.144typedef std::unordered_map<spv::Id, unsigned> typesize_map_t;145146// handle error147void error(const std::string& txt) const { errorLatch = true; errorHandler(txt); }148149bool isConstOp(spv::Op opCode) const;150bool isTypeOp(spv::Op opCode) const;151bool isStripOp(spv::Op opCode) const;152bool isFlowCtrl(spv::Op opCode) const;153range_t literalRange(spv::Op opCode) const;154range_t typeRange(spv::Op opCode) const;155range_t constRange(spv::Op opCode) const;156unsigned typeSizeInWords(spv::Id id) const;157unsigned idTypeSizeInWords(spv::Id id) const;158159bool isStripOp(spv::Op opCode, unsigned start) const;160161spv::Id& asId(unsigned word) { return spv[word]; }162const spv::Id& asId(unsigned word) const { return spv[word]; }163spv::Op asOpCode(unsigned word) const { return opOpCode(spv[word]); }164std::uint32_t asOpCodeHash(unsigned word);165spv::Decoration asDecoration(unsigned word) const { return spv::Decoration(spv[word]); }166unsigned asWordCount(unsigned word) const { return opWordCount(spv[word]); }167spv::Id asTypeConstId(unsigned word) const { return asId(word + (isTypeOp(asOpCode(word)) ? 1 : 2)); }168unsigned idPos(spv::Id id) const;169170static unsigned opWordCount(spirword_t data) { return data >> spv::WordCountShift; }171static spv::Op opOpCode(spirword_t data) { return spv::Op(data & spv::OpCodeMask); }172173// Header access & set methods174spirword_t magic() const { return spv[0]; } // return magic number175spirword_t bound() const { return spv[3]; } // return Id bound from header176spirword_t bound(spirword_t b) { return spv[3] = b; }177spirword_t genmagic() const { return spv[2]; } // generator magic178spirword_t genmagic(spirword_t m) { return spv[2] = m; }179spirword_t schemaNum() const { return spv[4]; } // schema number from header180181// Mapping fns: get182spv::Id localId(spv::Id id) const { return idMapL[id]; }183184// Mapping fns: set185inline spv::Id localId(spv::Id id, spv::Id newId);186void countIds(spv::Id id);187188// Return next unused new local ID.189// NOTE: boost::dynamic_bitset would be more efficient due to find_next(),190// which std::vector<bool> doens't have.191inline spv::Id nextUnusedId(spv::Id id);192193void buildLocalMaps();194std::string literalString(unsigned word) const; // Return literal as a std::string195int literalStringWords(const std::string& str) const { return (int(str.size())+4)/4; }196197bool isNewIdMapped(spv::Id newId) const { return isMapped(newId); }198bool isOldIdUnmapped(spv::Id oldId) const { return localId(oldId) == unmapped; }199bool isOldIdUnused(spv::Id oldId) const { return localId(oldId) == unused; }200bool isOldIdMapped(spv::Id oldId) const { return !isOldIdUnused(oldId) && !isOldIdUnmapped(oldId); }201bool isFunction(spv::Id oldId) const { return fnPos.find(oldId) != fnPos.end(); }202203// bool matchType(const globaltypes_t& globalTypes, spv::Id lt, spv::Id gt) const;204// spv::Id findType(const globaltypes_t& globalTypes, spv::Id lt) const;205std::uint32_t hashType(unsigned typeStart) const;206207spirvbin_t& process(instfn_t, idfn_t, unsigned begin = 0, unsigned end = 0);208int processInstruction(unsigned word, instfn_t, idfn_t);209210void validate() const;211void mapTypeConst();212void mapFnBodies();213void optLoadStore();214void dceFuncs();215void dceVars();216void dceTypes();217void mapNames();218void foldIds(); // fold IDs to smallest space219void forwardLoadStores(); // load store forwarding (EXPERIMENTAL)220void offsetIds(); // create relative offset IDs221222void applyMap(); // remap per local name map223void mapRemainder(); // map any IDs we haven't touched yet224void stripDebug(); // strip all debug info225void stripDeadRefs(); // strips debug info for now-dead references after DCE226void strip(); // remove debug symbols227228std::vector<spirword_t> spv; // SPIR words229230std::vector<std::string> stripWhiteList;231232namemap_t nameMap; // ID names from OpName233234// Since we want to also do binary ops, we can't use std::vector<bool>. we could use235// boost::dynamic_bitset, but we're trying to avoid a boost dependency.236typedef std::uint64_t bits_t;237std::vector<bits_t> mapped; // which new IDs have been mapped238static const int mBits = sizeof(bits_t) * 4;239240bool isMapped(spv::Id id) const { return id < maxMappedId() && ((mapped[id/mBits] & (1LL<<(id%mBits))) != 0); }241void setMapped(spv::Id id) { resizeMapped(id); mapped[id/mBits] |= (1LL<<(id%mBits)); }242void resizeMapped(spv::Id id) { if (id >= maxMappedId()) mapped.resize(id/mBits+1, 0); }243size_t maxMappedId() const { return mapped.size() * mBits; }244245// Add a strip range for a given instruction starting at 'start'246// Note: avoiding brace initializers to please older versions os MSVC.247void stripInst(unsigned start) { stripRange.push_back(range_t(start, start + asWordCount(start))); }248249// Function start and end. use unordered_map because we'll have250// many fewer functions than IDs.251std::unordered_map<spv::Id, range_t> fnPos;252253// Which functions are called, anywhere in the module, with a call count254std::unordered_map<spv::Id, int> fnCalls;255256posmap_t typeConstPos; // word positions that define types & consts (ordered)257posmap_rev_t idPosR; // reverse map from IDs to positions258typesize_map_t idTypeSizeMap; // maps each ID to its type size, if known.259260std::vector<spv::Id> idMapL; // ID {M}ap from {L}ocal to {G}lobal IDs261262spv::Id entryPoint; // module entry point263spv::Id largestNewId; // biggest new ID we have mapped anything to264265// Sections of the binary to strip, given as [begin,end)266std::vector<range_t> stripRange;267268// processing options:269std::uint32_t options;270int verbose; // verbosity level271272// Error latch: this is set if the error handler is ever executed. It would be better to273// use a try/catch block and throw, but that's not desired for certain environments, so274// this is the alternative.275mutable bool errorLatch;276277static errorfn_t errorHandler;278static logfn_t logHandler;279};280281} // namespace SPV282283#endif // SPIRVREMAPPER_H284285286