forked from AcademySoftwareFoundation/OpenShadingLanguage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntimeoptimize.cpp
More file actions
3592 lines (3184 loc) · 135 KB
/
runtimeoptimize.cpp
File metadata and controls
3592 lines (3184 loc) · 135 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 Contributors to the Open Shading Language project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/AcademySoftwareFoundation/OpenShadingLanguage
#include <cmath>
#include <cstdio>
#include <vector>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/thread.h>
#include <OpenImageIO/timer.h>
#include "batched_analysis.h"
#include "oslexec_pvt.h"
#include "runtimeoptimize.h"
using namespace OSL;
using namespace OSL::pvt;
// names of ops we'll be using frequently
static ustring u_nop("nop");
static ustring u_exit("exit");
static ustring u_assign("assign");
static ustring u_add("add");
static ustring u_sub("sub");
static ustring u_mul("mul");
static ustring u_if("if");
static ustring u_for("for");
static ustring u_while("while");
static ustring u_dowhile("dowhile");
static ustring u_functioncall("functioncall");
static ustring u_functioncall_nr("functioncall_nr");
static ustring u_break("break");
static ustring u_continue("continue");
static ustring u_return("return");
static ustring u_useparam("useparam");
static ustring u_closure("closure");
static ustring u_pointcloud_write("pointcloud_write");
static ustring u_isconnected("isconnected");
static ustring u_setmessage("setmessage");
static ustring u_getmessage("getmessage");
static ustring u_getattribute("getattribute");
static ustring u_backfacing("backfacing");
static ustring u_calculatenormal("calculatenormal");
static ustring u_flipHandedness("flipHandedness");
static ustring u_N("N");
static ustring u_I("I");
static ustring main_method_name("___main___");
OSL_NAMESPACE_BEGIN
namespace pvt { // OSL::pvt
using OIIO::spin_lock;
using OIIO::Timer;
DECLFOLDER(constfold_assign); // forward decl
/// Wrapper that erases elements of c for which predicate p is true.
/// (Unlike std::remove_if, it resizes the container so that it contains
/// ONLY elements for which the predicate is true.)
template<class Container, class Predicate>
void
erase_if(Container& c, const Predicate& p)
{
c.erase(std::remove_if(c.begin(), c.end(), p), c.end());
}
OSOProcessorBase::OSOProcessorBase(ShadingSystemImpl& shadingsys,
ShaderGroup& group, ShadingContext* ctx)
: m_shadingsys(shadingsys)
, m_group(group)
, m_context(ctx)
, m_debug(shadingsys.debug())
, m_inst(NULL)
{
set_debug();
}
OSOProcessorBase::~OSOProcessorBase() {}
RuntimeOptimizer::RuntimeOptimizer(ShadingSystemImpl& shadingsys,
ShaderGroup& group, ShadingContext* ctx)
: OSOProcessorBase(shadingsys, group, ctx)
, m_optimize(shadingsys.optimize())
, m_opt_simplify_param(shadingsys.m_opt_simplify_param)
, m_opt_constant_fold(shadingsys.m_opt_constant_fold)
, m_opt_stale_assign(shadingsys.m_opt_stale_assign)
, m_opt_elide_useless_ops(shadingsys.m_opt_elide_useless_ops)
, m_opt_elide_unconnected_outputs(
shadingsys.m_opt_elide_unconnected_outputs)
, m_opt_peephole(shadingsys.m_opt_peephole)
, m_opt_coalesce_temps(shadingsys.m_opt_coalesce_temps)
, m_opt_assign(shadingsys.m_opt_assign)
, m_opt_mix(shadingsys.m_opt_mix)
, m_opt_middleman(shadingsys.m_opt_middleman)
, m_opt_batched_analysis(shadingsys.m_opt_batched_analysis)
, m_keep_no_return_function_calls(shadingsys.m_llvm_debugging_symbols)
, m_pass(0)
, m_next_newconst(0)
, m_next_newtemp(0)
, m_stat_opt_locking_time(0)
, m_stat_specialization_time(0)
, m_stop_optimizing(false)
, m_raytypes_on(group.raytypes_on())
, m_raytypes_off(group.raytypes_off())
{
memset((char*)&m_shaderglobals, 0, sizeof(ShaderGlobals));
m_shaderglobals.context = shadingcontext();
// To handle error/warning/print that might be reported through
// the renderer services, we will need to provide the default one
// which will just report through the ShadingContext
m_shaderglobals.renderer = &m_rendererservices;
// Disable no_function_return_calls for OptiX renderers, because we
// aren't yet set up to support use of debugging symbols for PTX.
// FIXME: some day, we are going to want debugging symbols for PTX, and
// will need some refactoring of the debugging symbol code.
if (shadingsys.renderer()->supports("OptiX"))
m_keep_no_return_function_calls = false;
}
RuntimeOptimizer::~RuntimeOptimizer() {}
void
OSOProcessorBase::set_inst(int newlayer)
{
m_layer = newlayer;
m_inst = group()[m_layer];
OSL_DASSERT(m_inst != NULL);
set_debug();
}
void
RuntimeOptimizer::set_inst(int newlayer)
{
OSOProcessorBase::set_inst(newlayer);
m_all_consts.clear();
m_symbol_aliases.clear();
m_block_aliases.clear();
m_param_aliases.clear();
m_bblockids.clear();
}
void
OSOProcessorBase::set_debug()
{
// start with the shading system's idea of debugging level
m_debug = shadingsys().debug();
// If either group or layer was specified for debug, surely they want
// debugging turned on.
if (!shadingsys().debug_groupname().empty()
|| !shadingsys().debug_layername().empty())
m_debug = std::max(m_debug, 1);
// Force debugging off if a specific group was selected for debug
// and we're not it, or a specific layer was selected for debug and
// we're not it.
bool wronggroup = (!shadingsys().debug_groupname().empty()
&& shadingsys().debug_groupname() != group().name());
bool wronglayer = (!shadingsys().debug_layername().empty() && inst()
&& shadingsys().debug_layername()
!= inst()->layername());
if (wronggroup || wronglayer)
m_debug = 0;
}
void
RuntimeOptimizer::set_debug()
{
OSOProcessorBase::set_debug();
// If a specific group is isolated for debugging and the
// 'optimize_dondebug' flag is on, fully optimize all other groups.
if (!shadingsys().debug_groupname().empty()
&& shadingsys().debug_groupname() != group().name()) {
if (shadingsys().m_optimize_nondebug) {
// Debugging trick: if user said to only debug one group, turn
// on full optimization for all others! This prevents
// everything from running 10x slower just because you want to
// debug one shader.
m_optimize = 3;
m_opt_simplify_param = true;
m_opt_constant_fold = true;
m_opt_stale_assign = true;
m_opt_elide_useless_ops = true;
m_opt_elide_unconnected_outputs = true;
m_opt_peephole = true;
m_opt_coalesce_temps = true;
m_opt_assign = true;
m_opt_mix = true;
m_opt_middleman = true;
}
}
}
int
RuntimeOptimizer::find_constant(const TypeSpec& type, const void* data)
{
for (int c : m_all_consts) {
const Symbol& s(*inst()->symbol(c));
OSL_DASSERT(s.symtype() == SymTypeConst);
if (equivalent(s.typespec(), type)
&& !memcmp(s.data(), data, s.typespec().simpletype().size())) {
return c;
}
}
return -1;
}
int
RuntimeOptimizer::add_constant(const TypeSpec& type, const void* data,
TypeDesc datatype)
{
int ind = find_constant(type, data);
if (ind < 0) {
// support varlen arrays
TypeSpec newtype = type;
if (type.is_unsized_array())
newtype.make_array(datatype.numelements());
ustring symname;
if (newtype.is_int()) {
// If it's a constant integer, make the name $newconst_int42 and
// if it's negative, $newconst_int_42 (because we can't put a
// minus sign in a symbol name). This is easier to read than
// naming them sequentially (you know the value in the constant)
// and it means the name will be the same regardless of the order
// in which we made the constants (helpful for PTX cache
// behavior).
int val = *(const int*)data;
symname = ustring::fmtformat("$newconst_int{}{}",
val < 0 ? "_" : "", abs(val));
} else if (newtype.is_string()) {
// If it's a constant string, make the name $newconst_str_HASH
// where HASH is the hex value of the hash of that ustring. This
// ensures that the name will be the same regardless of the order
// in which we made the constants (helpful for PTX cache
// behavior).
ustring val(*(const char**)data);
symname = ustring::fmtformat("$newconst_str{:08x}", val.hash());
} else {
// All other cases, just name it sequentially as $newconst_1,
// $newconst_2, etc.
symname = ustring::fmtformat("$newconst{}", m_next_newconst++);
}
Symbol newconst(symname, newtype, SymTypeConst);
void* newdata = nullptr;
TypeDesc t(newtype.simpletype());
size_t n = t.aggregate * t.numelements();
if (datatype == TypeDesc::UNKNOWN)
datatype = t;
size_t datan = datatype.aggregate * datatype.numelements();
if (t.basetype == TypeDesc::INT && datatype.basetype == TypeDesc::INT
&& n == datan) {
newdata = inst()->shadingsys().alloc_int_constants(n);
memcpy(newdata, data, t.size());
} else if (t.basetype == TypeDesc::FLOAT
&& datatype.basetype == TypeDesc::FLOAT) {
newdata = inst()->shadingsys().alloc_float_constants(n);
if (n == datan)
for (size_t i = 0; i < n; ++i)
((float*)newdata)[i] = ((const float*)data)[i];
else if (datan == 1)
for (size_t i = 0; i < n; ++i)
((float*)newdata)[i] = ((const float*)data)[0];
else {
OSL_ASSERT(0 && "unsupported type for add_constant");
}
} else if (t.basetype == TypeDesc::FLOAT
&& datatype.basetype == TypeDesc::INT) {
newdata = inst()->shadingsys().alloc_float_constants(n);
if (n == datan)
for (size_t i = 0; i < n; ++i)
((float*)newdata)[i] = ((const int*)data)[i];
else if (datan == 1)
for (size_t i = 0; i < n; ++i)
((float*)newdata)[i] = ((const int*)data)[0];
else {
OSL_ASSERT(0 && "unsupported type for add_constant");
}
} else if (t.basetype == TypeDesc::STRING
&& datatype.basetype == TypeDesc::STRING && n == datan) {
newdata = inst()->shadingsys().alloc_string_constants(n);
memcpy(newdata, data, t.size());
} else {
OSL_ASSERT(0 && "unsupported type for add_constant");
}
newconst.set_dataptr(SymArena::Absolute, newdata);
ind = add_symbol(newconst);
m_all_consts.push_back(ind);
}
return ind;
}
int
RuntimeOptimizer::add_temp(const TypeSpec& type)
{
return add_symbol(Symbol(ustring::fmtformat("$opttemp{}", m_next_newtemp++),
type, SymTypeTemp));
}
int
RuntimeOptimizer::add_global(ustring name, const TypeSpec& type)
{
int index = inst()->findsymbol(name);
if (index < 0)
index = add_symbol(Symbol(name, type, SymTypeGlobal));
return index;
}
int
RuntimeOptimizer::add_symbol(const Symbol& sym)
{
size_t index = inst()->symbols().size();
OSL_ASSERT(inst()->symbols().capacity() > index
&& "we shouldn't have to realloc here");
inst()->symbols().push_back(sym);
// Mark the symbol as always read. Next time we recompute symbol
// lifetimes, it'll get the correct range for when it's read and
// written. But for now, just make sure it doesn't accidentally
// look entirely unused.
inst()->symbols().back().mark_always_used();
return (int)index;
}
void
RuntimeOptimizer::debug_opt_impl(string_view message) const
{
static OIIO::spin_mutex mutex;
OIIO::spin_lock lock(mutex);
std::cout << message;
}
void
RuntimeOptimizer::debug_opt_ops(int opbegin, int opend,
string_view message) const
{
const Opcode& op(inst()->ops()[opbegin]);
std::string oprange;
if (opbegin >= 0 && opend - opbegin > 1)
oprange = fmtformat("ops {}-{} ", opbegin, opend);
else if (opbegin >= 0)
oprange = fmtformat("op {} ", opbegin);
debug_optfmt(" {}{} (@ {}:{})\n", oprange, message, op.sourcefile(),
op.sourceline());
}
void
RuntimeOptimizer::debug_turn_into(const Opcode& op, int numops,
string_view newop, int newarg0, int newarg1,
int newarg2, string_view why)
{
int opnum = &op - &(inst()->ops()[0]);
std::string msg;
if (numops == 1)
msg = fmtformat("turned '{}' to '{}", op_string(op), newop);
else
msg = fmtformat("turned to '{}", newop);
if (newarg0 >= 0)
msg += fmtformat(" {}", inst()->symbol(newarg0)->name());
if (newarg1 >= 0)
msg += fmtformat(" {}", inst()->symbol(newarg1)->name());
if (newarg2 >= 0)
msg += fmtformat(" {}", inst()->symbol(newarg2)->name());
msg += "'";
if (why.size())
msg += fmtformat(" : {}", why);
debug_opt_ops(opnum, opnum + numops, msg);
}
void
RuntimeOptimizer::turn_into_new_op(Opcode& op, ustring newop, int newarg0,
int newarg1, int newarg2, string_view why)
{
int opnum = &op - &(inst()->ops()[0]);
OSL_DASSERT(opnum >= 0 && opnum < (int)inst()->ops().size());
if (debug() > 1)
debug_turn_into(op, 1, newop, newarg0, newarg1, newarg2, why);
op.reset(newop, newarg2 < 0 ? 2 : 3);
inst()->args()[op.firstarg() + 0] = newarg0;
op.argwriteonly(0);
opargsym(op, 0)->mark_rw(opnum, false, true);
inst()->args()[op.firstarg() + 1] = newarg1;
op.argreadonly(1);
opargsym(op, 1)->mark_rw(opnum, true, false);
if (newarg2 >= 0) {
inst()->args()[op.firstarg() + 2] = newarg2;
op.argreadonly(2);
opargsym(op, 2)->mark_rw(opnum, true, false);
}
}
void
RuntimeOptimizer::turn_into_assign(Opcode& op, int newarg, string_view why)
{
// We don't know the op num here, so we subtract the pointers
int opnum = &op - &(inst()->ops()[0]);
if (debug() > 1)
debug_turn_into(op, 1, "assign", oparg(op, 0), newarg, -1, why);
op.reset(u_assign, 2);
inst()->args()[op.firstarg() + 1] = newarg;
op.argwriteonly(0);
op.argread(1, true);
op.argwrite(1, false);
// Need to make sure the symbol we're assigning is marked as read
// for this op.
OSL_DASSERT(opnum >= 0 && opnum < (int)inst()->ops().size());
Symbol* arg = opargsym(op, 1);
arg->mark_rw(opnum, true, false);
}
// Turn the current op into a simple assignment to zero (of the first arg).
void
RuntimeOptimizer::turn_into_assign_zero(Opcode& op, string_view why)
{
static float zero[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
Symbol& R(*(inst()->argsymbol(op.firstarg() + 0)));
int cind = add_constant(R.typespec(), &zero);
turn_into_assign(op, cind, why);
}
// Turn the current op into a simple assignment to one (of the first arg).
void
RuntimeOptimizer::turn_into_assign_one(Opcode& op, string_view why)
{
Symbol& R(*(inst()->argsymbol(op.firstarg() + 0)));
if (R.typespec().is_int()) {
int one = 1;
int cind = add_constant(R.typespec(), &one);
turn_into_assign(op, cind, why);
} else {
OSL_DASSERT(R.typespec().is_triple() || R.typespec().is_float());
static float one[3] = { 1, 1, 1 };
int cind = add_constant(R.typespec(), &one);
turn_into_assign(op, cind, why);
}
}
// Turn the op into a no-op
int
RuntimeOptimizer::turn_into_nop(Opcode& op, string_view why)
{
if (op.opname() != u_nop) {
if (debug() > 1)
debug_turn_into(op, 1, "nop", -1, -1, -1, why);
op.reset(u_nop, 0);
return 1;
}
return 0;
}
int
RuntimeOptimizer::turn_into_nop(int begin, int end, string_view why)
{
int changed = 0;
for (int i = begin; i < end; ++i) {
Opcode& op(inst()->ops()[i]);
if (op.opname() != u_nop) {
op.reset(u_nop, 0);
++changed;
}
}
if (debug() > 1 && changed)
debug_turn_into(inst()->ops()[begin], end - begin, "nop", -1, -1, -1,
why);
return changed;
}
// Turn the op into a no-op functioncall
// We keep want to keep the jumps indices so we can correctly
// model an inlined function call for the debugger
int
RuntimeOptimizer::turn_into_functioncall_nr(Opcode& op, string_view why)
{
if (op.opname() == u_functioncall) {
if (debug() > 1)
debug_turn_into(op, 1, "functioncall_nr", -1, -1, -1, why);
op.transmute_opname(u_functioncall_nr);
return 1;
}
return 0;
}
void
RuntimeOptimizer::insert_code(int opnum, ustring opname,
const cspan<int> args_to_add,
RecomputeRWRangesOption recompute_rw_ranges,
InsertRelation relation)
{
OpcodeVec& code(inst()->ops());
std::vector<int>& opargs(inst()->args());
ustring method = (opnum < (int)code.size()) ? code[opnum].method()
: main_method_name;
int nargs = args_to_add.size();
Opcode op(opname, method, opargs.size(), nargs);
code.insert(code.begin() + opnum, op);
opargs.insert(opargs.end(), args_to_add.begin(), args_to_add.end());
if (opnum < inst()->m_maincodebegin)
++inst()->m_maincodebegin;
++inst()->m_maincodeend;
if ((relation == -1 && opnum > 0)
|| (relation == 1 && opnum < (int)code.size() - 1)) {
code[opnum].method(code[opnum + relation].method());
code[opnum].source(code[opnum + relation].sourcefile(),
code[opnum + relation].sourceline());
}
// Unless we were inserting at the end, we may need to adjust
// the jump addresses of other ops and the param init ranges.
if (opnum < (int)code.size() - 1) {
// Adjust jump offsets
for (auto& c : code) {
for (int j = 0; j < (int)Opcode::max_jumps && c.jump(j) >= 0; ++j) {
if (c.jump(j) > opnum) {
c.jump(j) = c.jump(j) + 1;
// std::cerr << "Adjusting jump target at op " << n << "\n";
}
}
}
// Adjust param init ranges
FOREACH_PARAM(auto&& s, inst())
{
if (s.initbegin() > opnum)
s.initbegin(s.initbegin() + 1);
if (s.initend() > opnum)
s.initend(s.initend() + 1);
}
}
// Inserting the instruction may change the read/write ranges of
// symbols. Not adjusting this can throw off other optimizations.
if (recompute_rw_ranges) {
for (auto&& s : inst()->symbols()) {
if (s.everread()) {
int first = s.firstread(), last = s.lastread();
if (first >= opnum)
++first;
if (last >= opnum)
++last;
s.set_read(first, last);
}
if (s.everwritten()) {
int first = s.firstwrite(), last = s.lastwrite();
if (first >= opnum)
++first;
if (last >= opnum)
++last;
s.set_write(first, last);
}
}
}
// Adjust the basic block IDs and which instructions are inside
// conditionals.
if (m_bblockids.size()) {
OSL_DASSERT(m_bblockids.size() == code.size() - 1);
m_bblockids.insert(m_bblockids.begin() + opnum, 1, m_bblockids[opnum]);
}
if (m_in_conditional.size()) {
OSL_DASSERT(m_in_conditional.size() == code.size() - 1);
m_in_conditional.insert(m_in_conditional.begin() + opnum, 1,
m_in_conditional[opnum]);
}
if (m_in_loop.size()) {
OSL_DASSERT(m_in_loop.size() == code.size() - 1);
m_in_loop.insert(m_in_loop.begin() + opnum, 1, m_in_loop[opnum]);
}
// If the first return happened after this, bump it up
if (m_first_return >= opnum)
++m_first_return;
if (opname == u_if) {
// special case for 'if' -- the arg is read, not written
inst()->symbol(args_to_add[0])->mark_rw(opnum, true, false);
} else if (opname != u_useparam) {
// Mark the args as being used for this op (assume that the
// first is written, the others are read).
for (int a = 0; a < nargs; ++a)
inst()->symbol(args_to_add[a])->mark_rw(opnum, a > 0, a == 0);
}
}
void
RuntimeOptimizer::insert_code(int opnum, ustring opname,
InsertRelation relation, int arg0, int arg1,
int arg2, int arg3)
{
int args[4];
int nargs = 0;
if (arg0 >= 0)
args[nargs++] = arg0;
if (arg1 >= 0)
args[nargs++] = arg1;
if (arg2 >= 0)
args[nargs++] = arg2;
if (arg3 >= 0)
args[nargs++] = arg3;
insert_code(opnum, opname, cspan<int>(args, args + nargs),
RecomputeRWRanges, relation);
}
/// Insert a 'useparam' instruction in front of instruction 'opnum', to
/// reference the symbols in 'params'.
void
RuntimeOptimizer::insert_useparam(size_t opnum,
const std::vector<int>& params_to_use)
{
OSL_DASSERT(params_to_use.size() > 0);
OpcodeVec& code(inst()->ops());
insert_code(opnum, u_useparam, params_to_use, RecomputeRWRanges,
GroupWithNext);
// All ops are "read"
code[opnum].argwrite(0, false);
code[opnum].argread(0, true);
if (opnum < code.size() - 1) {
// We have no parse node, but we set the new instruction's
// "source" to the one of the statement right after.
code[opnum].source(code[opnum + 1].sourcefile(),
code[opnum + 1].sourceline());
// Set the method id to the same as the statement right after
code[opnum].method(code[opnum + 1].method());
} else {
// If there IS no "next" instruction, just call it main
code[opnum].method(main_method_name);
}
}
void
RuntimeOptimizer::add_useparam(SymbolPtrVec& allsyms)
{
OpcodeVec& code(inst()->ops());
std::vector<int>& opargs(inst()->args());
// Mark all symbols as un-initialized
for (auto&& s : inst()->symbols())
s.initialized(false);
if (inst()->m_maincodebegin < 0)
inst()->m_maincodebegin = (int)code.size();
// Take care of the output params right off the bat -- as soon as the
// shader starts running 'main'.
std::vector<int> outputparams;
for (int i = 0; i < (int)inst()->symbols().size(); ++i) {
Symbol* s = inst()->symbol(i);
if (s->symtype() == SymTypeOutputParam
&& (s->connected() || s->connected_down() || s->renderer_output()
|| (s->valuesource() == Symbol::DefaultVal
&& s->has_init_ops()))) {
outputparams.push_back(i);
s->initialized(true);
}
}
if (outputparams.size())
insert_useparam(inst()->m_maincodebegin, outputparams);
// Figure out which statements are inside conditional states
find_conditionals();
// Loop over all ops...
for (int opnum = 0; opnum < (int)code.size(); ++opnum) {
Opcode& op(code[opnum]); // handy ref to the op
if (op.opname() == u_useparam)
continue; // skip useparam ops themselves, if we hit one
bool simple_assign = is_simple_assign(op);
bool in_main_code = (opnum >= inst()->m_maincodebegin);
std::vector<int> params; // list of params referenced by this op
// For each argument...
for (int a = 0; a < op.nargs(); ++a) {
int argind = op.firstarg() + a;
SymbolPtr s = inst()->argsymbol(argind);
OSL_DASSERT(s->dealias() == s);
// If this arg is a param and is read, remember it
if (s->symtype() != SymTypeParam
&& s->symtype() != SymTypeOutputParam)
continue; // skip non-params
// skip if we've already 'usedparam'ed it unconditionally
if (s->initialized() && in_main_code)
continue;
bool inside_init = (opnum >= s->initbegin()
&& opnum < s->initend());
if (op.argread(a) || (op.argwrite(a) && !inside_init)) {
// Don't add it more than once
if (std::find(params.begin(), params.end(), opargs[argind])
== params.end()) {
// If this arg is the one being written to by a
// "simple" assignment, it doesn't need a useparam here.
if (!(simple_assign && a == 0))
params.push_back(opargs[argind]);
// mark as already initialized unconditionally, if we do
if (op_is_unconditionally_executed(opnum)
&& op.method() == main_method_name)
s->initialized(true);
}
}
}
// If the arg we are examining read any params, insert a "useparam"
// op whose arguments are the list of params we are about to use.
if (params.size()) {
insert_useparam(opnum, params);
// Skip the op we just added
++opnum;
}
}
// Mark all symbols as un-initialized
for (auto&& s : inst()->symbols())
s.initialized(false);
// Re-track variable lifetimes, since the inserted useparam
// instructions will have change the instruction numbers.
find_basic_blocks();
track_variable_lifetimes(allsyms);
}
bool
OSOProcessorBase::is_zero(const Symbol& A)
{
if (!A.is_constant())
return false;
const TypeSpec& Atype(A.typespec());
static Vec3 Vzero(0, 0, 0);
return (Atype.is_float() && A.get_float() == 0)
|| (Atype.is_int() && A.get_int() == 0)
|| (Atype.is_triple() && A.get_vec3() == Vzero);
}
bool
OSOProcessorBase::is_one(const Symbol& A)
{
if (!A.is_constant())
return false;
const TypeSpec& Atype(A.typespec());
static Vec3 Vone(1, 1, 1);
static Matrix44 Mone(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
return (Atype.is_float() && A.get_float() == 1)
|| (Atype.is_int() && A.get_int() == 1)
|| (Atype.is_triple() && A.get_vec3() == Vone)
|| (Atype.is_matrix() && *(const Matrix44*)A.dataptr() == Mone);
}
bool
OSOProcessorBase::is_nonzero(const Symbol& A)
{
if (!A.is_constant())
return false;
const TypeSpec& Atype(A.typespec());
int ncomponents = Atype.numelements() * Atype.aggregate();
if (Atype.is_float_based()) {
const float* val = (const float*)A.data();
for (int i = 0; i < ncomponents; ++i)
if (val[i] == 0.0f)
return false;
return true;
}
if (Atype.is_int_based()) {
const int* val = (const int*)A.data();
for (int i = 0; i < ncomponents; ++i)
if (val[i] == 0)
return false;
return true;
}
return false;
}
std::string
OSOProcessorBase::const_value_as_string(const Symbol& A)
{
if (!A.is_constant())
return std::string();
TypeDesc type(A.typespec().simpletype());
int n = type.numelements() * type.aggregate;
std::ostringstream s;
s.imbue(std::locale::classic()); // force C locale
if (type.basetype == TypeDesc::FLOAT) {
for (int i = 0; i < n; ++i)
s << (i ? "," : "") << A.get_float(i);
} else if (type.basetype == TypeDesc::INT) {
for (int i = 0; i < n; ++i)
s << (i ? "," : "") << A.get_int(i);
} else if (type.basetype == TypeDesc::STRING) {
for (int i = 0; i < n; ++i)
s << (i ? "," : "") << '\"' << A.get_string(i) << '\"';
}
return s.str();
}
void
RuntimeOptimizer::register_message(ustring name)
{
m_local_messages_sent.push_back(name);
}
void
RuntimeOptimizer::register_unknown_message()
{
m_local_unknown_message_sent = true;
}
bool
RuntimeOptimizer::message_possibly_set(ustring name) const
{
return m_local_unknown_message_sent || m_unknown_message_sent
|| std::find(m_messages_sent.begin(), m_messages_sent.end(), name)
!= m_messages_sent.end()
|| std::find(m_local_messages_sent.begin(),
m_local_messages_sent.end(), name)
!= m_local_messages_sent.end();
}
/// For all the instance's parameters (that can't be overridden by the
/// geometry), if they can be found to be effectively constants or
/// globals, make constants for them and alias them to the constant. If
/// they are connected to an earlier layer's output, if it can determine
/// that the output will be a constant or global, then sever the
/// connection and just alias our parameter to that value.
void
RuntimeOptimizer::simplify_params()
{
for (int i = inst()->firstparam(); i < inst()->lastparam(); ++i) {
Symbol* s(inst()->symbol(i));
if (s->symtype() != SymTypeParam)
continue; // Skip non-params
// Don't simplify params that are interpolated or interactively
// editable
if (s->interpolated() || s->interactive())
continue;
if (s->typespec().is_structure() || s->typespec().is_closure_based())
continue; // We don't mess with struct placeholders or closures
if (s->valuesource() == Symbol::InstanceVal) {
// Instance value -- turn it into a constant and remove init ops
make_symbol_room(1);
s = inst()->symbol(i); // In case make_symbol_room changed ptrs
int cind = add_constant(s->typespec(), s->data());
global_alias(i, cind); // Alias this symbol to the new const
turn_into_nop(s->initbegin(), s->initend(),
"instance value doesn't need init ops");
} else if (s->valuesource() == Symbol::DefaultVal
&& !s->has_init_ops()) {
// Plain default value without init ops -- turn it into a constant
make_symbol_room(1);
s = inst()->symbol(i); // In case make_symbol_room changed ptrs
int cind = add_constant(s->typespec(), s->data(),
s->typespec().simpletype());
global_alias(i, cind); // Alias this symbol to the new const
} else if (s->valuesource() == Symbol::DefaultVal
&& s->has_init_ops()) {
// Default val comes from init ops -- special cases? Yes,
// if it's a simple assignment from a global whose value is
// not reassigned later, we can just alias it, and if we're
// lucky that may eliminate all uses of the parameter.
// First, trim init ops in case nops have accumulated
while (s->has_init_ops() && op(s->initbegin()).opname() == u_nop)
s->initbegin(s->initbegin() + 1);
while (s->has_init_ops() && op(s->initend() - 1).opname() == u_nop)
s->initend(s->initend() - 1);
if (s->initbegin() == s->initend() - 1) { // just one op
Opcode& op(inst()->ops()[s->initbegin()]);
if (op.opname() == u_assign) {
// The default value has init ops, but they consist of
// just a single assignment op...
Symbol* src = inst()->argsymbol(op.firstarg() + 1);
// Is it assigning a global, or a parameter that's
// got a default or instance value and isn't on the geom,
// and its value is never changed and the types match?
if ((src->symtype() == SymTypeGlobal
|| src->symtype() == SymTypeConst
|| (src->symtype() == SymTypeParam && src->lockgeom()
&& (src->valuesource() == Symbol::DefaultVal
|| src->valuesource() == Symbol::InstanceVal)))
&& !src->everwritten()
&& equivalent(src->typespec(), s->typespec())) {
// Great, so let's remember the alias. We can't
// call global_alias() here, because we're still in
// init ops, that'll screw us up. So we just record
// it in m_param_aliases and then we'll establish
// the global aliases when we hit the main code.
m_param_aliases[i] = inst()->arg(op.firstarg() + 1);
}
}
}
} else if (s->valuesource() == Symbol::ConnectedVal) {
// It's connected to an earlier layer. If the output var of
// the upstream shader is effectively constant or a global,
// then so is this variable.
for (auto&& c : inst()->connections()) {
if (c.dst.param != i)
continue;
if (c.dst.is_complete()) {
/// All components are being set through either
/// float->triple or triple->triple
/// Get rid of the un-needed init ops.
turn_into_nop(s->initbegin(), s->initend(),
"connected value doesn't need init ops");
}
if (c.is_complete()) {
// srcsym is the earlier group's output param, which
// is fully connected as the input to the param we're
// examining.
ShaderInstance* uplayer = group()[c.srclayer];
Symbol* srcsym = uplayer->symbol(c.src.param);
if (srcsym->interpolated())
continue; // Not if it can be overridden by geometry
// Is the source symbol known to be a global, from
// earlier analysis by find_params_holding_globals?
// If so, make sure the global is in this instance's
// symbol table, and alias the parameter to it.
ustringmap_t& g(m_params_holding_globals[c.srclayer]);
auto f = g.find(srcsym->name());
if (f != g.end()) {
if (debug() > 1)
debug_optfmt(
"Remapping {}.{} because it's connected to "
"{}.{}, which is known to be {}\n",
inst()->layername(), s->name(),
uplayer->layername(), srcsym->name(),
f->second);
make_symbol_room(1);
s = inst()->symbol(
i); // In case make_symbol_room changed ptrs
int ind = add_global(f->second, srcsym->typespec());
global_alias(i, ind);
shadingsys().m_stat_global_connections += 1;
break;