1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
|
// Compiler.cpp : Defines the entry point for the console application.
//
#include "../core/basic.h"
#include "../core/slang-io.h"
#include "compiler.h"
#include "lexer.h"
#include "parameter-binding.h"
#include "parser.h"
#include "preprocessor.h"
#include "syntax-visitors.h"
#include "slang-stdlib.h"
#include "reflection.h"
#include "emit.h"
// Utilities for pass-through modes
#include "../../tools/glslang/glslang.h"
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#undef WIN32_LEAN_AND_MEAN
#undef NOMINMAX
#include <d3dcompiler.h>
#endif
#ifdef CreateDirectory
#undef CreateDirectory
#endif
namespace Slang
{
// CompileResult
void CompileResult::append(CompileResult const& result)
{
// Find which to append to
ResultFormat appendTo = ResultFormat::None;
if (format == ResultFormat::None)
{
format = result.format;
appendTo = result.format;
}
else if (format == result.format)
{
appendTo = format;
}
if (appendTo == ResultFormat::Text)
{
outputString.append(result.outputString.Buffer());
}
else if (appendTo == ResultFormat::Binary)
{
outputBinary.AddRange(result.outputBinary.Buffer(), result.outputBinary.Count());
}
}
// EntryPointRequest
TranslationUnitRequest* EntryPointRequest::getTranslationUnit()
{
return compileRequest->translationUnits[translationUnitIndex].Ptr();
}
//
Profile Profile::LookUp(char const* name)
{
#define PROFILE(TAG, NAME, STAGE, VERSION) if(strcmp(name, #NAME) == 0) return Profile::TAG;
#define PROFILE_ALIAS(TAG, NAME) if(strcmp(name, #NAME) == 0) return Profile::TAG;
#include "profile-defs.h"
return Profile::Unknown;
}
//
String emitHLSLForEntryPoint(
EntryPointRequest* entryPoint)
{
auto compileRequest = entryPoint->compileRequest;
auto translationUnit = entryPoint->getTranslationUnit();
if (compileRequest->passThrough != PassThroughMode::None)
{
// Generate a string that includes the content of
// the source file(s), along with a line directive
// to ensure that we get reasonable messages
// from the downstream compiler when in pass-through
// mode.
StringBuilder codeBuilder;
for(auto sourceFile : translationUnit->sourceFiles)
{
codeBuilder << "#line 1 \"";
for(auto c : sourceFile->path)
{
char buffer[] = { c, 0 };
switch(c)
{
default:
codeBuilder << buffer;
break;
case '\\':
codeBuilder << "\\\\";
}
}
codeBuilder << "\"\n";
codeBuilder << sourceFile->content << "\n";
}
return codeBuilder.ProduceString();
}
else
{
return emitEntryPoint(
entryPoint,
compileRequest->layout.Ptr(),
CodeGenTarget::HLSL);
}
}
String emitGLSLForEntryPoint(
EntryPointRequest* entryPoint)
{
auto compileRequest = entryPoint->compileRequest;
auto translationUnit = entryPoint->getTranslationUnit();
if (compileRequest->passThrough != PassThroughMode::None)
{
// Generate a string that includes the content of
// the source file(s), along with a line directive
// to ensure that we get reasonable messages
// from the downstream compiler when in pass-through
// mode.
StringBuilder codeBuilder;
int translationUnitCounter = 0;
for(auto sourceFile : translationUnit->sourceFiles)
{
int translationUnitIndex = translationUnitCounter++;
// We want to output `#line` directives, but we need
// to skip this for the first file, since otherwise
// some GLSL implementations will get tripped up by
// not having the `#version` directive be the first
// thing in the file.
if(translationUnitIndex != 0)
{
codeBuilder << "#line 1 " << translationUnitIndex << "\n";
}
codeBuilder << sourceFile->content << "\n";
}
return codeBuilder.ProduceString();
}
else
{
// TODO(tfoley): need to pass along the entry point
// so that we properly emit it as the `main` function.
return emitEntryPoint(
entryPoint,
compileRequest->layout.Ptr(),
CodeGenTarget::GLSL);
}
}
char const* GetHLSLProfileName(Profile profile)
{
switch(profile.raw)
{
#define PROFILE(TAG, NAME, STAGE, VERSION) case Profile::TAG: return #NAME;
#include "profile-defs.h"
default:
// TODO: emit an error here!
return "unknown";
}
}
#ifdef _WIN32
void* GetD3DCompilerDLL()
{
// TODO(tfoley): let user specify version of d3dcompiler DLL to use.
static HMODULE d3dCompiler = LoadLibraryA("d3dcompiler_47");
// TODO(tfoley): handle case where we can't find it gracefully
assert(d3dCompiler);
return d3dCompiler;
}
List<uint8_t> EmitDXBytecodeForEntryPoint(
EntryPointRequest* entryPoint)
{
static pD3DCompile D3DCompile_ = nullptr;
if (!D3DCompile_)
{
HMODULE d3dCompiler = (HMODULE)GetD3DCompilerDLL();
assert(d3dCompiler);
D3DCompile_ = (pD3DCompile)GetProcAddress(d3dCompiler, "D3DCompile");
assert(D3DCompile_);
}
auto hlslCode = emitHLSLForEntryPoint(entryPoint);
ID3DBlob* codeBlob;
ID3DBlob* diagnosticsBlob;
HRESULT hr = D3DCompile_(
hlslCode.begin(),
hlslCode.Length(),
"slang",
nullptr,
nullptr,
entryPoint->name.begin(),
GetHLSLProfileName(entryPoint->profile),
0,
0,
&codeBlob,
&diagnosticsBlob);
List<uint8_t> data;
if (codeBlob)
{
data.AddRange((uint8_t const*)codeBlob->GetBufferPointer(), (int)codeBlob->GetBufferSize());
codeBlob->Release();
}
if (diagnosticsBlob)
{
// TODO(tfoley): need a better policy for how we translate diagnostics
// back into the Slang world (although we should always try to generate
// HLSL that doesn't produce any diagnostics...)
String diagnostics = (char const*) diagnosticsBlob->GetBufferPointer();
fprintf(stderr, "%s", diagnostics.begin());
OutputDebugStringA(diagnostics.begin());
diagnosticsBlob->Release();
}
if (FAILED(hr))
{
// TODO(tfoley): What to do on failure?
exit(1);
}
return data;
}
#if 0
List<uint8_t> EmitDXBytecode(
ExtraContext& context)
{
if(context.getTranslationUnitOptions().entryPoints.Count() != 1)
{
if(context.getTranslationUnitOptions().entryPoints.Count() == 0)
{
// TODO(tfoley): need to write diagnostics into this whole thing...
fprintf(stderr, "no entry point specified\n");
}
else
{
fprintf(stderr, "multiple entry points specified\n");
}
return List<uint8_t>();
}
return EmitDXBytecodeForEntryPoint(context, context.getTranslationUnitOptions().entryPoints[0]);
}
#endif
String EmitDXBytecodeAssemblyForEntryPoint(
EntryPointRequest* entryPoint)
{
static pD3DDisassemble D3DDisassemble_ = nullptr;
if (!D3DDisassemble_)
{
HMODULE d3dCompiler = (HMODULE)GetD3DCompilerDLL();
assert(d3dCompiler);
D3DDisassemble_ = (pD3DDisassemble)GetProcAddress(d3dCompiler, "D3DDisassemble");
assert(D3DDisassemble_);
}
List<uint8_t> dxbc = EmitDXBytecodeForEntryPoint(entryPoint);
if (!dxbc.Count())
{
return String();
}
ID3DBlob* codeBlob;
HRESULT hr = D3DDisassemble_(
&dxbc[0],
dxbc.Count(),
0,
nullptr,
&codeBlob);
String result;
if (codeBlob)
{
char const* codeBegin = (char const*)codeBlob->GetBufferPointer();
char const* codeEnd = codeBegin + codeBlob->GetBufferSize();
result.append(codeBegin, codeEnd);
codeBlob->Release();
}
if (FAILED(hr))
{
// TODO(tfoley): need to figure out what to diagnose here...
}
return result;
}
#if 0
String EmitDXBytecodeAssembly(
ExtraContext& context)
{
if(context.getTranslationUnitOptions().entryPoints.Count() == 0)
{
// TODO(tfoley): need to write diagnostics into this whole thing...
fprintf(stderr, "no entry point specified\n");
return "";
}
StringBuilder sb;
for (auto entryPoint : context.getTranslationUnitOptions().entryPoints)
{
sb << EmitDXBytecodeAssemblyForEntryPoint(context, entryPoint);
}
return sb.ProduceString();
}
#endif
HMODULE getGLSLCompilerDLL()
{
// TODO(tfoley): let user specify version of glslang DLL to use.
static HMODULE glslCompiler = LoadLibraryA("glslang");
// TODO(tfoley): handle case where we can't find it gracefully
assert(glslCompiler);
return glslCompiler;
}
int invokeGLSLCompilerForEntryPoint(
EntryPointRequest* entryPoint,
glslang_CompileRequest& request)
{
String rawGLSL = emitGLSLForEntryPoint(entryPoint);
static glslang_CompileFunc glslang_compile = nullptr;
if (!glslang_compile)
{
HMODULE glslCompiler = getGLSLCompilerDLL();
assert(glslCompiler);
glslang_compile = (glslang_CompileFunc)GetProcAddress(glslCompiler, "glslang_compile");
assert(glslang_compile);
}
String diagnosticOutput;
auto diagnosticOutputFunc = [](void const* data, size_t size, void* userData)
{
(*(String*)userData).append((char const*)data, (char const*)data + size);
};
request.sourcePath = "slang";
request.sourceText = rawGLSL.begin();
request.slangStage = (SlangStage)entryPoint->profile.GetStage();
request.diagnosticFunc = diagnosticOutputFunc;
request.diagnosticUserData = &diagnosticOutput;
int err = glslang_compile(&request);
if (err)
{
OutputDebugStringA(diagnosticOutput.Buffer());
fprintf(stderr, "%s", diagnosticOutput.Buffer());
exit(1);
}
return 0;
}
List<uint8_t> emitSPIRVForEntryPoint(
EntryPointRequest* entryPoint)
{
List<uint8_t> output;
auto outputFunc = [](void const* data, size_t size, void* userData)
{
((List<uint8_t>*)userData)->AddRange((uint8_t*)data, size);
};
glslang_CompileRequest request;
request.outputFunc = outputFunc;
request.outputUserData = &output;
request.disassembleResult = false;
int err = invokeGLSLCompilerForEntryPoint(entryPoint, request);
if (err)
{
return List<uint8_t>();
}
return output;
}
String emitSPIRVAssemblyForEntryPoint(
EntryPointRequest* entryPoint)
{
String output;
auto outputFunc = [](void const* data, size_t size, void* userData)
{
(*(String*)userData).append((char const*)data, (char const*)data + size);
};
glslang_CompileRequest request;
request.outputFunc = outputFunc;
request.outputUserData = &output;
request.disassembleResult = true;
int err = invokeGLSLCompilerForEntryPoint(entryPoint, request);
if (err)
{
String();
}
return output;
}
#endif
#if 0
String emitSPIRVAssembly(
ExtraContext& context)
{
if(context.getTranslationUnitOptions().entryPoints.Count() == 0)
{
// TODO(tfoley): need to write diagnostics into this whole thing...
fprintf(stderr, "no entry point specified\n");
return "";
}
StringBuilder sb;
for (auto entryPoint : context.getTranslationUnitOptions().entryPoints)
{
sb << emitSPIRVAssemblyForEntryPoint(context, entryPoint);
}
return sb.ProduceString();
}
#endif
// Do emit logic for a single entry point
CompileResult emitEntryPoint(
EntryPointRequest* entryPoint)
{
CompileResult result;
auto compileRequest = entryPoint->compileRequest;
switch (compileRequest->Target)
{
case CodeGenTarget::HLSL:
{
String code = emitHLSLForEntryPoint(entryPoint);
result = CompileResult(code);
}
break;
case CodeGenTarget::GLSL:
{
String code = emitGLSLForEntryPoint(entryPoint);
result = CompileResult(code);
}
break;
case CodeGenTarget::DXBytecode:
{
List<uint8_t> code = EmitDXBytecodeForEntryPoint(entryPoint);
result = CompileResult(code);
}
break;
case CodeGenTarget::DXBytecodeAssembly:
{
String code = EmitDXBytecodeAssemblyForEntryPoint(entryPoint);
result = CompileResult(code);
}
break;
case CodeGenTarget::SPIRV:
{
List<uint8_t> code = emitSPIRVForEntryPoint(entryPoint);
result = CompileResult(code);
}
break;
case CodeGenTarget::SPIRVAssembly:
{
String code = emitSPIRVAssemblyForEntryPoint(entryPoint);
result = CompileResult(code);
}
break;
case CodeGenTarget::None:
// The user requested no output
break;
// Note(tfoley): We currently hit this case when compiling the stdlib
case CodeGenTarget::Unknown:
break;
default:
throw "unimplemented";
}
return result;
}
CompileResult emitTranslationUnitEntryPoints(
TranslationUnitRequest* translationUnit)
{
CompileResult result;
for (auto& entryPoint : translationUnit->entryPoints)
{
CompileResult entryPointResult = emitEntryPoint(entryPoint.Ptr());
entryPoint->result = entryPointResult;
}
// The result for the translation unit will just be the concatenation
// of the results for each entry point. This doesn't actually make
// much sense, but it is good enough for now.
//
// TODO: Replace this with a packaged JSON and/or binary format.
for (auto& entryPoint : translationUnit->entryPoints)
{
result.append(entryPoint->result);
}
return result;
}
// Do emit logic for an entire translation unit, which might
// have zero or more entry points
CompileResult emitTranslationUnit(
TranslationUnitRequest* translationUnit)
{
return emitTranslationUnitEntryPoints(translationUnit);
}
#if 0
TranslationUnitResult generateOutput(ExtraContext& context)
{
TranslationUnitResult result = emitTranslationUnit(context);
return result;
}
#endif
void generateOutput(
CompileRequest* compileRequest)
{
// Allow for an "extra" target to verride things first.
switch (compileRequest->extraTarget)
{
case CodeGenTarget::ReflectionJSON:
{
String reflectionJSON = emitReflectionJSON(compileRequest->layout.Ptr());
// HACK(tfoley): just print it out since that is what people probably expect.
// TODO: need a way to control where output gets routed across all possible targets.
fprintf(stdout, "%s", reflectionJSON.begin());
return;
}
break;
default:
break;
}
// For most targets, we will do things per-translation-unit
for( auto translationUnit : compileRequest->translationUnits )
{
CompileResult translationUnitResult = emitTranslationUnit(translationUnit.Ptr());
translationUnit->result = translationUnitResult;
}
}
}
|