Merge pull request #20 from google/remove_exception
[platform/upstream/glslang.git] / StandAlone / spirv-remap.cpp
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 <iostream>
37 #include <fstream>
38 #include <cstring>
39 #include <stdexcept>
40
41 #include "../SPIRV/SPVRemapper.h"
42
43 namespace {
44
45     typedef unsigned int SpvWord;
46
47     // Poor man's basename: given a complete path, return file portion.
48     // E.g:
49     //      Linux:  /foo/bar/test  -> test
50     //      Win:   c:\foo\bar\test -> test
51     // It's not very efficient, but that doesn't matter for our minimal-duty use.
52     // Using boost::filesystem would be better in many ways, but want to avoid that dependency.
53
54     // OS dependent path separator (avoiding boost::filesystem dependency)
55 #if defined(_WIN32)
56     char path_sep_char() { return '\\'; }
57 #else
58     char path_sep_char() { return '/';  }
59 #endif
60
61     std::string basename(const std::string filename)
62     {
63         const size_t sepLoc = filename.find_last_of(path_sep_char());
64
65         return (sepLoc == filename.npos) ? filename : filename.substr(sepLoc+1);
66     }
67
68     void errHandler(const std::string& str) {
69         std::cout << str << std::endl;
70         exit(5);
71     }
72
73     void logHandler(const std::string& str) {
74         std::cout << str << std::endl;
75     }
76
77     // Read word stream from disk
78     void read(std::vector<SpvWord>& spv, const std::string& inFilename, int verbosity)
79     {
80         std::ifstream fp;
81
82         if (verbosity > 0)
83             logHandler(std::string("  reading: ") + inFilename);
84
85         spv.clear();
86         fp.open(inFilename, std::fstream::in | std::fstream::binary);
87
88         if (fp.fail())
89             errHandler("error opening file for read: ");
90
91         // Reserve space (for efficiency, not for correctness)
92         fp.seekg(0, fp.end);
93         spv.reserve(size_t(fp.tellg()) / sizeof(SpvWord));
94         fp.seekg(0, fp.beg);
95
96         while (!fp.eof()) {
97             SpvWord inWord;
98             fp.read((char *)&inWord, sizeof(inWord));
99
100             if (!fp.eof()) {
101                 spv.push_back(inWord);
102                 if (fp.fail())
103                     errHandler(std::string("error reading file: ") + inFilename);
104             }
105         }
106     }
107
108     void write(std::vector<SpvWord>& spv, const std::string& outFile, int verbosity)
109     {
110         if (outFile.empty())
111             errHandler("missing output filename.");
112
113         std::ofstream fp;
114
115         if (verbosity > 0)
116             logHandler(std::string("  writing: ") + outFile);
117
118         fp.open(outFile, std::fstream::out | std::fstream::binary);
119
120         if (fp.fail())
121             errHandler(std::string("error opening file for write: ") + outFile);
122
123         for (auto word : spv) {
124             fp.write((char *)&word, sizeof(word));
125             if (fp.fail())
126                 errHandler(std::string("error writing file: ") + outFile);
127         }
128
129         // file is closed by destructor
130     }
131
132     // Print helpful usage message to stdout, and exit
133     void usage(const char* const name, const char* const msg = 0)
134     {
135         if (msg)
136             std::cout << msg << std::endl << std::endl;
137
138         std::cout << "Usage: " << std::endl;
139
140         std::cout << "  " << basename(name)
141             << " [-v[v[...]] | --verbose [int]]"
142             << " [--map (all|types|names|funcs)]"
143             << " [--dce (all|types|funcs)]"
144             << " [--opt (all|loadstore)]"
145             << " [--strip-all | --strip all | -s]" 
146             << " [--do-everything]" 
147             << " --input | -i file1 [file2...] --output|-o DESTDIR"
148             << std::endl;
149
150         std::cout << "  " << basename(name) << " [--version | -V]" << std::endl;
151         std::cout << "  " << basename(name) << " [--help | -?]" << std::endl;
152
153         exit(5);
154     }
155
156     // grind through each SPIR in turn
157     void execute(const std::vector<std::string>& inputFile, const std::string& outputDir,
158         int opts, int verbosity)
159     {
160         for (const auto& filename : inputFile) {
161             std::vector<SpvWord> spv;
162             read(spv, filename, verbosity);
163             spv::spirvbin_t(verbosity).remap(spv, opts);
164
165             const std::string outfile = outputDir + path_sep_char() + basename(filename);
166
167             write(spv, outfile, verbosity);
168         }
169
170         if (verbosity > 0)
171             std::cout << "Done: " << inputFile.size() << " file(s) processed" << std::endl;
172     }
173
174     // Parse command line options
175     void parseCmdLine(int argc, char** argv, std::vector<std::string>& inputFile,
176         std::string& outputDir,
177         int& options,
178         int& verbosity)
179     {
180         if (argc < 2)
181             usage(argv[0]);
182
183         verbosity  = 0;
184         options    = spv::spirvbin_t::NONE;
185
186         // Parse command line.
187         // boost::program_options would be quite a bit nicer, but we don't want to
188         // introduce a dependency on boost.
189         for (int a=1; a<argc; ) {
190             const std::string arg = argv[a];
191
192             if (arg == "--output" || arg == "-o") {
193                 // Output directory
194                 if (++a >= argc)
195                     usage(argv[0], "--output requires an argument");
196                 if (!outputDir.empty())
197                     usage(argv[0], "--output can be provided only once");
198
199                 outputDir = argv[a++];
200
201                 // Remove trailing directory separator characters
202                 while (!outputDir.empty() && outputDir.back() == path_sep_char())
203                     outputDir.pop_back();
204
205             }
206             else if (arg == "-vv")     { verbosity = 2; ++a; } // verbosity shortcuts
207             else if (arg == "-vvv")    { verbosity = 3; ++a; } // ...
208             else if (arg == "-vvvv")   { verbosity = 4; ++a; } // ...
209             else if (arg == "-vvvvv")  { verbosity = 5; ++a; } // ...
210
211             else if (arg == "--verbose" || arg == "-v") {
212                 ++a;
213                 verbosity = 1;
214
215                 if (a < argc) {
216                     char* end_ptr = 0;
217                     int verb = ::strtol(argv[a], &end_ptr, 10);
218                     // If we have not read to the end of the string or
219                     // the string contained no elements, then we do not want to
220                     // store the value.
221                     if (*end_ptr == '\0' && end_ptr != argv[a]) {
222                         verbosity = verb;
223                         ++a;
224                     }
225                 }
226             }
227             else if (arg == "--version" || arg == "-V") {
228                 std::cout << basename(argv[0]) << " version 0.97 " << __DATE__ << " " << __TIME__ << std::endl;
229                 exit(0);
230             } else if (arg == "--input" || arg == "-i") {
231                 // Collect input files
232                 for (++a; a < argc && argv[a][0] != '-'; ++a)
233                     inputFile.push_back(argv[a]);
234             } else if (arg == "--do-everything") {
235                 ++a;
236                 options = options | spv::spirvbin_t::DO_EVERYTHING;
237             } else if (arg == "--strip-all" || arg == "-s") {
238                 ++a;
239                 options = options | spv::spirvbin_t::STRIP;
240             } else if (arg == "--strip") {
241                 ++a;
242                 if (strncmp(argv[a], "all", 3) == 0) {
243                     options = options | spv::spirvbin_t::STRIP;
244                     ++a;
245                 }
246             } else if (arg == "--dce") {
247                 // Parse comma (or colon, etc) separated list of things to dce
248                 ++a;
249                 for (const char* c = argv[a]; *c; ++c) {
250                     if (strncmp(c, "all", 3) == 0) {
251                         options = (options | spv::spirvbin_t::DCE_ALL);
252                         c += 3;
253                     } else if (strncmp(c, "*", 1) == 0) {
254                         options = (options | spv::spirvbin_t::DCE_ALL);
255                         c += 1;
256                     } else if (strncmp(c, "funcs", 5) == 0) {
257                         options = (options | spv::spirvbin_t::DCE_FUNCS);
258                         c += 5;
259                     } else if (strncmp(c, "types", 5) == 0) {
260                         options = (options | spv::spirvbin_t::DCE_TYPES);
261                         c += 5;
262                     }
263                 }
264                 ++a;
265             } else if (arg == "--map") {
266                 // Parse comma (or colon, etc) separated list of things to map
267                 ++a;
268                 for (const char* c = argv[a]; *c; ++c) {
269                     if (strncmp(c, "all", 3) == 0) {
270                         options = (options | spv::spirvbin_t::MAP_ALL);
271                         c += 3;
272                     } else if (strncmp(c, "*", 1) == 0) {
273                         options = (options | spv::spirvbin_t::MAP_ALL);
274                         c += 1;
275                     } else if (strncmp(c, "types", 5) == 0) {
276                         options = (options | spv::spirvbin_t::MAP_TYPES);
277                         c += 5;
278                     } else if (strncmp(c, "names", 5) == 0) {
279                         options = (options | spv::spirvbin_t::MAP_NAMES);
280                         c += 5;
281                     } else if (strncmp(c, "funcs", 5) == 0) {
282                         options = (options | spv::spirvbin_t::MAP_FUNCS);
283                         c += 5;
284                     }
285                 }
286                 ++a;
287             } else if (arg == "--opt") {
288                 ++a;
289                 for (const char* c = argv[a]; *c; ++c) {
290                     if (strncmp(c, "all", 3) == 0) {
291                         options = (options | spv::spirvbin_t::OPT_ALL);
292                         c += 3;
293                     } else if (strncmp(c, "*", 1) == 0) {
294                         options = (options | spv::spirvbin_t::OPT_ALL);
295                         c += 1;
296                     } else if (strncmp(c, "loadstore", 9) == 0) {
297                         options = (options | spv::spirvbin_t::OPT_LOADSTORE);
298                         c += 9;
299                     }
300                 }
301                 ++a;
302             } else if (arg == "--help" || arg == "-?") {
303                 usage(argv[0]);
304             } else {
305                 usage(argv[0], "Unknown command line option");
306             }
307         }
308     }
309
310 } // namespace
311
312
313 int main(int argc, char** argv)
314 {
315     std::vector<std::string> inputFile;
316     std::string              outputDir;
317     int                      opts;
318     int                      verbosity;
319
320 #ifdef use_cpp11
321     // handle errors by exiting
322     spv::spirvbin_t::registerErrorHandler(errHandler);
323
324     // Log messages to std::cout
325     spv::spirvbin_t::registerLogHandler(logHandler);
326 #endif
327
328     if (argc < 2)
329         usage(argv[0]);
330
331     parseCmdLine(argc, argv, inputFile, outputDir, opts, verbosity);
332
333     if (outputDir.empty())
334         usage(argv[0], "Output directory required");
335
336     std::string errmsg;
337
338     // Main operations: read, remap, and write.
339     execute(inputFile, outputDir, opts, verbosity);
340
341     // If we get here, everything went OK!  Nothing more to be done.
342 }