• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2016 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 // This program demonstrates basic SPIR-V module processing using
16 // SPIRV-Tools C++ API:
17 // * Assembling
18 // * Validating
19 // * Optimizing
20 // * Disassembling
21 
22 #include <iostream>
23 #include <string>
24 #include <vector>
25 
26 #include "spirv-tools/libspirv.hpp"
27 #include "spirv-tools/optimizer.hpp"
28 
main()29 int main() {
30   const std::string source =
31       "         OpCapability Linkage "
32       "         OpCapability Shader "
33       "         OpMemoryModel Logical GLSL450 "
34       "         OpSource GLSL 450 "
35       "         OpDecorate %spec SpecId 1 "
36       "  %int = OpTypeInt 32 1 "
37       " %spec = OpSpecConstant %int 0 "
38       "%const = OpConstant %int 42";
39 
40   spvtools::SpirvTools core(SPV_ENV_UNIVERSAL_1_3);
41   spvtools::Optimizer opt(SPV_ENV_UNIVERSAL_1_3);
42 
43   auto print_msg_to_stderr = [](spv_message_level_t, const char*,
44                                 const spv_position_t&, const char* m) {
45     std::cerr << "error: " << m << std::endl;
46   };
47   core.SetMessageConsumer(print_msg_to_stderr);
48   opt.SetMessageConsumer(print_msg_to_stderr);
49 
50   std::vector<uint32_t> spirv;
51   if (!core.Assemble(source, &spirv)) return 1;
52   if (!core.Validate(spirv)) return 1;
53 
54   opt.RegisterPass(spvtools::CreateSetSpecConstantDefaultValuePass({{1, "42"}}))
55       .RegisterPass(spvtools::CreateFreezeSpecConstantValuePass())
56       .RegisterPass(spvtools::CreateUnifyConstantPass())
57       .RegisterPass(spvtools::CreateStripDebugInfoPass());
58   if (!opt.Run(spirv.data(), spirv.size(), &spirv)) return 1;
59 
60   std::string disassembly;
61   if (!core.Disassemble(spirv, &disassembly)) return 1;
62   std::cout << disassembly << "\n";
63 
64   return 0;
65 }
66