forked from AcademySoftwareFoundation/OpenShadingLanguage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatched_llvm_gen.cpp
More file actions
8772 lines (7529 loc) · 366 KB
/
batched_llvm_gen.cpp
File metadata and controls
8772 lines (7529 loc) · 366 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 <set>
#include <llvm/IR/Constant.h>
#include <OSL/oslconfig.h>
#include <OSL/batched_rendererservices.h>
#ifdef OSL_DEV
# include <llvm/Support/raw_os_ostream.h>
#endif
#include "batched_backendllvm.h"
using namespace OSL;
using namespace OSL::pvt;
OSL_NAMESPACE_BEGIN
namespace pvt {
static ustring op_and("and");
static ustring op_bitand("bitand");
static ustring op_bitor("bitor");
static ustring op_break("break");
static ustring op_ceil("ceil");
static ustring op_compl("compl");
static ustring op_continue("continue");
static ustring op_dowhile("dowhile");
static ustring op_eq("eq");
static ustring op_error("error");
static ustring op_floor("floor");
static ustring op_format("format");
static ustring op_fprintf("fprintf");
static ustring op_ge("ge");
static ustring op_gt("gt");
static ustring op_logb("logb");
static ustring op_le("le");
static ustring op_lt("lt");
static ustring op_min("min");
static ustring op_neq("neq");
static ustring op_printf("printf");
static ustring op_round("round");
static ustring op_shl("shl");
static ustring op_shr("shr");
static ustring op_sign("sign");
static ustring op_step("step");
static ustring op_trunc("trunc");
static ustring op_warning("warning");
static ustring op_xor("xor");
static ustring u_distance("distance");
static ustring u_index("index");
/// Macro that defines the arguments to LLVM IR generating routines
///
#define LLVMGEN_ARGS BatchedBackendLLVM &rop, int opnum
/// Macro that defines the full declaration of an LLVM generator.
///
#define LLVMGEN(name) bool name(LLVMGEN_ARGS)
// Forward decl
LLVMGEN(llvm_gen_generic);
typedef typename BatchedBackendLLVM::FuncSpec FuncSpec;
void
BatchedBackendLLVM::llvm_gen_debug_printf(string_view message)
{
ustring s = ustring::fmtformat("({} {}) {}", inst()->shadername(),
inst()->layername(), message);
ll.call_function(build_name("printf"), sg_void_ptr(), ll.constant("%s\n"),
ll.constant(s));
}
void
BatchedBackendLLVM::llvm_call_layer(int layer, bool unconditional)
{
OSL_DEV_ONLY(std::cout << "llvm_call_layer layer=" << layer
<< " unconditional=" << unconditional << std::endl);
// Make code that looks like:
// if (! groupdata->run[parentlayer])
// parent_layer (sg, groupdata, wide_shadeindex_ptr,
// userdata_base_ptr, output_base_ptr,
// execution_mask, interactive_params_ptr);
// if it's a conditional call, or
// parent_layer (sg, groupdata, wide_shadeindex_ptr,
// userdata_base_ptr, output_base_ptr,
// execution_mask, interactive_params_ptr);
// if it's run unconditionally.
// The code in the parent layer itself will set its 'executed' flag.
llvm::Value* args[7];
args[0] = sg_ptr();
args[1] = groupdata_ptr();
args[2] = ll.void_ptr(wide_shadeindex_ptr());
args[3] = userdata_base_ptr();
args[4] = output_base_ptr();
ShaderInstance* parent = group()[layer];
llvm::Value* layerfield = layer_run_ref(layer_remap(layer));
llvm::BasicBlock *then_block = NULL, *after_block = NULL;
llvm::Value* lanes_requiring_execution_value = nullptr;
if (!unconditional) {
llvm::Value* previously_executed = ll.int_as_mask(
ll.op_load(ll.type_int(), layerfield));
llvm::Value* lanes_requiring_execution
= ll.op_select(previously_executed, ll.wide_constant_bool(false),
ll.current_mask());
lanes_requiring_execution_value = ll.mask_as_int(
lanes_requiring_execution);
llvm::Value* execution_required
= ll.op_ne(lanes_requiring_execution_value, ll.constant(0));
then_block = ll.new_basic_block(
llvm_debug() ? Strutil::fmt::format("then layer {}", layer)
: std::string());
after_block = ll.new_basic_block(
llvm_debug() ? Strutil::fmt::format("after layer {}", layer)
: std::string());
ll.op_branch(execution_required, then_block, after_block);
// insert point is now then_block
} else {
lanes_requiring_execution_value = ll.mask_as_int(ll.shader_mask());
}
args[5] = lanes_requiring_execution_value;
args[6] = m_llvm_interactive_params_ptr;
// Before the merge, keeping in case we broke it
//std::string name = fmtformat("{}_{}_{}", m_library_selector, parent->layername().c_str(),
// parent->id());
std::string name
= Strutil::fmt::format("{}_{}", m_library_selector,
layer_function_name(group(), *parent));
// Mark the call as a fast call
llvm::Value* funccall = ll.call_function(name.c_str(), args);
if (!parent->entry_layer())
ll.mark_fast_func_call(funccall);
if (!unconditional)
ll.op_branch(after_block); // also moves insert point
shadingsys().m_stat_call_layers_inserted++;
}
void
BatchedBackendLLVM::llvm_run_connected_layers(const Symbol& sym, int symindex,
int opnum,
std::set<int>* already_run)
{
if (sym.valuesource() != Symbol::ConnectedVal)
return; // Nothing to do
OSL_DEV_ONLY(std::cout << "BatchedBackendLLVM::llvm_run_connected_layers "
<< sym.name().c_str() << " opnum " << opnum
<< std::endl);
bool inmain = (opnum >= inst()->maincodebegin()
&& opnum < inst()->maincodeend());
for (int c = 0; c < inst()->nconnections(); ++c) {
const Connection& con(inst()->connection(c));
// If the connection gives a value to this param
if (con.dst.param == symindex) {
// already_run is a set of layers run for this particular op.
// Just so we don't stupidly do several consecutive checks on
// whether we ran this same layer. It's JUST for this op.
if (already_run) {
if (already_run->count(con.srclayer))
continue; // already ran that one on this op
else
already_run->insert(con.srclayer); // mark it
}
if (inmain) {
// There is an instance-wide m_layers_already_run that tries
// to remember which earlier layers have unconditionally
// been run at any point in the execution of this layer. But
// only honor (and modify) that when in the main code
// section, not when in init ops, which are inherently
// conditional.
if (m_layers_already_run.count(con.srclayer)) {
continue; // already unconditionally ran the layer
}
if (!m_in_conditional[opnum]) {
// Unconditionally running -- mark so we don't do it
// again. If we're inside a conditional, don't mark
// because it may not execute the conditional body.
m_layers_already_run.insert(con.srclayer);
}
}
if (shadingsys().m_opt_useparam && inmain) {
// m_call_layers_inserted tracks if we've already run this layer inside the current basic block
const CallLayerKey key = { m_bblockids[opnum], con.srclayer };
if (m_call_layers_inserted.count(key)) {
continue;
}
m_call_layers_inserted.insert(key);
}
// If the earlier layer it comes from has not yet been
// executed, do so now.
llvm_call_layer(con.srclayer);
}
}
}
LLVMGEN(llvm_gen_nop)
{
return true;
}
LLVMGEN(llvm_gen_useparam)
{
OSL_ASSERT(!rop.inst()->unused()
&& "oops, thought this layer was unused, why do we call it?");
OSL_DEV_ONLY(
std::cout << ">>>>>>>>>>>>>>>>>>>>>llvm_gen_useparam <<<<<<<<<<<<<<<<<<<"
<< std::endl);
// If we have multiple params needed on this statement, don't waste
// time checking the same upstream layer more than once.
std::set<int> already_run;
Opcode& op(rop.inst()->ops()[opnum]);
for (int i = 0; i < op.nargs(); ++i) {
Symbol& sym = *rop.opargsym(op, i);
int symindex = rop.inst()->arg(op.firstarg() + i);
rop.llvm_run_connected_layers(sym, symindex, opnum, &already_run);
// If it's an interpolated (userdata) parameter and we're
// initializing them lazily, now we have to do it.
if ((sym.symtype() == SymTypeParam
|| sym.symtype() == SymTypeOutputParam)
&& sym.interpolated() && !sym.typespec().is_closure()
&& !sym.connected() && !sym.connected_down()
&& rop.shadingsys().lazy_userdata()) {
rop.llvm_assign_initial_value(sym, rop.ll.mask_as_int(
rop.ll.current_mask()));
}
}
rop.increment_useparam_ops();
return true;
}
// Used for printf, error, warning, format, fprintf
LLVMGEN(llvm_gen_printf)
{
Opcode& op(rop.inst()->ops()[opnum]);
// Prepare the args for the call
// Which argument is the format string? Usually 0, but for op
// format() and fprintf(), the formatting string is argument #1.
int format_arg = (op.opname() == "format" || op.opname() == "fprintf") ? 1
: 0;
Symbol& format_sym = *rop.opargsym(op, format_arg);
OSL_ASSERT(format_sym.is_uniform());
// For WIDE parameters we want to test the lane first to see
// if we need to extract values or not
struct DelayedExtraction {
int argument_slot;
bool is_float;
bool is_closure;
llvm::Value* loaded_value;
};
std::vector<DelayedExtraction> delay_extraction_args;
std::vector<llvm::Value*> call_args;
if (!format_sym.is_constant()) {
rop.shadingcontext()->warningfmt(
"{} must currently have constant format\n", op.opname());
return false;
}
ustring format_ustring = format_sym.get_string();
const char* format = format_ustring.c_str();
std::string s;
int arg = format_arg + 1;
// Check all arguments to see if we will need to generate
// a separate printf call for each data lane or not
// consider the op to be uniform until we find an argument that isn't
bool op_is_uniform = true;
for (int a = arg; a < op.nargs(); ++a) {
Symbol& sym(*rop.opargsym(op, a));
bool arg_is_uniform = sym.is_uniform();
if (arg_is_uniform == false) {
op_is_uniform = false;
}
}
int mask_slot = -1;
// For some ops, we push the shader globals pointer
if (op.opname() == op_printf || op.opname() == op_error
|| op.opname() == op_warning || op.opname() == op_fprintf) {
auto sg = rop.sg_void_ptr();
call_args.push_back(sg);
// Add mask or placeholder
mask_slot = call_args.size();
call_args.push_back(op_is_uniform
? rop.ll.mask_as_int(rop.ll.current_mask())
: nullptr);
}
if (op.opname() == op_fprintf) {
Symbol& Filename = *rop.opargsym(op, 0);
llvm::Value* fn = rop.llvm_load_value(Filename);
call_args.push_back(fn);
}
// For some ops, we push the output symbol & mask
if ((op.opname() == op_format) && (false == op_is_uniform)) {
Symbol& outSymbol = *rop.opargsym(op, 0);
llvm::Value* outPtr = rop.llvm_void_ptr(outSymbol);
call_args.push_back(outPtr);
// Add placeholder for mask
mask_slot = call_args.size();
call_args.push_back(nullptr);
}
// We're going to need to adjust the format string as we go, but I'd
// like to reserve a spot for the char*.
size_t new_format_slot = call_args.size();
call_args.push_back(NULL);
while (*format != '\0') {
if (*format == '%') {
if (format[1] == '%') {
// '%%' is a literal '%'
s += "%%";
format += 2; // skip both percentages
continue;
}
const char* oldfmt = format; // mark beginning of format
while (*format && *format != 'c' && *format != 'd' && *format != 'e'
&& *format != 'f' && *format != 'g' && *format != 'i'
&& *format != 'm' && *format != 'n' && *format != 'o'
&& *format != 'p' && *format != 's' && *format != 'u'
&& *format != 'v' && *format != 'x' && *format != 'X')
++format;
char formatchar = *format++; // Also eat the format char
if (arg >= op.nargs()) {
rop.shadingcontext()->errorfmt(
"Mismatch between format string and arguments ({}:{})",
op.sourcefile(), op.sourceline());
return false;
}
std::string ourformat(oldfmt, format); // straddle the format
// Doctor it to fix mismatches between format and data
Symbol& sym(*rop.opargsym(op, arg));
OSL_ASSERT(!sym.typespec().is_structure_based());
bool arg_is_uniform = sym.is_uniform();
TypeDesc simpletype(sym.typespec().simpletype());
int num_elements = simpletype.numelements();
int num_components = simpletype.aggregate;
if ((sym.typespec().is_closure_based()
|| simpletype.basetype == TypeDesc::STRING)
&& formatchar != 's') {
ourformat[ourformat.length() - 1] = 's';
}
if (simpletype.basetype == TypeDesc::INT && formatchar != 'd'
&& formatchar != 'i' && formatchar != 'o' && formatchar != 'u'
&& formatchar != 'x' && formatchar != 'X') {
ourformat[ourformat.length() - 1] = 'd';
}
if (simpletype.basetype == TypeDesc::FLOAT && formatchar != 'f'
&& formatchar != 'g' && formatchar != 'c' && formatchar != 'e'
&& formatchar != 'm' && formatchar != 'n' && formatchar != 'p'
&& formatchar != 'v') {
ourformat[ourformat.length() - 1] = 'f';
}
// NOTE(boulos): Only for debug mode do the derivatives get printed...
for (int a = 0; a < num_elements; ++a) {
llvm::Value* arrind = simpletype.arraylen ? rop.ll.constant(a)
: NULL;
for (int c = 0; c < num_components; c++) {
if (c != 0 || a != 0)
s += " ";
s += ourformat;
// As the final printf library call does not handle wide
// data types, we will load the wide data type here and
// in a loop extract scalar values for the current data
// lane before making the scalar printf call.
// NOTE: We don't want any uniform arguments to be
// widened, so our typical op_is_uniform doesn't do what we
// want for this when loading. So just pass arg_is_uniform
// which will avoid widening any uniform arguments.
llvm::Value* loaded
= rop.llvm_load_value(sym, 0, arrind, c,
TypeDesc::UNKNOWN,
/*op_is_uniform*/ arg_is_uniform,
/*index_is_uniform*/ true);
// Always expand llvm booleans to integers
if (sym.forced_llvm_bool()) {
loaded = rop.ll.op_bool_to_int(loaded);
}
if (arg_is_uniform) {
if (simpletype.basetype == TypeDesc::FLOAT) {
// C varargs convention upconverts float->double.
loaded = rop.ll.op_float_to_double(loaded);
} else if (sym.typespec().is_closure_based()) {
// we need to convert this closure to a string
FuncSpec to_string("closure_to_string");
loaded = rop.ll.call_function(rop.build_name(
to_string),
rop.sg_void_ptr(),
loaded);
}
call_args.push_back(loaded);
} else {
OSL_ASSERT(false == op_is_uniform);
delay_extraction_args.push_back(DelayedExtraction {
static_cast<int>(call_args.size()),
simpletype.basetype == TypeDesc::FLOAT,
sym.typespec().is_closure_based(), loaded });
// Need to populate call arguments with a place holder
// that we can fill in later from a loop that loads values
// for each lane
call_args.push_back(nullptr);
}
}
}
++arg;
} else {
// Everything else -- just copy the character and advance
s += *format++;
}
}
// Some ops prepend things
if (op.opname() == op_error || op.opname() == op_warning) {
s = fmtformat("Shader {} [{}]: {}", op.opname(),
rop.inst()->shadername(), s);
}
// Now go back and put the new format string in its place
auto llvm_new_format_string = rop.ll.constant(s.c_str());
call_args[new_format_slot] = llvm_new_format_string;
// Construct the function name and call it.
const char* func_name = op.opname().c_str();
if ((op.opname() == op_format) && op_is_uniform) {
func_name = "format_uniform";
}
FuncSpec func_spec(func_name);
if (op_is_uniform) {
llvm::Value* ret = rop.ll.call_function(rop.build_name(func_spec),
call_args);
// The format op returns a string value, put in in the right spot
if (op.opname() == op_format)
rop.llvm_store_value(ret, *rop.opargsym(op, 0));
} else {
// Loop over each lane, if mask is active for the lane,
// extract values and call printf
llvm::Value* loc_of_lane_index
= rop.ll.op_alloca(rop.ll.type_int(), 1,
rop.llvm_debug() ? std::string("printf index")
: std::string());
rop.ll.op_unmasked_store(rop.ll.constant(0), loc_of_lane_index);
llvm::Value* mask = rop.ll.current_mask();
#ifdef __OSL_TRACE_MASKS
rop.llvm_print_mask("printf loop over:", mask);
#endif
llvm::BasicBlock* cond_block = rop.ll.new_basic_block(
rop.llvm_debug() ? std::string("printf_cond") : std::string());
llvm::BasicBlock* step_block = rop.ll.new_basic_block(
rop.llvm_debug() ? std::string("printf_step") : std::string());
llvm::BasicBlock* body_block = rop.ll.new_basic_block(
rop.llvm_debug() ? std::string("printf_body") : std::string());
llvm::BasicBlock* nested_body_block = rop.ll.new_basic_block(
rop.llvm_debug() ? std::string("printf_nested_body")
: std::string());
llvm::BasicBlock* after_block = rop.ll.new_basic_block(
rop.llvm_debug() ? std::string("after_printf") : std::string());
rop.ll.op_branch(cond_block);
{
// Condition
llvm::Value* lane_index = rop.ll.op_load(rop.ll.type_int(),
loc_of_lane_index);
llvm::Value* more_lanes_to_process
= rop.ll.op_lt(lane_index, rop.ll.constant(rop.vector_width()));
rop.ll.op_branch(more_lanes_to_process, body_block, after_block);
// body_block
// do printf of a single lane
llvm::Value* lane_active = rop.ll.test_mask_lane(mask, lane_index);
rop.ll.op_branch(lane_active, nested_body_block, step_block);
// nested_body_block
llvm::Value* int_value_lane_mask = rop.ll.op_shl(rop.ll.constant(1),
lane_index);
call_args[mask_slot] = int_value_lane_mask;
for (const DelayedExtraction& de : delay_extraction_args) {
llvm::Value* scalar_val = rop.ll.op_extract(de.loaded_value,
lane_index);
if (de.is_float) {
// C varargs convention upconverts float->double.
scalar_val = rop.ll.op_float_to_double(scalar_val);
} else if (de.is_closure) {
// we need to convert this closure to a string
FuncSpec to_string("closure_to_string");
scalar_val = rop.ll.call_function(rop.build_name(to_string),
rop.sg_void_ptr(),
scalar_val);
}
call_args[de.argument_slot] = scalar_val;
}
rop.ll.call_function(rop.build_name(func_spec), call_args);
rop.ll.op_branch(step_block);
// Step
//lane_index = rop.ll.op_load(rop.ll.type_int(), loc_of_lane_index);
llvm::Value* next_lane_index = rop.ll.op_add(lane_index,
rop.ll.constant(1));
rop.ll.op_unmasked_store(next_lane_index, loc_of_lane_index);
rop.ll.op_branch(cond_block);
// Continue on with the previous flow
rop.ll.set_insert_point(after_block);
}
}
return true;
}
// Array length
LLVMGEN(llvm_gen_arraylength)
{
Opcode& op(rop.inst()->ops()[opnum]);
Symbol& Result = *rop.opargsym(op, 0);
Symbol& A = *rop.opargsym(op, 1);
OSL_DASSERT(Result.typespec().is_int() && A.typespec().is_array());
int len = A.typespec().is_unsized_array() ? A.initializers()
: A.typespec().arraylength();
// Even thought the array's size should be uniform across all lanes,
// the symbol its being stored in maybe varying
llvm::Value* const_length = Result.is_uniform() ? rop.ll.constant(len)
: rop.ll.wide_constant(len);
rop.llvm_store_value(const_length, Result);
return true;
}
// Array reference
LLVMGEN(llvm_gen_aref)
{
Opcode& op(rop.inst()->ops()[opnum]);
Symbol& Result = *rop.opargsym(op, 0);
Symbol& Src = *rop.opargsym(op, 1);
Symbol& Index = *rop.opargsym(op, 2);
bool op_is_uniform = Result.is_uniform();
bool index_is_uniform = Index.is_uniform();
// Get array index we're interested in
llvm::Value* index = rop.loadLLVMValue(Index, 0, 0, TypeInt,
index_is_uniform);
if (!index)
return false;
if (rop.inst()->master()->range_checking()) {
if (index_is_uniform) {
if (!(Index.is_constant() && Index.get_int() >= 0
&& Index.get_int() < Src.typespec().arraylength())) {
llvm::Value* args[]
= { index,
rop.ll.constant(Src.typespec().arraylength()),
rop.ll.constant(Src.unmangled()),
rop.sg_void_ptr(),
rop.ll.constant(op.sourcefile()),
rop.ll.constant(op.sourceline()),
rop.ll.constant(rop.group().name()),
rop.ll.constant(rop.layer()),
rop.ll.constant(rop.inst()->layername()),
rop.ll.constant(rop.inst()->shadername()) };
index = rop.ll.call_function(rop.build_name("range_check"),
args);
}
} else {
BatchedBackendLLVM::TempScope temp_scope(rop);
// We need a copy of the indices in case the range check clamps them
llvm::Value* loc_clamped_wide_index = rop.getOrAllocateTemp(
TypeSpec(TypeDesc::INT), false /*derivs*/, false /*is_uniform*/,
false /*forceBool*/,
std::string("range clamped index:") + Src.name().c_str());
// copy the indices into our temporary
rop.ll.op_unmasked_store(index, loc_clamped_wide_index);
llvm::Value* args[]
= { rop.ll.void_ptr(loc_clamped_wide_index),
rop.ll.mask_as_int(rop.ll.current_mask()),
rop.ll.constant(Src.typespec().arraylength()),
rop.ll.constant(Src.unmangled()),
rop.sg_void_ptr(),
rop.ll.constant(op.sourcefile()),
rop.ll.constant(op.sourceline()),
rop.ll.constant(rop.group().name()),
rop.ll.constant(rop.layer()),
rop.ll.constant(rop.inst()->layername()),
rop.ll.constant(rop.inst()->shadername()) };
rop.ll.call_function(rop.build_name(FuncSpec("range_check").mask()),
args);
// Use the range check indices
index = rop.ll.op_load(rop.ll.type_wide_int(),
loc_clamped_wide_index);
}
}
int num_components = Src.typespec().simpletype().aggregate;
for (int d = 0; d <= 2; ++d) {
for (int c = 0; c < num_components; ++c) {
llvm::Value* val
= rop.llvm_load_value(Src, d, index, c, TypeDesc::UNKNOWN,
op_is_uniform, index_is_uniform);
rop.storeLLVMValue(val, Result, c, d);
}
if (!Result.has_derivs())
break;
}
return true;
}
// Array assignment
LLVMGEN(llvm_gen_aassign)
{
Opcode& op(rop.inst()->ops()[opnum]);
Symbol& Result = *rop.opargsym(op, 0);
Symbol& Index = *rop.opargsym(op, 1);
Symbol& Src = *rop.opargsym(op, 2);
bool resultIsUniform = Result.is_uniform();
bool index_is_uniform = Index.is_uniform();
OSL_ASSERT(index_is_uniform || !resultIsUniform);
// Get array index we're interested in
llvm::Value* index = rop.loadLLVMValue(Index, 0, 0, TypeInt,
index_is_uniform);
if (!index)
return false;
if (rop.inst()->master()->range_checking()) {
if (index_is_uniform) {
if (!(Index.is_constant() && Index.get_int() >= 0
&& Index.get_int() < Result.typespec().arraylength())) {
llvm::Value* args[]
= { index,
rop.ll.constant(Result.typespec().arraylength()),
rop.ll.constant(Result.unmangled()),
rop.sg_void_ptr(),
rop.ll.constant(op.sourcefile()),
rop.ll.constant(op.sourceline()),
rop.ll.constant(rop.group().name()),
rop.ll.constant(rop.layer()),
rop.ll.constant(rop.inst()->layername()),
rop.ll.constant(rop.inst()->shadername()) };
index = rop.ll.call_function(rop.build_name("range_check"),
args);
}
} else {
BatchedBackendLLVM::TempScope temp_scope(rop);
// We need a copy of the indices in case the range check clamps them
llvm::Value* loc_clamped_wide_index = rop.getOrAllocateTemp(
TypeSpec(TypeDesc::INT), false /*derivs*/, false /*is_uniform*/,
false /*forceBool*/,
std::string("range clamped index:") + Result.name().c_str());
// copy the indices into our temporary
rop.ll.op_unmasked_store(index, loc_clamped_wide_index);
llvm::Value* args[]
= { rop.ll.void_ptr(loc_clamped_wide_index),
rop.ll.mask_as_int(rop.ll.current_mask()),
rop.ll.constant(Result.typespec().arraylength()),
rop.ll.constant(Result.unmangled()),
rop.sg_void_ptr(),
rop.ll.constant(op.sourcefile()),
rop.ll.constant(op.sourceline()),
rop.ll.constant(rop.group().name()),
rop.ll.constant(rop.layer()),
rop.ll.constant(rop.inst()->layername()),
rop.ll.constant(rop.inst()->shadername()) };
rop.ll.call_function(rop.build_name(FuncSpec("range_check").mask()),
args);
// Use the range check indices
index = rop.ll.op_load(rop.ll.type_wide_int(),
loc_clamped_wide_index);
}
}
int num_components = Result.typespec().simpletype().aggregate;
// Allow float <=> int casting
TypeDesc cast; // defaults to TypeDesc::UNKNOWN
if (num_components == 1 && !Result.typespec().is_closure()
&& !Src.typespec().is_closure()
&& (Result.typespec().is_int_based()
|| Result.typespec().is_float_based())
&& (Src.typespec().is_int_based() || Src.typespec().is_float_based())) {
cast = Result.typespec().simpletype();
cast.arraylen = 0;
} else {
// Try to warn before llvm_fatal_error is called which provides little
// context as to what went wrong.
OSL_ASSERT(Result.typespec().simpletype().basetype
== Src.typespec().simpletype().basetype);
}
for (int d = 0; d <= 2; ++d) {
for (int c = 0; c < num_components; ++c) {
llvm::Value* val = rop.loadLLVMValue(Src, c, d, cast,
resultIsUniform);
// Bool is not a supported OSL type, so if we find one it needs
// to be promoted to an int
llvm::Type* typeOfVal = rop.ll.llvm_typeof(val);
if (typeOfVal == rop.ll.type_bool()
|| typeOfVal == rop.ll.type_wide_bool()) {
val = rop.ll.op_bool_to_int(val);
}
rop.llvm_store_value(val, Result, d, index, c, index_is_uniform);
}
if (!Result.has_derivs())
break;
}
return true;
}
// Generic llvm code generation. See the comments in llvm_ops.cpp for
// the full list of assumptions and conventions. But in short:
// 1. All polymorphic and derivative cases implemented as functions in
// llvm_ops.cpp -- no custom IR is needed.
// 2. Naming conention is: osl_NAME_{args}, where args is the
// concatenation of type codes for all args including return value --
// f/i/v/m/s for float/int/triple/matrix/string, and df/dv/dm for
// duals.
// 3. The function returns scalars as an actual return value (that
// must be stored), but "returns" aggregates or duals in the first
// argument.
// 4. Duals and aggregates are passed as void*'s, float/int/string
// passed by value.
// 5. Note that this only works if triples are all treated identically,
// this routine can't be used if it must be polymorphic based on
// color, point, vector, normal differences.
//
LLVMGEN(llvm_gen_generic)
{
Opcode& op(rop.inst()->ops()[opnum]);
bool uniformFormOfFunction = true;
for (int i = 0; i < op.nargs(); ++i) {
Symbol* s(rop.opargsym(op, i));
if (s->is_uniform() == false) {
uniformFormOfFunction = false;
}
}
Symbol& Result = *rop.opargsym(op, 0);
std::vector<const Symbol*> args;
bool any_deriv_args = false;
for (int i = 0; i < op.nargs(); ++i) {
Symbol* s(rop.opargsym(op, i));
args.push_back(s);
any_deriv_args |= (i > 0 && s->has_derivs()
&& !s->typespec().is_matrix());
}
// Special cases: functions that have no derivs -- suppress them
if (any_deriv_args)
if (op.opname() == op_logb || op.opname() == op_floor
|| op.opname() == op_ceil || op.opname() == op_round
|| op.opname() == op_step || op.opname() == op_trunc
|| op.opname() == op_sign)
any_deriv_args = false;
FuncSpec func_spec(op.opname().c_str());
if (uniformFormOfFunction) {
func_spec.unbatch();
}
for (int i = 0; i < op.nargs(); ++i) {
Symbol* s(rop.opargsym(op, i));
bool has_derivs = any_deriv_args && Result.has_derivs()
&& s->has_derivs() && !s->typespec().is_matrix();
func_spec.arg(*s, has_derivs, uniformFormOfFunction);
}
OSL_DEV_ONLY(std::cout << "llvm_gen_generic " << rop.build_name(func_spec)
<< std::endl);
if (!Result.has_derivs() || !any_deriv_args) {
// Right now all library calls are not LLVM IR, so can't be inlined
// In future perhaps we can detect if function exists in module
// and choose to inline.
// Controls if parameters are passed by value or pointer
// and if the mask is passed as llvm type or integer
constexpr bool functionIsLlvmInlined = false;
// This can get a bit confusing here,
// basically in the uniform version, scalar values can be returned by value
// by functions. However, if varying, those scalar's are really wide
// and we can't return by value. Except if the function in question
// is llvm source marked as always inline. In that case we can return
// wide types. For all other cases we need to pass a pointer to the
// where the return value needs to go.
// Don't compute derivs -- either not needed or not provided in args
if (Result.typespec().aggregate() == TypeDesc::SCALAR
&& (uniformFormOfFunction || functionIsLlvmInlined)) {
OSL_DEV_ONLY(std::cout << ">>stores return value "
<< rop.build_name(func_spec) << std::endl);
llvm::Value* r = rop.llvm_call_function(
func_spec, &(args[1]), op.nargs() - 1,
/*deriv_ptrs*/ false, uniformFormOfFunction,
functionIsLlvmInlined, false /*ptrToReturnStructIs1stArg*/);
if (uniformFormOfFunction
&& Result.typespec().simpletype() == TypeDesc::STRING) {
// We did call a function from the scalar version
// of the OSL library. The scalar version has
// changed to use ustringhash_pod, but the wide version hasn't yet
// So we will need to extract the ustring from the resulting ustringhash_pod.
r = rop.ll.call_function("osl_gen_ustring", r);
}
// The store will deal with masking
rop.llvm_store_value(r, Result);
} else {
OSL_DEV_ONLY(std::cout << ">>return value is pointer "
<< rop.build_name(func_spec) << std::endl);
rop.llvm_call_function(func_spec, (args.size()) ? &(args[0]) : NULL,
op.nargs(),
/*deriv_ptrs*/ false, uniformFormOfFunction,
functionIsLlvmInlined,
true /*ptrToReturnStructIs1stArg*/);
}
rop.llvm_zero_derivs(Result);
} else {
// Cases with derivs
OSL_DEV_ONLY(std::cout << " Cases with derivs");
OSL_ASSERT(Result.has_derivs() && any_deriv_args);
rop.llvm_call_function(func_spec, (args.size()) ? &(args[0]) : NULL,
op.nargs(),
/*deriv_ptrs*/ true, uniformFormOfFunction,
false /*functionIsLlvmInlined*/,
true /*ptrToReturnStructIs1stArg*/);
}
OSL_DEV_ONLY(std::cout << std::endl);
return true;
}
LLVMGEN(llvm_gen_sincos)
{
Opcode& op(rop.inst()->ops()[opnum]);
Symbol& Theta = *rop.opargsym(op, 0); //Input
Symbol& Sin_out = *rop.opargsym(op, 1); //Output
Symbol& Cos_out = *rop.opargsym(op, 2); //Output
bool theta_deriv = Theta.has_derivs();
bool result_derivs = (Sin_out.has_derivs() || Cos_out.has_derivs());
bool op_is_uniform = Theta.is_uniform();
OSL_ASSERT(op_is_uniform
|| (!Sin_out.is_uniform() && !Cos_out.is_uniform()));
// Handle broadcasting results to wide results
BatchedBackendLLVM::TempScope temp_scope(rop);
llvm::Value* theta_param = nullptr;
// Need 2 pointers, because the parameter must be void *
// but we need a typed * for the broadcast later
llvm::Value* sin_out_typed_temp = nullptr;
llvm::Value* sin_out_param = nullptr;
llvm::Value* cos_out_typed_temp = nullptr;
llvm::Value* cos_out_param = nullptr;
if (true
== ((theta_deriv && result_derivs) || Theta.typespec().is_triple()
|| !op_is_uniform)) {
theta_param = rop.llvm_void_ptr(Theta, 0); //If varying
} else {
theta_param = rop.llvm_load_value(Theta);
}
//rop.llvm_store_value(wideTheta, Theta);
FuncSpec func_spec("sincos");
func_spec.arg(Theta, result_derivs && theta_deriv, op_is_uniform);
func_spec.arg(Sin_out, Sin_out.has_derivs() && result_derivs && theta_deriv,
op_is_uniform);
func_spec.arg(Cos_out, Cos_out.has_derivs() && result_derivs && theta_deriv,
op_is_uniform);
if (op_is_uniform && !Sin_out.is_uniform()) {
sin_out_typed_temp = rop.getOrAllocateTemp(Sin_out.typespec(),
Sin_out.has_derivs(),
true /*is_uniform*/);
sin_out_param = rop.ll.void_ptr(sin_out_typed_temp);
} else {
sin_out_param = rop.llvm_void_ptr(Sin_out, 0);
}
if (op_is_uniform && !Cos_out.is_uniform()) {
cos_out_typed_temp = rop.getOrAllocateTemp(Cos_out.typespec(),
Cos_out.has_derivs(),
true /*is_uniform*/);
cos_out_param = rop.ll.void_ptr(cos_out_typed_temp);
} else {
cos_out_param = rop.llvm_void_ptr(Cos_out, 0);
}
llvm::Value* args[] = { theta_param, sin_out_param, cos_out_param,
nullptr };
int arg_count = 3;
if (!op_is_uniform) {
if (rop.ll.is_masking_required()) {
func_spec.mask();
args[arg_count++] = rop.ll.mask_as_int(rop.ll.current_mask());
}
} else {
func_spec.unbatch();
}
rop.ll.call_function(rop.build_name(func_spec),
cspan<llvm::Value*>(args, arg_count));
if (op_is_uniform && !Sin_out.is_uniform()) {
rop.llvm_broadcast_uniform_value_from_mem(sin_out_typed_temp, Sin_out);
}
if (op_is_uniform && !Cos_out.is_uniform()) {
rop.llvm_broadcast_uniform_value_from_mem(cos_out_typed_temp, Cos_out);
}
// If the input angle didn't have derivatives, we would not have
// called the version of sincos with derivs; however in that case we
// need to clear the derivs of either of the outputs that has them.
if (Sin_out.has_derivs() && !theta_deriv)
rop.llvm_zero_derivs(Sin_out);