xref: /aosp_15_r20/external/swiftshader/src/Pipeline/SpirvProfiler.hpp (revision 03ce13f70fcc45d86ee91b7ee4cab1936a95046e)
1 // Copyright 2022 The SwiftShader Authors. All Rights Reserved.
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 #ifndef sw_SpirvProfiler_hpp
16 #define sw_SpirvProfiler_hpp
17 
18 #include "System/SwiftConfig.hpp"
19 
20 #define SPV_ENABLE_UTILITY_CODE
21 #include <spirv/unified1/spirv.hpp>
22 
23 #include "marl/mutex.h"
24 
25 #include <atomic>
26 #include <cstdint>
27 #include <thread>
28 #include <unordered_map>
29 
30 namespace sw {
31 
32 // SpirvProfileData contains bookkeeping data structures for SPIR-V
33 // instrumentation.
34 class SpirvProfileData
35 {
36 public:
37 	SpirvProfileData() = default;
38 	SpirvProfileData(const SpirvProfileData &) = delete;
39 	SpirvProfileData(SpirvProfileData &&) = delete;
40 	SpirvProfileData &operator=(const SpirvProfileData &) = delete;
41 	SpirvProfileData &operator=(SpirvProfileData &&) = delete;
42 
43 	// SPIR-V instruction execution count, by opcode.
44 	std::unordered_map<spv::Op, int64_t> spvOpExecutionCount;
45 };
46 
47 class SpirvProfiler
48 {
49 public:
50 	SpirvProfiler(const Configuration &config);
51 	~SpirvProfiler();
52 
53 	void RegisterShaderForProfiling(std::string shaderId, std::unique_ptr<SpirvProfileData> profData);
54 
55 private:
56 	void ReportSnapshot();
57 	std::unordered_map<std::string, SpirvProfileData *> GetRegisteredProfilesSnapshot();
58 
59 	const Configuration &cfg;
60 	std::string reportFilePath;
61 
62 	std::thread reportThread;
63 	std::atomic<bool> reportThreadStop;
64 
65 	// Map from shader ID to associated profile data.
66 	std::unordered_map<std::string, std::unique_ptr<SpirvProfileData>> shaderProfiles GUARDED_BY(profileMux);
67 	marl::mutex profileMux;
68 };
69 
70 }  // namespace sw
71 
72 #endif  // sw_SpirvProfiler_hpp