1 // Copyright 2019 The Amber Authors.
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 #include "src/dxc_helper.h"
16
17 #include <algorithm>
18 #include <sstream>
19
20 #include "src/platform.h"
21 #include "src/virtual_file_store.h"
22
23 #if AMBER_PLATFORM_WINDOWS
24 #pragma warning(push)
25 #pragma warning(disable : 4267)
26 #pragma warning(disable : 4003)
27 #endif // AMBER_PLATFORM_WINDOWS
28
29 #pragma clang diagnostic push
30 #pragma clang diagnostic ignored "-Wreserved-id-macro"
31 #pragma clang diagnostic ignored "-Wextra-semi"
32 #pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
33 #pragma clang diagnostic ignored "-Wold-style-cast"
34 #pragma clang diagnostic ignored "-Wshadow-field-in-constructor"
35 #pragma clang diagnostic ignored "-Wconversion"
36 #pragma clang diagnostic ignored "-Wsign-conversion"
37 #pragma clang diagnostic ignored "-Wshadow"
38 #pragma clang diagnostic ignored "-Wweak-vtables"
39 #pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
40 #pragma clang diagnostic ignored "-Wundef"
41 #pragma clang diagnostic ignored "-Wunused-function"
42 #pragma clang diagnostic ignored "-Wunused-parameter"
43 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
44 #pragma GCC diagnostic push
45 #pragma GCC diagnostic ignored "-Wunused-function"
46 #pragma GCC diagnostic ignored "-Wunused-parameter"
47 #ifndef __STDC_LIMIT_MACROS
48 #define __STDC_LIMIT_MACROS
49 #endif // __STDC_LIMIT_MACROS
50 #ifndef __STDC_CONSTANT_MACROS
51 #define __STDC_CONSTANT_MACROS
52 #endif // __STDC_CONSTANT_MACROS
53
54 // clang-format off
55 // The order here matters, so don't reformat.
56 #include "dxc/Support/Global.h"
57 #include "dxc/Support/HLSLOptions.h"
58 #include "dxc/dxcapi.h"
59 #include "dxc/Support/microcom.h"
60 // clang-format on
61
62 namespace amber {
63 namespace dxchelper {
64 namespace {
65
66 const wchar_t* kDxcFlags[] = {
67 L"-spirv", // SPIR-V compilation
68 L"-fcgl", // No SPIR-V Optimization
69 L"-enable-16bit-types", // Enabling 16bit types
70 };
71 const size_t kDxcFlagsCount = sizeof(kDxcFlags) / sizeof(const wchar_t*);
72
73 // Converts an IDxcBlob into a vector of 32-bit unsigned integers which
74 // is returned via the 'binaryWords' argument.
ConvertIDxcBlobToUint32(IDxcBlob * blob,std::vector<uint32_t> * binaryWords)75 void ConvertIDxcBlobToUint32(IDxcBlob* blob,
76 std::vector<uint32_t>* binaryWords) {
77 size_t num32BitWords = (blob->GetBufferSize() + 3) / 4;
78 std::string binaryStr(static_cast<char*>(blob->GetBufferPointer()),
79 blob->GetBufferSize());
80 binaryStr.resize(num32BitWords * 4, 0);
81 binaryWords->resize(num32BitWords, 0);
82 memcpy(binaryWords->data(), binaryStr.data(), binaryStr.size());
83 }
84
85 class IncludeHandler : public IDxcIncludeHandler {
86 public:
IncludeHandler(const VirtualFileStore * file_store,IDxcLibrary * dxc_lib,IDxcIncludeHandler * fallback)87 IncludeHandler(const VirtualFileStore* file_store,
88 IDxcLibrary* dxc_lib,
89 IDxcIncludeHandler* fallback)
90 : file_store_(file_store), dxc_lib_(dxc_lib), fallback_(fallback) {}
91
LoadSource(LPCWSTR pFilename,IDxcBlob ** ppIncludeSource)92 HRESULT STDMETHODCALLTYPE LoadSource(LPCWSTR pFilename,
93 IDxcBlob** ppIncludeSource) override {
94 std::wstring wide_path(pFilename);
95 std::string path = std::string(wide_path.begin(), wide_path.end());
96
97 std::string content;
98 Result r = file_store_->Get(path, &content);
99 if (r.IsSuccess()) {
100 IDxcBlobEncoding* source;
101 auto res = dxc_lib_->CreateBlobWithEncodingOnHeapCopy(
102 content.data(), static_cast<uint32_t>(content.size()), CP_UTF8,
103 &source);
104 if (res != S_OK) {
105 DxcCleanupThreadMalloc();
106 return res;
107 }
108 *ppIncludeSource = source;
109 return S_OK;
110 }
111
112 return fallback_->LoadSource(pFilename, ppIncludeSource);
113 }
114
QueryInterface(REFIID iid,void ** ppvObject)115 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,
116 void** ppvObject) override {
117 return DoBasicQueryInterface<IDxcIncludeHandler>(this, iid, ppvObject);
118 }
119
120 private:
121 const VirtualFileStore* const file_store_;
122 IDxcLibrary* const dxc_lib_;
123 IDxcIncludeHandler* const fallback_;
124 };
125
126 #pragma GCC diagnostic pop
127 #pragma clang diagnostic pop
128 #if AMBER_PLATFORM_WINDOWS
129 #pragma warning(pop)
130 #endif // AMBER_PLATFORM_WINDOWS
131
132 } // namespace
133
Compile(const std::string & src,const std::string & entry,const std::string & profile,const std::string & spv_env,const std::string & filename,const VirtualFileStore * virtual_files,std::vector<uint32_t> * generated_binary)134 Result Compile(const std::string& src,
135 const std::string& entry,
136 const std::string& profile,
137 const std::string& spv_env,
138 const std::string& filename,
139 const VirtualFileStore* virtual_files,
140 std::vector<uint32_t>* generated_binary) {
141 if (hlsl::options::initHlslOptTable()) {
142 DxcCleanupThreadMalloc();
143 return Result("DXC compile failure: initHlslOptTable");
144 }
145
146 IDxcLibrary* dxc_lib;
147 if (DxcCreateInstance(CLSID_DxcLibrary, __uuidof(IDxcLibrary),
148 reinterpret_cast<void**>(&dxc_lib)) < 0) {
149 DxcCleanupThreadMalloc();
150 return Result("DXCCreateInstance for DXCLibrary failed");
151 }
152
153 IDxcBlobEncoding* source;
154 if (dxc_lib->CreateBlobWithEncodingOnHeapCopy(
155 src.data(), static_cast<uint32_t>(src.size()), CP_UTF8, &source) <
156 0) {
157 DxcCleanupThreadMalloc();
158 return Result("DXC compile failure: CreateBlobFromFile");
159 }
160
161 IDxcIncludeHandler* fallback_include_handler;
162 if (dxc_lib->CreateIncludeHandler(&fallback_include_handler) < 0) {
163 DxcCleanupThreadMalloc();
164 return Result("DXC compile failure: CreateIncludeHandler");
165 }
166
167 CComPtr<IDxcIncludeHandler> include_handler(
168 new IncludeHandler(virtual_files, dxc_lib, fallback_include_handler));
169
170 IDxcCompiler* compiler;
171 if (DxcCreateInstance(CLSID_DxcCompiler, __uuidof(IDxcCompiler),
172 reinterpret_cast<void**>(&compiler)) < 0) {
173 DxcCleanupThreadMalloc();
174 return Result("DXCCreateInstance for DXCCompiler failed");
175 }
176
177 std::string filepath = filename.empty() ? ("amber." + profile) : filename;
178
179 std::vector<const wchar_t*> dxc_flags(kDxcFlags, &kDxcFlags[kDxcFlagsCount]);
180
181 const wchar_t* target_env = nullptr;
182 if (!spv_env.compare("spv1.3") || !spv_env.compare("vulkan1.1")) {
183 target_env = L"-fspv-target-env=vulkan1.1";
184 } else if (!spv_env.compare("spv1.0") || !spv_env.compare("vulkan1.0")) {
185 target_env = L"-fspv-target-env=vulkan1.0";
186 } else if (!spv_env.empty()) {
187 return Result(
188 "Invalid target environment. Choose spv1.3 or vulkan1.1 for vulkan1.1 "
189 "and spv1.0 or vulkan1.0 for vulkan1.0.");
190 }
191 if (target_env)
192 dxc_flags.push_back(target_env);
193
194 IDxcOperationResult* result;
195 if (compiler->Compile(
196 source, /* source text */
197 std::wstring(filepath.begin(), filepath.end())
198 .c_str(), /* original file source */
199 std::wstring(entry.begin(), entry.end())
200 .c_str(), /* entry point name */
201 std::wstring(profile.begin(), profile.end())
202 .c_str(), /* shader profile to compile */
203 dxc_flags.data(), /* arguments */
204 static_cast<uint32_t>(dxc_flags.size()), /* argument count */
205 nullptr, /* defines */
206 0, /* define count */
207 include_handler, /* handler for #include */
208 &result /* output status */) < 0) {
209 DxcCleanupThreadMalloc();
210 return Result("DXC compile failure: Compile");
211 }
212
213 // Compilation is done. We can clean up the HlslOptTable.
214 hlsl::options::cleanupHlslOptTable();
215
216 // Get compilation results.
217 HRESULT result_status;
218 if (result->GetStatus(&result_status) < 0) {
219 DxcCleanupThreadMalloc();
220 return Result("DXC compile failure: GetStatus");
221 }
222
223 // Get diagnostics string.
224 IDxcBlobEncoding* error_buffer;
225 if (result->GetErrorBuffer(&error_buffer)) {
226 DxcCleanupThreadMalloc();
227 return Result("DXC compile failure: GetErrorBuffer");
228 }
229
230 const std::string diagnostics(
231 static_cast<char*>(error_buffer->GetBufferPointer()),
232 error_buffer->GetBufferSize());
233
234 bool success = true;
235 if (static_cast<HRESULT>(result_status) >= 0) {
236 IDxcBlob* compiled_blob;
237 if (result->GetResult(&compiled_blob) < 0) {
238 DxcCleanupThreadMalloc();
239 return Result("DXC compile failure: GetResult");
240 }
241 ConvertIDxcBlobToUint32(compiled_blob, generated_binary);
242 } else {
243 success = false;
244 }
245
246 DxcCleanupThreadMalloc();
247 return success ? Result() : Result("DXC compile failure: " + diagnostics);
248 }
249
250 } // namespace dxchelper
251 } // namespace amber
252