-
Notifications
You must be signed in to change notification settings - Fork 405
Expand file tree
/
Copy pathllvm_instance.cpp
More file actions
1946 lines (1701 loc) · 78.2 KB
/
llvm_instance.cpp
File metadata and controls
1946 lines (1701 loc) · 78.2 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 <bitset>
#include <cmath>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#ifdef __GNUC__
# include <cxxabi.h>
#endif
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/fmath.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/timer.h>
#include "../liboslcomp/oslcomp_pvt.h"
#include "oslexec_pvt.h"
#include "backendllvm.h"
// Create external declarations for all built-in funcs we may call from LLVM
#define DECL(name, signature) extern "C" void name();
#include "builtindecl.h"
#undef DECL
/*
This whole file is concerned with taking our post-optimized OSO
intermediate code and translating it into LLVM IR code so we can JIT it
and run it directly, for an expected huge speed gain over running our
interpreter.
Schematically, we want to create code that resembles the following:
// In this example, we assume a shader group with 2 layers.
// The GroupData struct is defined that gives the layout of the "heap",
// the temporary memory arena that the shader can use as it executes.
struct GroupData {
// Array telling if we have already run each layer
char layer_run[nlayers];
// Array telling if we have already initialized each
// needed user data (0 = haven't checked, 1 = checked and there
// was no userdata, 2 = checked and there was userdata)
char userdata_initialized[num_userdata];
// All the user data slots, in order
float userdata_s;
float userdata_t;
// For each layer in the group, we declare all shader params
// whose values are not known -- they have init ops, or are
// interpolated from the geom, or are connected to other layers.
float param_0_foo; // number is layer ID
float param_1_bar;
};
// Data for the interactively adjusted parameters of this group -- these
// can't be turned into constants because the app may want to modify them
// as it runs (such as for user interaction). This block of memory has
// one global copy specific each the shader group, managed by OSL.
struct InteractiveParams {
float iparam_0_baz;
};
// Name of layer entry is $layer_ID
void $layer_0(ShaderGlobals* sg, GroupData* group,
void* userdatda_base_ptr, void* output_base_ptr,
int shadeindex, InteractiveParams* interactive_params)
{
// Declare locals, temps, constants, params with known values.
// Make them all look like stack memory locations:
float *x = alloca(sizeof(float));
// ...and so on for all the other locals & temps...
// then run the shader body:
*x = sg->u * group->param_0_bar;
group->param_1_foo = *x;
*x += interactive_params->iparam_0_baz;
// ...
}
void $layer_1(ShaderGlobals* sg, GroupData* group,
void* userdatda_base_ptr, void* output_base_ptr,
int shadeindex, InteractiveParams* interactive_params)
{
// Because we need the outputs of layer 0 now, we call it if it
// hasn't already run:
if (! group->layer_run[0]) {
group->layer_run[0] = 1;
$layer_0 (sg, group, userdata_base_ptr, output_base_ptr,
shadeindex, interactive_params); // because we need its outputs
}
*y = sg->u * group->$param_1_bar;
}
void $group_1(ShaderGlobals* sg, GroupData* group,
void* userdatda_base_ptr, void* output_base_ptr,
int shadeindex, InteractiveParams* interactive_params)
{
group->layer_run[...] = 0;
// Run just the unconditional layers
if (! group->layer_run[1]) {
group->layer_run[1] = 1;
$layer_1(sg, group, userdata_base_ptr, output_base_ptr,
shadeindex, interactive_params);
}
}
*/
extern int osl_llvm_compiled_ops_size;
extern unsigned char osl_llvm_compiled_ops_block[];
extern int osl_llvm_compiled_ops_cuda_size;
extern unsigned char osl_llvm_compiled_ops_cuda_block[];
extern int osl_llvm_compiled_rs_dependent_ops_size;
extern unsigned char osl_llvm_compiled_rs_dependent_ops_block[];
using namespace OSL::pvt;
OSL_NAMESPACE_ENTER
namespace pvt {
static spin_mutex llvm_mutex;
static ustring op_end("end");
static ustring op_nop("nop");
static ustring op_aassign("aassign");
static ustring op_compassign("compassign");
static ustring op_mxcompassign("mxcompassign");
static ustring op_aref("aref");
static ustring op_compref("compref");
static ustring op_mxcompref("mxcompref");
static ustring op_useparam("useparam");
static ustring unknown_shader_group_name("<Unknown Shader Group Name>");
struct HelperFuncRecord {
const char* argtypes;
void (*function)();
HelperFuncRecord(const char* argtypes = NULL, void (*function)() = NULL)
: argtypes(argtypes), function(function)
{
}
};
typedef std::unordered_map<std::string, HelperFuncRecord> HelperFuncMap;
static HelperFuncMap llvm_helper_function_map;
static atomic_int llvm_helper_function_map_initialized(0);
static spin_mutex llvm_helper_function_map_mutex;
static std::vector<std::string>
external_function_names; // used for internalize_module_functions
static void
initialize_llvm_helper_function_map()
{
if (llvm_helper_function_map_initialized)
return; // already done
spin_lock lock(llvm_helper_function_map_mutex);
if (llvm_helper_function_map_initialized)
return;
#define DECL(name, signature) \
llvm_helper_function_map[#name] = HelperFuncRecord(signature, name); \
external_function_names.push_back(#name);
#include "builtindecl.h"
#undef DECL
llvm_helper_function_map_initialized = 1;
}
static void*
helper_function_lookup(const std::string& name)
{
HelperFuncMap::const_iterator i = llvm_helper_function_map.find(name);
if (i == llvm_helper_function_map.end())
return NULL;
return (void*)i->second.function;
}
std::string
layer_function_name(const ShaderGroup& group, const ShaderInstance& inst,
bool api)
{
bool use_optix = inst.shadingsys().use_optix();
const char* prefix = use_optix && api ? "__direct_callable__" : "";
return fmtformat("{}osl_layer_group_{}_name_{}", prefix, group.name(),
inst.layername());
}
std::string
init_function_name(const ShadingSystemImpl& shadingsys,
const ShaderGroup& group, bool api)
{
bool use_optix = shadingsys.use_optix();
const char* prefix = use_optix && api ? "__direct_callable__" : "";
return fmtformat("{}osl_init_group_{}", prefix, group.name());
}
std::string
fused_function_name(const ShaderGroup& group)
{
int nlayers = group.nlayers();
ShaderInstance* inst = group[nlayers - 1];
return fmtformat("__direct_callable__fused_{}_name_{}", group.name(),
inst->layername());
}
llvm::Type*
BackendLLVM::llvm_type_sg()
{
// Create a type that defines the ShaderGlobals for LLVM IR. This
// absolutely MUST exactly match the ShaderGlobals struct in oslexec.h.
if (m_llvm_type_sg)
return m_llvm_type_sg;
// Derivs look like arrays of 3 values
llvm::Type* float_deriv = llvm_type(
TypeDesc(TypeDesc::FLOAT, TypeDesc::SCALAR, 3));
llvm::Type* triple_deriv = llvm_type(
TypeDesc(TypeDesc::FLOAT, TypeDesc::VEC3, 3));
std::vector<llvm::Type*> sg_types;
sg_types.push_back(triple_deriv); // P, dPdx, dPdy
sg_types.push_back(ll.type_triple()); // dPdz
sg_types.push_back(triple_deriv); // I, dIdx, dIdy
sg_types.push_back(ll.type_triple()); // N
sg_types.push_back(ll.type_triple()); // Ng
sg_types.push_back(float_deriv); // u, dudx, dudy
sg_types.push_back(float_deriv); // v, dvdx, dvdy
sg_types.push_back(ll.type_triple()); // dPdu
sg_types.push_back(ll.type_triple()); // dPdv
sg_types.push_back(ll.type_float()); // time
sg_types.push_back(ll.type_float()); // dtime
sg_types.push_back(ll.type_triple()); // dPdtime
sg_types.push_back(triple_deriv); // Ps
llvm::Type* vp = (llvm::Type*)ll.type_void_ptr();
sg_types.push_back(vp); // opaque renderstate*
sg_types.push_back(vp); // opaque tracedata*
sg_types.push_back(vp); // opaque objdata*
sg_types.push_back(vp); // ShadingContext*
sg_types.push_back(vp); // OpaqueShadingStateUniformPtr
sg_types.push_back(vp); // RendererServices*
sg_types.push_back(vp); // object2common
sg_types.push_back(vp); // shader2common
sg_types.push_back(vp); // Ci
sg_types.push_back(ll.type_float()); // surfacearea
sg_types.push_back(ll.type_int()); // raytype
sg_types.push_back(ll.type_int()); // flipHandedness
sg_types.push_back(ll.type_int()); // backfacing
return m_llvm_type_sg = ll.type_struct(sg_types, "ShaderGlobals");
}
llvm::Type*
BackendLLVM::llvm_type_sg_ptr()
{
return ll.type_ptr(llvm_type_sg());
}
llvm::Type*
BackendLLVM::llvm_type_groupdata()
{
// If already computed, return it
if (m_llvm_type_groupdata)
return m_llvm_type_groupdata;
std::vector<llvm::Type*> fields;
int offset = 0;
int order = 0;
m_groupdata_field_names.clear();
if (llvm_debug() >= 2)
std::cout << "Group param struct:\n";
// First, add the array that tells if each layer has run. But only make
// slots for the layers that may be called/used.
if (llvm_debug() >= 2)
std::cout << " layers run flags: " << m_num_used_layers
<< " at offset " << offset << "\n";
int sz = (m_num_used_layers + 3) & (~3); // Round up to 32 bit boundary
fields.push_back(ll.type_array(ll.type_bool(), sz));
m_groupdata_field_names.emplace_back("layer_runflags");
offset += sz * sizeof(bool);
++order;
// Now add the array that tells which userdata have been initialized,
// and the space for the userdata values.
int nuserdata = (int)group().m_userdata_names.size();
if (nuserdata) {
if (llvm_debug() >= 2)
std::cout << " userdata initialized flags: " << nuserdata
<< " at offset " << offset << ", field " << order << "\n";
ustring* names = &group().m_userdata_names[0];
TypeDesc* types = &group().m_userdata_types[0];
int* offsets = &group().m_userdata_offsets[0];
int sz = (nuserdata + 3) & (~3);
fields.push_back(ll.type_array(ll.type_bool(), sz));
m_groupdata_field_names.emplace_back("userdata_init_flags");
offset += nuserdata * sizeof(bool);
++order;
for (int i = 0; i < nuserdata; ++i) {
TypeDesc type = types[i];
// make room for float derivs only
type.arraylen = type.basetype == TypeDesc::FLOAT
? type.numelements() * 3
: type.numelements();
fields.push_back(llvm_type(type));
m_groupdata_field_names.emplace_back(
fmtformat("userdata{}_{}_", i, names[i]));
// Alignment
int align = type.basesize();
offset = OIIO::round_to_multiple_of_pow2(offset, align);
if (llvm_debug() >= 2)
std::cout << " userdata " << names[i] << ' ' << type
<< ", field " << order << ", offset " << offset
<< "\n";
offsets[i] = offset;
offset += int(type.size());
++order;
}
}
// For each layer in the group, add entries for all params that are
// connected or interpolated, and output params. Also mark those
// symbols with their offset within the group struct.
m_param_order_map.clear();
for (int layer = 0; layer < group().nlayers(); ++layer) {
ShaderInstance* inst = group()[layer];
if (inst->unused())
continue;
FOREACH_PARAM(Symbol & sym, inst)
{
TypeSpec ts = sym.typespec();
if (ts.is_structure()) // skip the struct symbol itself
continue;
const int arraylen = std::max(1, sym.typespec().arraylength());
const int derivSize = (sym.has_derivs() ? 3 : 1);
ts.make_array(arraylen * derivSize);
fields.push_back(llvm_type(ts));
m_groupdata_field_names.emplace_back(
fmtformat("lay{}param_{}_", layer, sym.name()));
// FIXME(arena) -- temporary debugging
if (debug() && sym.symtype() == SymTypeOutputParam
&& !sym.connected_down()) {
auto found = group().find_symloc(sym.name());
if (found)
print("layer {} \"{}\" : OUTPUT {}\n", layer,
inst->layername(), found->name);
}
// Alignment
size_t align = sym.typespec().is_closure_based()
? sizeof(void*)
: sym.typespec().simpletype().basesize();
if (offset & (align - 1))
offset += align - (offset & (align - 1));
if (llvm_debug() >= 2)
print(" {} ({}) {} {}, field {}, size {}, offset {}{}{}\n",
inst->layername(), inst->id(), sym.mangled(), ts.c_str(),
order, derivSize * int(sym.size()), offset,
sym.interpolated() ? " (interpolated)" : "",
sym.interactive() ? " (interactive)" : "");
sym.dataoffset((int)offset);
// TODO(arenas): sym.set_dataoffset(SymArena::Heap, offset);
offset += derivSize * sym.size();
m_param_order_map[&sym] = order;
++order;
}
}
group().llvm_groupdata_size(offset);
if (llvm_debug() >= 2)
print(" Group struct had {} fields, total size {}\n\n", order, offset);
m_llvm_type_groupdata = ll.type_struct(fields, "Groupdata");
OSL_ASSERT(fields.size() == m_groupdata_field_names.size());
return m_llvm_type_groupdata;
}
llvm::Type*
BackendLLVM::llvm_type_groupdata_ptr()
{
return ll.type_ptr(llvm_type_groupdata());
}
llvm::Type*
BackendLLVM::llvm_type_closure_component()
{
if (m_llvm_type_closure_component)
return m_llvm_type_closure_component;
std::vector<llvm::Type*> comp_types;
comp_types.push_back(ll.type_int()); // id
comp_types.push_back(ll.type_triple()); // w
comp_types.push_back(ll.type_int()); // fake field for char mem[4]
return m_llvm_type_closure_component = ll.type_struct(comp_types,
"ClosureComponent");
}
llvm::Type*
BackendLLVM::llvm_type_closure_component_ptr()
{
return ll.type_ptr(llvm_type_closure_component());
}
void
BackendLLVM::llvm_assign_initial_value(const Symbol& sym, bool force)
{
// Don't write over connections! Connection values are written into
// our layer when the earlier layer is run, as part of its code. So
// we just don't need to initialize it here at all.
if (!force && sym.valuesource() == Symbol::ConnectedVal
&& !sym.typespec().is_closure_based())
return;
// For "globals" that are closures, there is nothing to initialize.
if (sym.typespec().is_closure_based() && sym.symtype() == SymTypeGlobal)
return;
// Closures need to get their storage before anything can be
// assigned to them. Unless they are params, in which case we took
// care of it in the group entry point.
if (sym.typespec().is_closure_based() && sym.symtype() != SymTypeParam
&& sym.symtype() != SymTypeOutputParam) {
llvm_assign_zero(sym);
return;
}
// For local variables (including temps), when "debug_uninit" is enabled,
// we store special values in the variable to make it easier to detect
// uninitialized use.
if ((sym.symtype() == SymTypeLocal || sym.symtype() == SymTypeTemp)
&& shadingsys().debug_uninit()) {
bool isarray = sym.typespec().is_array();
int alen = isarray ? sym.typespec().arraylength() : 1;
llvm::Value* u = NULL;
if (sym.typespec().is_closure_based()) {
// skip closures
} else if (sym.typespec().is_float_based())
u = ll.constant(std::numeric_limits<float>::quiet_NaN());
else if (sym.typespec().is_int_based())
u = ll.constant(std::numeric_limits<int>::min());
else if (sym.typespec().is_string_based())
u = llvm_load_string(Strings::uninitialized_string);
if (u) {
for (int a = 0; a < alen; ++a) {
llvm::Value* aval = isarray ? ll.constant(a) : NULL;
for (int c = 0; c < (int)sym.typespec().aggregate(); ++c)
llvm_store_value(u, sym, 0, aval, c);
}
}
return;
}
// Local/temp strings are always initialized to the empty string.
if ((sym.symtype() == SymTypeLocal || sym.symtype() == SymTypeTemp)
&& sym.typespec().is_string_based()) {
// Strings are pointers. Can't take any chance on leaving
// local/tmp syms uninitialized.
llvm_assign_zero(sym);
return; // we're done, the parts below are just for params
}
// FIXME: Future work -- how expensive would it be to initialize all
// locals to 0? We should test this for performance hit, and if
// reasonable, it may be a good idea to do it by default.
// From here on, everything we are dealing with is a shader parameter
// (either ordinary or output).
OSL_ASSERT_MSG(sym.symtype() == SymTypeParam
|| sym.symtype() == SymTypeOutputParam,
"symtype was %d, data type was %s", (int)sym.symtype(),
sym.typespec().c_str());
// Handle interpolated params by calling osl_bind_interpolated_param,
// which will check if userdata is already retrieved, if not it will
// call RendererServices::get_userdata to retrieve it. In either case,
// it will return 1 if it put the userdata in the right spot (either
// retrieved de novo or copied from a previous retrieval), or 0 if no
// such userdata was available.
llvm::BasicBlock* after_userdata_block = nullptr;
const SymLocationDesc* symloc = nullptr;
if (sym.interpolated() && !sym.typespec().is_closure()) {
ustring symname = sym.name();
TypeDesc type = sym.typespec().simpletype();
int userdata_index = find_userdata_index(sym);
OSL_DASSERT(userdata_index >= 0);
llvm::Value* got_userdata = nullptr;
// See if userdata input placement has been used for this symbol
ustring layersym = ustring::fmtformat("{}.{}", inst()->layername(),
sym.name());
symloc = group().find_symloc(layersym, SymArena::UserData);
if (!symloc)
symloc = group().find_symloc(sym.name(), SymArena::UserData);
if (symloc) {
// We had a userdata pre-placement record for this variable.
// Just copy from the correct offset location!
// Strutil::print("GEN found placeable userdata input {} -> {} {} size={}\n",
// sym.name(), symloc->name, sym.typespec(),
// symloc->type.size());
int size = int(symloc->type.size());
if (symloc->derivs && sym.has_derivs())
size *= 3; // If we're copying the derivs
llvm::Value* srcptr = symloc_ptr(symloc, m_llvm_userdata_base_ptr);
llvm::Value* dstptr = llvm_void_ptr(sym);
ll.op_memcpy(dstptr, srcptr, size);
// Clear derivs if the variable wants derivs but placement
// source didn't have them.
if (sym.has_derivs() && !symloc->derivs)
ll.op_memset(ll.offset_ptr(dstptr, size), 0, 2 * size);
} else {
// No pre-placement: fall back to call to the renderer callback.
llvm::Value* args[] = {
sg_void_ptr(),
llvm_load_string(symname),
ll.constant(type),
ll.constant((int)group().m_userdata_derivs[userdata_index]),
groupdata_field_ptr(2 + userdata_index), // userdata data ptr
ll.constant((int)sym.has_derivs()),
llvm_void_ptr(sym),
ll.constant(sym.derivsize()),
ll.void_ptr(userdata_initialized_ref(userdata_index)),
ll.constant(userdata_index),
};
got_userdata = ll.call_function("osl_bind_interpolated_param",
args);
}
if (shadingsys().debug_nan() && type.basetype == TypeDesc::FLOAT) {
// check for NaN/Inf for float-based types
int ncomps = type.numelements() * type.aggregate;
llvm::Value* args[] = { ll.constant(ncomps),
llvm_void_ptr(sym),
ll.constant((int)sym.has_derivs()),
sg_void_ptr(),
llvm_load_string(inst()->shadername()),
ll.constant(0),
llvm_load_string(sym.unmangled()),
ll.constant(0),
ll.constant(ncomps),
llvm_load_string("<get_userdata>") };
ll.call_function("osl_naninf_check", args);
}
// userdata pre-placement always succeeds, we don't need to bother
// with handing partial results possibly from bind_interpolated_param
if (symloc == nullptr) {
// We will enclose the subsequent initialization of default values
// or init ops in an "if" so that the extra copies or code don't
// happen if the userdata was retrieved.
llvm::BasicBlock* no_userdata_block = ll.new_basic_block(
"no_userdata");
after_userdata_block = ll.new_basic_block();
llvm::Value* cond_val = ll.op_eq(got_userdata, ll.constant(0));
ll.op_branch(cond_val, no_userdata_block, after_userdata_block);
}
}
// Only generate init_ops or default assignment when userdata pre-placement
// is not found
if (symloc == nullptr) {
if (sym.has_init_ops() && sym.valuesource() == Symbol::DefaultVal) {
// Handle init ops.
build_llvm_code(sym.initbegin(), sym.initend());
#if OSL_USE_OPTIX
} else if (use_optix() && !sym.typespec().is_closure()) {
// If the call to osl_bind_interpolated_param returns 0, the default
// value needs to be loaded from a CUDA variable.
llvm::Value* cuda_var = getOrAllocateCUDAVariable(sym);
// memcpy the initial value from the CUDA variable
llvm::Value* src = ll.ptr_cast(ll.GEP(cuda_var, 0),
ll.type_void_ptr());
llvm::Value* dst = llvm_void_ptr(sym);
TypeDesc t = sym.typespec().simpletype();
ll.op_memcpy(dst, src, t.size(), t.basesize());
if (sym.has_derivs())
llvm_zero_derivs(sym);
#endif
} else if (sym.interpolated() && !sym.typespec().is_closure()) {
// geometrically-varying param; memcpy its default value
TypeDesc t = sym.typespec().simpletype();
ll.op_memcpy(llvm_void_ptr(sym), ll.constant_ptr(sym.data()),
t.size(), t.basesize() /*align*/);
if (sym.has_derivs())
llvm_zero_derivs(sym);
} else {
// Use default value
int num_components = sym.typespec().simpletype().aggregate;
TypeSpec elemtype = sym.typespec().elementtype();
int arraylen = std::max(1, sym.typespec().arraylength());
for (int a = 0, c = 0; a < arraylen; ++a) {
llvm::Value* arrind = sym.typespec().is_array() ? ll.constant(a)
: NULL;
if (sym.typespec().is_closure_based())
continue;
for (int i = 0; i < num_components; ++i, ++c) {
// Fill in the constant val
llvm::Value* init_val = 0;
if (elemtype.is_float_based())
init_val = ll.constant(sym.get_float(c));
else if (elemtype.is_string())
init_val = llvm_load_string(sym.get_string(c));
else if (elemtype.is_int())
init_val = ll.constant(sym.get_int(c));
OSL_DASSERT(init_val);
llvm_store_value(init_val, sym, 0, arrind, i);
}
}
if (sym.has_derivs())
llvm_zero_derivs(sym);
}
if (after_userdata_block) {
// If we enclosed the default initialization in an "if", jump to the
// next basic block now.
ll.op_branch(after_userdata_block);
}
}
}
void
BackendLLVM::llvm_generate_debugnan(const Opcode& op)
{
// This function inserts extra debugging code to make sure that this op
// did not produce any NaN values.
// Check each argument to the op...
for (int i = 0; i < op.nargs(); ++i) {
// Only consider the arguments that this op WRITES to
if (!op.argwrite(i))
continue;
Symbol& sym(*opargsym(op, i));
TypeDesc t = sym.typespec().simpletype();
// Only consider floats, because nothing else can be a NaN
if (t.basetype != TypeDesc::FLOAT)
continue;
// Default: Check all elements of the variable being written
llvm::Value* ncomps = ll.constant(int(t.numelements() * t.aggregate));
llvm::Value* offset = ll.constant(0);
llvm::Value* ncheck = ncomps;
// There are a few special cases where an op writes a partial value:
// one element of an array, aggregate (like a point), or matrix. In
// those cases, don't check the other pieces that haven't been
// touched by this op, because (a) it's unnecessary work and code
// generation, and (b) they might generate a false positive error.
// An example would be:
// float A[3]; // 1 Elements could be anything
// A[1] = x; // 2 <-- this is where we are
// Line 2 only wrote element [1], so we do not need to check the
// current values of [0] or [2].
if (op.opname() == op_aassign) {
OSL_DASSERT(i == 0 && "only arg 0 is written for aassign");
llvm::Value* ind = llvm_load_value(*opargsym(op, 1));
llvm::Value* agg = ll.constant(t.aggregate);
offset = t.aggregate == 1 ? ind : ll.op_mul(ind, agg);
ncheck = agg;
} else if (op.opname() == op_compassign) {
OSL_DASSERT(i == 0 && "only arg 0 is written for compassign");
llvm::Value* ind = llvm_load_value(*opargsym(op, 1));
offset = ind;
ncheck = ll.constant(1);
} else if (op.opname() == op_mxcompassign) {
OSL_DASSERT(i == 0 && "only arg 0 is written for mxcompassign");
Symbol& row_sym = *opargsym(op, 1);
Symbol& col_sym = *opargsym(op, 2);
llvm::Value* row_ind = llvm_load_value(row_sym);
llvm::Value* col_ind = llvm_load_value(col_sym);
llvm::Value* comp = ll.op_mul(row_ind, ll.constant(4));
comp = ll.op_add(comp, col_ind);
offset = comp;
ncheck = ll.constant(1);
}
llvm::Value* args[] = { ncomps,
llvm_void_ptr(sym),
ll.constant((int)sym.has_derivs()),
sg_void_ptr(),
ll.constant(op.sourcefile()),
ll.constant(op.sourceline()),
ll.constant(sym.unmangled()),
offset,
ncheck,
ll.constant(op.opname()) };
ll.call_function("osl_naninf_check", args);
}
}
void
BackendLLVM::llvm_generate_debug_uninit(const Opcode& op)
{
// This function inserts extra debugging code to make sure that this op
// did not read an uninitialized value.
if (op.opname() == op_useparam) {
// Don't check the args of a useparam before the op; they are by
// definition potentially not yet set before the useparam action
// itself puts values into them. Checking them for uninitialized
// values will result in false positives.
return;
}
// Check each argument to the op...
for (int i = 0; i < op.nargs(); ++i) {
// Only consider the arguments that this op READS
if (!op.argread(i))
continue;
Symbol& sym(*opargsym(op, i));
// just check float, int, string based types.
if (sym.typespec().is_closure_based())
continue;
TypeDesc t = sym.typespec().simpletype();
if (t.basetype != TypeDesc::FLOAT && t.basetype != TypeDesc::INT
&& t.basetype != TypeDesc::STRING)
continue;
// Some special cases...
if (op.opname() == Strings::op_for && i == 0) {
// The first argument of 'for' is the condition temp, but
// note that it may not have had its initializer run yet, so
// don't generate uninit test code for it.
continue;
}
if (op.opname() == Strings::op_dowhile && i == 0) {
// The first argument of 'dowhile' is the condition temp, but
// most likely its initializer has not run yet. Unless there is
// no "condition" code block, in that case we should still test
// it for uninit.
if (op.jump(0) != op.jump(1))
continue;
}
// Default: Check all elements of the variable being read
llvm::Value* ncheck = ll.constant(int(t.numelements() * t.aggregate));
llvm::Value* offset = ll.constant(0);
// There are a few special cases where an op reads a partial value:
// one element of an array, aggregate (like a point), or matrix. In
// those cases, don't check the other pieces that haven't been
// touched by this op, because (a) it's unnecessary work and code
// generation, and (b) they might generate a false positive error.
// An example would be:
// float A[3]; // 1 Elements are uninitialized
// A[1] = 1; // 2
// float x = A[1]; // 3 <--- this is where we are
// Line 3 only reads element [1]. It is NOT an uninitialized read,
// even though other parts of array A are uninitialized. And even if
// they were initialized, it's unnecessary to check the status of
// the other elements that we didn't just read. Even if [2] is
// uninitialized for the whole shader, that doesn't matter as long
// as we don't try to read it.
if (op.opname() == op_aref && i == 1) {
// Special case -- array assignment -- only check one element
llvm::Value* ind = llvm_load_value(*opargsym(op, 2));
llvm::Value* agg = ll.constant(t.aggregate);
offset = t.aggregate == 1 ? ind : ll.op_mul(ind, agg);
ncheck = agg;
} else if (op.opname() == op_compref && i == 1) {
// Special case -- component assignment -- only check one channel
llvm::Value* ind = llvm_load_value(*opargsym(op, 2));
offset = ind;
ncheck = ll.constant(1);
} else if (op.opname() == op_mxcompref && i == 1) {
// Special case -- matrix component reference -- only check one channel
Symbol& row_sym = *opargsym(op, 2);
Symbol& col_sym = *opargsym(op, 3);
llvm::Value* row_ind = llvm_load_value(row_sym);
llvm::Value* col_ind = llvm_load_value(col_sym);
llvm::Value* comp = ll.op_mul(row_ind, ll.constant(4));
comp = ll.op_add(comp, col_ind);
offset = comp;
ncheck = ll.constant(1);
}
llvm::Value* args[] = { ll.constant(t),
llvm_void_ptr(sym),
sg_void_ptr(),
ll.constant(op.sourcefile()),
ll.constant(op.sourceline()),
ll.constant(group().name()),
ll.constant(layer()),
ll.constant(inst()->layername()),
ll.constant(inst()->shadername().c_str()),
ll.constant(int(&op - &inst()->ops()[0])),
ll.constant(op.opname()),
ll.constant(i),
ll.constant(sym.unmangled()),
offset,
ncheck };
ll.call_function("osl_uninit_check", args);
}
}
void
BackendLLVM::llvm_generate_debug_op_printf(const Opcode& op)
{
std::ostringstream msg;
msg.imbue(std::locale::classic()); // force C locale
msg << op.sourcefile() << ':' << op.sourceline() << ' ' << op.opname();
for (int i = 0; i < op.nargs(); ++i)
msg << ' ' << opargsym(op, i)->mangled();
llvm_gen_debug_printf(msg.str());
}
bool
BackendLLVM::build_llvm_code(int beginop, int endop, llvm::BasicBlock* bb)
{
if (bb)
ll.set_insert_point(bb);
for (int opnum = beginop; opnum < endop; ++opnum) {
const Opcode& op = inst()->ops()[opnum];
const OpDescriptor* opd = shadingsys().op_descriptor(op.opname());
if (opd && opd->llvmgen) {
if (shadingsys().debug_uninit() /* debug uninitialized vals */)
llvm_generate_debug_uninit(op);
if (shadingsys().llvm_debug_ops())
llvm_generate_debug_op_printf(op);
if (ll.debug_is_enabled())
ll.debug_set_location(op.sourcefile(),
std::max(op.sourceline(), 1));
bool ok = (*opd->llvmgen)(*this, opnum);
if (!ok)
return false;
if (shadingsys().debug_nan() /* debug NaN/Inf */
&& op.farthest_jump() < 0 /* Jumping ops don't need it */) {
llvm_generate_debugnan(op);
}
} else if (op.opname() == op_nop || op.opname() == op_end) {
// Skip this op, it does nothing...
} else {
shadingcontext()->errorfmt(
"LLVMOSL: Unsupported op {} in layer {}\n", op.opname(),
inst()->layername());
return false;
}
// If the op we coded jumps around, skip past its recursive block
// executions.
int next = op.farthest_jump();
if (next >= 0)
opnum = next - 1;
}
return true;
}
llvm::Function*
BackendLLVM::build_llvm_init()
{
// Make a group init function: void group_init(ShaderGlobals*, GroupData*)
// Note that the GroupData* is passed as a void*.
std::string unique_name = init_function_name(shadingsys(), group());
ll.current_function(
ll.make_function(unique_name, false,
ll.type_void(), // return type
{
llvm_type_sg_ptr(), llvm_type_groupdata_ptr(),
ll.type_void_ptr(), // userdata_base_ptr
ll.type_void_ptr(), // output_base_ptr
ll.type_int(),
ll.type_void_ptr(), // FIXME: interactive params
}));
if (ll.debug_is_enabled()) {
ustring sourcefile
= group()[0]->op(group()[0]->maincodebegin()).sourcefile();
ll.debug_push_function(unique_name, sourcefile, 0);
}
// Get shader globals and groupdata pointers
m_llvm_shaderglobals_ptr = ll.current_function_arg(0); //arg_it++;
m_llvm_shaderglobals_ptr->setName("shaderglobals_ptr");
m_llvm_groupdata_ptr = ll.current_function_arg(1); //arg_it++;
m_llvm_groupdata_ptr->setName("groupdata_ptr");
m_llvm_userdata_base_ptr = ll.current_function_arg(2); //arg_it++;
m_llvm_userdata_base_ptr->setName("userdata_base_ptr");
m_llvm_output_base_ptr = ll.current_function_arg(3); //arg_it++;
m_llvm_output_base_ptr->setName("output_base_ptr");
m_llvm_shadeindex = ll.current_function_arg(4); //arg_it++;
m_llvm_shadeindex->setName("shadeindex");
m_llvm_interactive_params_ptr = ll.current_function_arg(5); //arg_it++;
m_llvm_interactive_params_ptr->setName("interactive_params_ptr");
// Set up a new IR builder
llvm::BasicBlock* entry_bb = ll.new_basic_block(unique_name);
ll.new_builder(entry_bb);
#if 0 /* helpful for debugging */
if (llvm_debug()) {
llvm_gen_debug_printf (fmtformat("\n\n\n\nGROUP! {}",group().name()));
llvm_gen_debug_printf ("enter group initlayer %d %s %s",
this->layer(), inst()->layername(), inst()->shadername()));
}
#endif
// Group init clears all the "layer_run" and "userdata_initialized" flags.
if (m_num_used_layers > 1) {
int sz = (m_num_used_layers + 3) & (~3); // round up to 32 bits
ll.op_memset(ll.void_ptr(layer_run_ref(0)), 0, sz, 4 /*align*/);
}
int num_userdata = (int)group().m_userdata_names.size();
if (num_userdata) {
int sz = (num_userdata + 3) & (~3); // round up to 32 bits
ll.op_memset(ll.void_ptr(userdata_initialized_ref(0)), 0, sz,
4 /*align*/);
}
// Group init also needs to allot space for ALL layers' params
// that are closures (to avoid weird order of layer eval problems).
for (int i = 0; i < group().nlayers(); ++i) {
ShaderInstance* gi = group()[i];
if (gi->unused() || gi->empty_instance())
continue;
FOREACH_PARAM(Symbol & sym, gi)
{
if (sym.typespec().is_closure_based()) {
int arraylen = std::max(1, sym.typespec().arraylength());
llvm::Value* val = ll.constant_ptr(NULL, ll.type_void_ptr());
for (int a = 0; a < arraylen; ++a) {
llvm::Value* arrind = sym.typespec().is_array()
? ll.constant(a)
: NULL;
llvm_store_value(val, sym, 0, arrind, 0);
}
}
}
}
// All done
#if 0 /* helpful for debugging */
if (llvm_debug())
llvm_gen_debug_printf(fmtformat("exit group init {}", group().name());
#endif
ll.op_return();
if (llvm_debug())
print("group init func ({}) after llvm = {}\n", unique_name,
ll.bitcode_string(ll.current_function()));
if (ll.debug_is_enabled())
ll.debug_pop_function();
ll.end_builder(); // clear the builder
return ll.current_function();
}
llvm::Function* BackendLLVM::build_check_layer_skip_stub()
{
// This just creates a function that returns false
llvm::Function* stub = ll.make_function(
"osl_check_layer_skip_stub",
false,
ll.type_bool(),