forked from AcademySoftwareFoundation/OpenShadingLanguage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoslcomp.cpp
More file actions
1517 lines (1283 loc) · 52.5 KB
/
oslcomp.cpp
File metadata and controls
1517 lines (1283 loc) · 52.5 KB
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <string>
#include <fstream>
#include <cstdio>
#include <streambuf>
#include <cstdio>
#include <cerrno>
#include "oslcomp_pvt.h"
#include <OpenImageIO/platform.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/dassert.h>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/thread.h>
#ifndef USE_BOOST_WAVE
# define USE_BOOST_WAVE 0
#endif
#if USE_BOOST_WAVE
# include <boost/wave.hpp>
# include <boost/wave/cpplexer/cpp_lex_token.hpp>
# include <boost/wave/cpplexer/cpp_lex_iterator.hpp>
#else
# if !defined(__STDC_CONSTANT_MACROS)
# define __STDC_CONSTANT_MACROS 1
# endif
# include <clang/Frontend/CompilerInstance.h>
# include <clang/Frontend/TextDiagnosticPrinter.h>
# include <clang/Frontend/Utils.h>
# include <clang/Basic/TargetInfo.h>
# include <clang/Lex/PreprocessorOptions.h>
# include <llvm/Support/ToolOutputFile.h>
# include <llvm/Support/Host.h>
# include <llvm/Support/MemoryBuffer.h>
# include <llvm/Support/raw_ostream.h>
#endif
OSL_NAMESPACE_ENTER
OSLCompiler::OSLCompiler (ErrorHandler *errhandler)
{
m_impl = new pvt::OSLCompilerImpl (errhandler);
}
OSLCompiler::~OSLCompiler ()
{
delete m_impl;
}
bool
OSLCompiler::compile (string_view filename,
const std::vector<std::string> &options,
string_view stdoslpath)
{
return m_impl->compile (filename, options, stdoslpath);
}
bool
OSLCompiler::compile_buffer (string_view sourcecode,
std::string &osobuffer,
const std::vector<std::string> &options,
string_view stdoslpath)
{
return m_impl->compile_buffer (sourcecode, osobuffer, options, stdoslpath);
}
string_view
OSLCompiler::output_filename () const
{
return m_impl->output_filename();
}
namespace pvt { // OSL::pvt
OSLCompilerImpl *oslcompiler = NULL;
static ustring op_for("for");
static ustring op_while("while");
static ustring op_dowhile("dowhile");
OSLCompilerImpl::OSLCompilerImpl (ErrorHandler *errhandler)
: m_errhandler(errhandler ? errhandler : &ErrorHandler::default_handler()),
m_err(false), m_symtab(*this),
m_current_typespec(TypeDesc::UNKNOWN), m_current_output(false),
m_verbose(false), m_quiet(false), m_debug(false),
m_preprocess_only(false), m_optimizelevel(1),
m_next_temp(0), m_next_const(0),
m_osofile(NULL),
m_total_nesting(0), m_loop_nesting(0), m_derivsym(NULL),
m_main_method_start(-1),
m_declaring_shader_formals(false)
{
initialize_globals ();
initialize_builtin_funcs ();
}
OSLCompilerImpl::~OSLCompilerImpl ()
{
delete m_derivsym;
}
bool
OSLCompilerImpl::preprocess_file (const std::string &filename,
const std::string &stdoslpath,
const std::vector<std::string> &defines,
const std::vector<std::string> &includepaths,
std::string &result)
{
// Read file contents into a string
std::ifstream instream;
OIIO::Filesystem::open(instream, filename);
if (! instream.is_open()) {
error (ustring(filename), 0, "Could not open \"%s\"\n", filename.c_str());
return false;
}
instream.unsetf (std::ios::skipws);
std::string instring (std::istreambuf_iterator<char>(instream.rdbuf()),
std::istreambuf_iterator<char>());
instream.close ();
return preprocess_buffer (instring, filename, stdoslpath, defines,
includepaths, result);
}
#if USE_BOOST_WAVE
bool
OSLCompilerImpl::preprocess_buffer (const std::string &buffer,
const std::string &filename,
const std::string &stdoslpath,
const std::vector<std::string> &defines,
const std::vector<std::string> &includepaths,
std::string &result)
{
std::ostringstream ss;
boost::wave::util::file_position_type current_position;
std::string instring;
if (!stdoslpath.empty())
instring = OIIO::Strutil::format("#include \"%s\"\n", stdoslpath.c_str());
else
instring = "\n";
instring += buffer;
try {
typedef boost::wave::cpplexer::lex_token<> token_type;
typedef boost::wave::cpplexer::lex_iterator<token_type> lex_iterator_type;
typedef boost::wave::context<std::string::iterator, lex_iterator_type> context_type;
// Setup wave context
context_type ctx (instring.begin(), instring.end(), filename.c_str());
// Turn on support of variadic macros, e.g. #define FOO(...) __VA_ARGS__
// Turn off whitespace insertion.
boost::wave::language_support lang = boost::wave::language_support (
(ctx.get_language() | boost::wave::support_option_variadics)
& ~boost::wave::language_support::support_option_insert_whitespace);
ctx.set_language (lang);
ctx.add_macro_definition (OIIO::Strutil::format("OSL_VERSION_MAJOR=%d",
OSL_LIBRARY_VERSION_MAJOR).c_str());
ctx.add_macro_definition (OIIO::Strutil::format("OSL_VERSION_MINOR=%d",
OSL_LIBRARY_VERSION_MINOR).c_str());
ctx.add_macro_definition (OIIO::Strutil::format("OSL_VERSION_PATCH=%d",
OSL_LIBRARY_VERSION_PATCH).c_str());
ctx.add_macro_definition (OIIO::Strutil::format("OSL_VERSION=%d",
OSL_LIBRARY_VERSION_CODE).c_str());
for (size_t i = 0; i < defines.size(); ++i) {
if (defines[i][1] == 'D')
ctx.add_macro_definition (defines[i].c_str()+2);
else if (defines[i][1] == 'U')
ctx.remove_macro_definition (defines[i].c_str()+2);
}
for (size_t i = 0; i < includepaths.size(); ++i) {
ctx.add_sysinclude_path (includepaths[i].c_str());
ctx.add_include_path (includepaths[i].c_str());
}
context_type::iterator_type first = ctx.begin();
context_type::iterator_type last = ctx.end();
#if 0
// N.B. The force_include() method is buggy, see
// https://svn.boost.org/trac/boost/ticket/6838
// It turns out that it screws up all file/line tracking therafter.
// So instead, we simply force a '#include "stdosl.h"' as the first
// line (see above) and then doctor the subsequent line numbers to
// subtract one in osllex.h. Oh, the tangled web we weave when
// we attempt to work around boost bugs.
// Add standard include
first.force_include (stdinclude.c_str(), true);
#endif
// Get result
while (first != last) {
current_position = (*first).get_position();
ss << (*first).get_value();
++first;
}
} catch (boost::wave::cpp_exception const& e) {
// Processing error, ignore pedantic last line not terminated warning
if (e.get_errorcode() == boost::wave::preprocess_exception::last_line_not_terminated) {
ss << "\n";
}
else {
error (ustring(e.file_name()), e.line_no(), "%s\n", e.description());
return false;
}
} catch (std::exception const& e) {
// STL exception
error (ustring(current_position.get_file().c_str()),
current_position.get_line(),
"preprocessor exception caught: %s\n", e.what());
return false;
} catch (...) {
// Other exception
error (ustring(current_position.get_file().c_str()),
current_position.get_line(),
"unexpected exception caught\n");
return false;
}
result = ss.str();
return true;
}
#else /* LLVM: vvvvvvvvvv */
bool
OSLCompilerImpl::preprocess_buffer (const std::string &buffer,
const std::string &filename,
const std::string &stdoslpath,
const std::vector<std::string> &defines,
const std::vector<std::string> &includepaths,
std::string &result)
{
std::string instring;
if (!stdoslpath.empty())
instring = OIIO::Strutil::format("#include \"%s\"\n", stdoslpath);
else
instring = "\n";
instring += buffer;
std::unique_ptr<llvm::MemoryBuffer> mbuf (llvm::MemoryBuffer::getMemBuffer(instring, filename));
clang::CompilerInstance inst;
// Set up error capture for the preprocessor
std::string preproc_errors;
llvm::raw_string_ostream errstream(preproc_errors);
clang::DiagnosticOptions *diagOptions = new clang::DiagnosticOptions();
clang::TextDiagnosticPrinter *diagPrinter =
new clang::TextDiagnosticPrinter(errstream, diagOptions);
llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagIDs(new clang::DiagnosticIDs);
clang::DiagnosticsEngine *diagEngine =
new clang::DiagnosticsEngine(diagIDs, diagOptions, diagPrinter);
inst.setDiagnostics(diagEngine);
const std::shared_ptr<clang::TargetOptions> &targetopts =
std::make_shared<clang::TargetOptions>(inst.getTargetOpts());
targetopts->Triple = llvm::sys::getDefaultTargetTriple();
clang::TargetInfo *target =
clang::TargetInfo::CreateTargetInfo(inst.getDiagnostics(), targetopts);
inst.setTarget(target);
inst.createFileManager();
inst.createSourceManager(inst.getFileManager());
clang::SourceManager &sm = inst.getSourceManager();
sm.setMainFileID (sm.createFileID(std::move(mbuf), clang::SrcMgr::C_User));
inst.getPreprocessorOutputOpts().ShowCPP = 1;
inst.getPreprocessorOutputOpts().ShowMacros = 0;
clang::HeaderSearchOptions &headerOpts = inst.getHeaderSearchOpts();
headerOpts.UseBuiltinIncludes = 0;
headerOpts.UseStandardSystemIncludes = 0;
headerOpts.UseStandardCXXIncludes = 0;
std::string directory = OIIO::Filesystem::parent_path(filename);
if (directory.empty())
directory = OIIO::Filesystem::current_path();
headerOpts.AddPath (directory, clang::frontend::Angled, false, true);
for (auto&& inc : includepaths) {
headerOpts.AddPath (inc, clang::frontend::Angled,
false /* not a framework */,
true /* ignore sys root */);
}
clang::PreprocessorOptions &preprocOpts = inst.getPreprocessorOpts();
preprocOpts.UsePredefines = 0;
preprocOpts.addMacroDef (OIIO::Strutil::format("OSL_VERSION_MAJOR=%d",
OSL_LIBRARY_VERSION_MAJOR).c_str());
preprocOpts.addMacroDef (OIIO::Strutil::format("OSL_VERSION_MINOR=%d",
OSL_LIBRARY_VERSION_MINOR).c_str());
preprocOpts.addMacroDef (OIIO::Strutil::format("OSL_VERSION_PATCH=%d",
OSL_LIBRARY_VERSION_PATCH).c_str());
preprocOpts.addMacroDef (OIIO::Strutil::format("OSL_VERSION=%d",
OSL_LIBRARY_VERSION_CODE).c_str());
for (auto&& d : defines) {
if (d[1] == 'D')
preprocOpts.addMacroDef (d.c_str()+2);
else if (d[1] == 'U')
preprocOpts.addMacroUndef (d.c_str()+2);
}
inst.getLangOpts().LineComment = 1;
inst.createPreprocessor(clang::TU_Prefix);
llvm::raw_string_ostream ostream(result);
diagPrinter->BeginSourceFile (inst.getLangOpts(), &inst.getPreprocessor());
clang::DoPrintPreprocessedInput (inst.getPreprocessor(),
&ostream, inst.getPreprocessorOutputOpts());
diagPrinter->EndSourceFile ();
if (preproc_errors.size()) {
while (preproc_errors.size() &&
preproc_errors[preproc_errors.size()-1] == '\n')
preproc_errors.erase (preproc_errors.size()-1);
error (ustring(), -1, "%s", preproc_errors.c_str());
return false;
}
return true;
}
#endif
void
OSLCompilerImpl::read_compile_options (const std::vector<std::string> &options,
std::vector<std::string> &defines,
std::vector<std::string> &includepaths)
{
m_output_filename.clear ();
m_preprocess_only = false;
for (size_t i = 0; i < options.size(); ++i) {
if (options[i] == "-v") {
// verbose mode
m_verbose = true;
} else if (options[i] == "-q") {
// quiet mode
m_quiet = true;
} else if (options[i] == "-d") {
// debug mode
m_debug = true;
} else if (options[i] == "-E") {
m_preprocess_only = true;
} else if (options[i] == "-o" && i < options.size()-1) {
++i;
m_output_filename = options[i];
} else if (options[i] == "-O0") {
m_optimizelevel = 0;
} else if (options[i] == "-O" || options[i] == "-O1") {
m_optimizelevel = 1;
} else if (options[i] == "-O2") {
m_optimizelevel = 2;
} else if (options[i].c_str()[0] == '-' && options[i].size() > 2) {
// options meant for the preprocessor
if (options[i].c_str()[1] == 'D' || options[i].c_str()[1] == 'U')
defines.push_back(options[i]);
else if (options[i].c_str()[1] == 'I')
includepaths.push_back(options[i].substr(2));
}
}
}
// Guess the path for stdosl.h. This is only called if no explicit
// stdoslpath is given to the compile command.
static string_view
find_stdoslpath (const std::vector<std::string>& includepaths)
{
// first look in $OSLHOME/shaders
std::string OSLHOME = OIIO::Sysutil::getenv ("OSLHOME");
if (! OSLHOME.empty()) {
std::string path = OSLHOME + "/shaders";
if (OIIO::Filesystem::is_directory (path)) {
path = path + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
}
// If no OSLHOME, try looking wherever this program (the one running)
// lives, in a shaders or lib/osl/include directory.
std::string program = OIIO::Sysutil::this_program_path ();
if (program.size()) {
std::string path (program); // our program
path = OIIO::Filesystem::parent_path(path); // the bin dir of our program
path = OIIO::Filesystem::parent_path(path); // now the parent dir
std::string savepath = path;
// We search two spots: ../../lib/osl/include, and ../shaders
path = savepath + "/lib/osl/include";
if (OIIO::Filesystem::is_directory (path)) {
path = path + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
path = savepath + "/shaders";
if (OIIO::Filesystem::is_directory (path)) {
path = path + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
path = OIIO::Filesystem::parent_path(savepath); // Try one level higher
path = path + "/shaders";
if (OIIO::Filesystem::is_directory (path)) {
path = path + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
}
// Try looking for "oslc" binary in the $PATH, and if so, look in
// ../../shaders/stdosl.h
std::vector<std::string> exec_path_dirs;
OIIO::Filesystem::searchpath_split (OIIO::Sysutil::getenv("PATH"),
exec_path_dirs, true);
if (exec_path_dirs.size()) {
#ifdef WIN32
std::string oslcbin = "oslc.exe";
#else
std::string oslcbin = "oslc";
#endif
oslcbin = OIIO::Filesystem::searchpath_find (oslcbin, exec_path_dirs);
if (oslcbin.size()) {
std::string path = OIIO::Filesystem::parent_path(oslcbin); // the bin dir of our program
path = OIIO::Filesystem::parent_path(path); // now the parent dir
path += "/shaders";
if (OIIO::Filesystem::is_directory (path)) {
path = path + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
}
}
// Try the include paths
for (const auto& incpath : includepaths) {
std::string path = incpath + "/stdosl.h";
if (OIIO::Filesystem::exists (path))
return ustring(path);
}
// Give up
return string_view();
}
bool
OSLCompilerImpl::compile (string_view filename,
const std::vector<std::string> &options,
string_view stdoslpath)
{
if (! OIIO::Filesystem::exists (filename)) {
error (ustring(), 0, "Input file \"%s\" not found", filename.c_str());
return false;
}
std::vector<std::string> defines;
std::vector<std::string> includepaths;
m_cwd = OIIO::Filesystem::current_path();
m_main_filename = filename;
read_compile_options (options, defines, includepaths);
// Determine where the installed shader include directory is, and
// look for ../shaders/stdosl.h and force it to include.
if (stdoslpath.empty()) {
stdoslpath = find_stdoslpath(includepaths);
}
if (stdoslpath.empty() || ! OIIO::Filesystem::exists(stdoslpath))
warning (ustring(filename), 0, "Unable to find \"stdosl.h\"");
else {
// Add the directory of stdosl.h to the include paths
includepaths.push_back (OIIO::Filesystem::parent_path (stdoslpath));
}
std::string preprocess_result;
if (! preprocess_file (filename, stdoslpath,
defines, includepaths, preprocess_result)) {
return false;
} else if (m_preprocess_only) {
std::cout << preprocess_result;
} else {
bool parseerr = osl_parse_buffer (preprocess_result);
if (! parseerr) {
if (shader())
shader()->typecheck ();
else
error (ustring(), 0, "No shader function defined");
}
// Print the parse tree if there were no errors
if (m_debug) {
symtab().print ();
if (shader())
shader()->print (std::cout);
}
if (! error_encountered()) {
shader()->codegen ();
track_variable_dependencies ();
track_variable_lifetimes ();
check_for_illegal_writes ();
// if (m_optimizelevel >= 1)
// coalesce_temporaries ();
}
if (! error_encountered()) {
if (m_output_filename.size() == 0)
m_output_filename = default_output_filename ();
std::ofstream oso_output;
OIIO::Filesystem::open (oso_output, m_output_filename);
if (! oso_output.good()) {
error (ustring(), 0, "Could not open \"%s\"",
m_output_filename.c_str());
return false;
}
ASSERT (m_osofile == NULL);
m_osofile = &oso_output;
write_oso_file (m_output_filename, OIIO::Strutil::join(options," "));
ASSERT (m_osofile == NULL);
}
oslcompiler = NULL;
}
return ! error_encountered();
}
bool
OSLCompilerImpl::compile_buffer (string_view sourcecode,
std::string &osobuffer,
const std::vector<std::string> &options,
string_view stdoslpath)
{
string_view filename ("<buffer>");
std::vector<std::string> defines;
std::vector<std::string> includepaths;
read_compile_options (options, defines, includepaths);
m_cwd = OIIO::Filesystem::current_path();
m_main_filename = filename;
// Determine where the installed shader include directory is, and
// look for ../shaders/stdosl.h and force it to include.
if (stdoslpath.empty()) {
stdoslpath = find_stdoslpath(includepaths);
}
if (stdoslpath.empty() || ! OIIO::Filesystem::exists(stdoslpath))
warning (ustring(filename), 0, "Unable to find \"stdosl.h\"");
std::string preprocess_result;
if (! preprocess_buffer (sourcecode, filename, stdoslpath,
defines, includepaths, preprocess_result)) {
return false;
} else if (m_preprocess_only) {
std::cout << preprocess_result;
} else {
bool parseerr = osl_parse_buffer (preprocess_result);
if (! parseerr) {
if (shader())
shader()->typecheck ();
else
error (ustring(), 0, "No shader function defined");
}
// Print the parse tree if there were no errors
if (m_debug) {
symtab().print ();
if (shader())
shader()->print (std::cout);
}
if (! error_encountered()) {
shader()->codegen ();
track_variable_dependencies ();
track_variable_lifetimes ();
check_for_illegal_writes ();
// if (m_optimizelevel >= 1)
// coalesce_temporaries ();
}
if (! error_encountered()) {
m_output_filename = "<buffer>";
std::ostringstream oso_output;
oso_output.imbue (std::locale::classic()); // force C locale
ASSERT (m_osofile == NULL);
m_osofile = &oso_output;
write_oso_file (m_output_filename, OIIO::Strutil::join(options," "));
osobuffer = oso_output.str();
ASSERT (m_osofile == NULL);
}
oslcompiler = NULL;
}
return ! error_encountered();
}
struct GlobalTable {
const char *name;
TypeSpec type;
};
void
OSLCompilerImpl::initialize_globals ()
{
static GlobalTable globals[] = {
{ "P", TypeDesc::TypePoint },
{ "I", TypeDesc::TypeVector },
{ "N", TypeDesc::TypeNormal },
{ "Ng", TypeDesc::TypeNormal },
{ "u", TypeDesc::TypeFloat },
{ "v", TypeDesc::TypeFloat },
{ "dPdu", TypeDesc::TypeVector },
{ "dPdv", TypeDesc::TypeVector },
#if 0
// Light variables -- we don't seem to be on a route to support this
// kind of light shader, so comment these out for now.
{ "L", TypeDesc::TypeVector },
{ "Cl", TypeDesc::TypeColor },
{ "Ns", TypeDesc::TypeNormal },
{ "Pl", TypeDesc::TypePoint },
{ "Nl", TypeDesc::TypeNormal },
#endif
{ "Ps", TypeDesc::TypePoint },
{ "Ci", TypeSpec (TypeDesc::TypeColor, true) },
{ "time", TypeDesc::TypeFloat },
{ "dtime", TypeDesc::TypeFloat },
{ "dPdtime", TypeDesc::TypeVector },
{ NULL }
};
for (int i = 0; globals[i].name; ++i) {
Symbol *s = new Symbol (ustring(globals[i].name), globals[i].type,
SymTypeGlobal);
symtab().insert (s);
}
}
std::string
OSLCompilerImpl::default_output_filename ()
{
if (m_shader && shader_decl())
return shader_decl()->shadername().string() + ".oso";
return std::string();
}
void
OSLCompilerImpl::write_oso_metadata (const ASTNode *metanode) const
{
ASSERT (metanode->nodetype() == ASTNode::variable_declaration_node);
const ASTvariable_declaration *metavar = static_cast<const ASTvariable_declaration *>(metanode);
Symbol *metasym = metavar->sym();
ASSERT (metasym);
TypeSpec ts = metasym->typespec();
std::string pdl;
bool ok = metavar->param_default_literals (metasym, metavar->init().get(), pdl, ",");
if (ok) {
oso ("%%meta{%s,%s,%s} ", ts.string().c_str(), metasym->name(), pdl);
} else {
error (metanode->sourcefile(), metanode->sourceline(),
"Don't know how to print metadata %s (%s) with node type %s",
metasym->name().c_str(), ts.string().c_str(),
metavar->init()->nodetypename());
}
}
void
OSLCompilerImpl::write_oso_const_value (const ConstantSymbol *sym) const
{
ASSERT (sym);
TypeDesc type = sym->typespec().simpletype();
TypeDesc elemtype = type.elementtype();
int nelements = std::max (1, type.arraylen);
if (elemtype == TypeDesc::STRING)
for (int i = 0; i < nelements; ++i)
oso ("\"%s\"%s", sym->strval(i), nelements>1 ? " " : "");
else if (elemtype == TypeDesc::INT)
for (int i = 0; i < nelements; ++i)
oso ("%d%s", sym->intval(i), nelements>1 ? " " : "");
else if (elemtype == TypeDesc::FLOAT)
for (int i = 0; i < nelements; ++i)
oso ("%.8g%s", sym->floatval(i), nelements>1 ? " " : "");
else if (equivalent (elemtype, TypeDesc::TypeVector))
for (int i = 0; i < nelements; ++i)
oso ("%.8g %.8g %.8g%s", sym->vecval(i)[0], sym->vecval(i)[1],
sym->vecval(i)[2], nelements>1 ? " " : "");
else {
ASSERT (0 && "Don't know how to output this constant type");
}
}
void
OSLCompilerImpl::write_oso_symbol (const Symbol *sym)
{
// symtype / datatype / name
oso ("%s\t%s\t%s", sym->symtype_shortname(),
type_c_str(sym->typespec()), sym->mangled().c_str());
ASTvariable_declaration *v = NULL;
if (sym->node() && sym->node()->nodetype() == ASTNode::variable_declaration_node)
v = static_cast<ASTvariable_declaration *>(sym->node());
// Print default values
bool isparam = (sym->symtype() == SymTypeParam ||
sym->symtype() == SymTypeOutputParam);
if (sym->symtype() == SymTypeConst) {
oso ("\t");
write_oso_const_value (static_cast<const ConstantSymbol *>(sym));
oso ("\t");
} else if (v && isparam) {
std::string out;
v->param_default_literals (sym, v->init().get(), out);
oso ("\t%s\t", out.c_str());
}
//
// Now output all the hints, which is most of the work!
//
int hints = 0;
// %meta{} encodes metadata (handled by write_oso_metadata)
if (v) {
ASSERT (v);
for (ASTNode::ref m = v->meta(); m; m = m->next()) {
if (hints++ == 0)
oso ("\t");
write_oso_metadata (m.get());
}
}
// %read and %write give the range of ops over which a symbol is used.
oso ("%c%%read{%d,%d} %%write{%d,%d}", hints++ ? ' ' : '\t',
sym->firstread(), sym->lastread(),
sym->firstwrite(), sym->lastwrite());
// %struct, %structfields, and %structfieldtypes document the
// definition of a structure and which other symbols comprise the
// individual fields.
if (sym->typespec().is_structure()) {
const StructSpec *structspec (sym->typespec().structspec());
std::string fieldlist, signature;
for (int i = 0; i < (int)structspec->numfields(); ++i) {
if (i > 0)
fieldlist += ",";
fieldlist += structspec->field(i).name.string();
signature += code_from_type (structspec->field(i).type);
}
oso ("%c%%struct{\"%s\"} %%structfields{%s} %%structfieldtypes{\"%s\"} %%structnfields{%d}",
hints++ ? ' ' : '\t',
structspec->mangled().c_str(), fieldlist.c_str(),
signature.c_str(), structspec->numfields());
}
// %mystruct and %mystructfield document the symbols holding structure
// fields, linking them back to the structures they are part of.
if (sym->fieldid() >= 0) {
ASTvariable_declaration *vd = (ASTvariable_declaration *) sym->node();
if (vd)
oso ("%c%%mystruct{%s} %%mystructfield{%d}", hints++ ? ' ' : '\t',
vd->sym()->mangled().c_str(), sym->fieldid());
}
// %derivs hint marks symbols that need to carry derivatives
if (sym->has_derivs())
oso ("%c%%derivs", hints++ ? ' ' : '\t');
// %initexpr hint marks parameters whose default is the result of code
// that must be executed (an expression, like =noise(P) or =u), rather
// than a true default value that is statically known (like =3.14).
if (isparam && sym->has_init_ops())
oso ("%c%%initexpr", hints++ ? ' ' : '\t');
#if 0 // this is recomputed by the runtime optimizer, no need to bloat the .oso with these
// %depends marks, for potential OUTPUTs, which symbols they depend
// upon. This is so that derivativeness, etc., may be
// back-propagated as shader networks are linked together.
if (isparam || sym->symtype() == SymTypeGlobal) {
// FIXME
const SymPtrSet &deps (m_symdeps[sym]);
std::vector<const Symbol *> inputdeps;
for (auto&& d : deps)
if (d->symtype() == SymTypeParam ||
d->symtype() == SymTypeOutputParam ||
d->symtype() == SymTypeGlobal ||
d->symtype() == SymTypeLocal ||
d->symtype() == SymTypeTemp)
inputdeps.push_back (d);
if (inputdeps.size()) {
if (hints++ == 0)
oso ("\t");
oso (" %%depends{");
int deps = 0;
for (size_t i = 0; i < inputdeps.size(); ++i) {
if (inputdeps[i]->symtype() == SymTypeTemp &&
inputdeps[i]->dealias() != inputdeps[i])
continue; // Skip aliased temporaries
if (deps++)
oso (",");
oso ("%s", inputdeps[i]->mangled().c_str());
}
oso ("}");
}
}
#endif
oso ("\n");
}
void
OSLCompilerImpl::write_oso_file (const std::string &outfilename,
string_view options)
{
ASSERT (m_osofile != NULL && m_osofile->good());
oso ("OpenShadingLanguage %d.%02d\n",
OSO_FILE_VERSION_MAJOR, OSO_FILE_VERSION_MINOR);
oso ("# Compiled by oslc %s\n", OSL_LIBRARY_VERSION_STRING);
oso ("# options: %s\n", options);
ASTshader_declaration *shaderdecl = shader_decl();
oso ("%s %s", shaderdecl->shadertypename(),
shaderdecl->shadername().c_str());
// output global hints and metadata
int hints = 0;
for (ASTNode::ref m = shaderdecl->metadata(); m; m = m->next()) {
if (hints++ == 0)
oso ("\t");
write_oso_metadata (m.get());
}
oso ("\n");
// Output params, so they are first
for (auto&& s : symtab()) {
if (s->symtype() == SymTypeParam || s->symtype() == SymTypeOutputParam)
write_oso_symbol (s);
}
// Output globals, locals, temps, const
for (auto&& s : symtab()) {
if (s->symtype() == SymTypeLocal || s->symtype() == SymTypeTemp ||
s->symtype() == SymTypeGlobal || s->symtype() == SymTypeConst) {
// Don't bother writing symbols that are never used
if (s->lastuse() >= 0) {
write_oso_symbol (s);
}
}
}
// Output all opcodes
int lastline = -1;
ustring lastfile;
ustring lastmethod ("___uninitialized___");
for (auto& op : m_ircode) {
if (lastmethod != op.method()) {
oso ("code %s\n", op.method());
lastmethod = op.method();
lastfile = ustring();
lastline = -1;
}
if (/*m_debug &&*/ op.sourcefile()) {
ustring file = op.sourcefile();
int line = op.sourceline();
if (file != lastfile || line != lastline)
oso ("# %s:%d\n# %s\n", file, line,
retrieve_source (file, line));
}
// Op name
oso ("\t%s", op.opname());
// Register arguments
if (op.nargs())
oso (op.opname().length() < 8 ? "\t\t" : "\t");
for (int i = 0; i < op.nargs(); ++i) {
int arg = op.firstarg() + i;
oso ("%s ", m_opargs[arg]->dealias()->mangled());
}
// Jump targets
for (size_t i = 0; i < Opcode::max_jumps; ++i)
if (op.jump(i) >= 0)
oso ("%d ", op.jump(i));
//
// Opcode Hints
//
bool firsthint = true;
// %filename and %line document the source code file and line that
// contained code that generated this op. To avoid clutter, we
// only output these hints when they DIFFER from the previous op.
if (op.sourcefile()) {
if (op.sourcefile() != lastfile) {
lastfile = op.sourcefile();
oso ("%c%%filename{\"%s\"}", firsthint ? '\t' : ' ', lastfile);
firsthint = false;
}
if (op.sourceline() != lastline) {
lastline = op.sourceline();
oso ("%c%%line{%d}", firsthint ? '\t' : ' ', lastline);
firsthint = false;
}
}
// %argrw documents which arguments are read, written, or both (rwW).
if (op.nargs()) {
oso ("%c%%argrw{\"", firsthint ? '\t' : ' ');
for (int i = 0; i < op.nargs(); ++i) {
if (op.argwrite(i))
oso (op.argread(i) ? "W" : "w");
else
oso (op.argread(i) ? "r" : "-");
}
oso ("\"}");
firsthint = false;
}