-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathFunc.cpp
More file actions
3670 lines (3195 loc) · 133 KB
/
Func.cpp
File metadata and controls
3670 lines (3195 loc) · 133 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
#include <algorithm>
#include <cstring>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#ifdef _MSC_VER
#include <intrin.h>
#endif
#include "ApplySplit.h"
#include "Argument.h"
#include "Associativity.h"
#include "Callable.h"
#include "CodeGen_LLVM.h"
#include "Debug.h"
#include "ExprUsesVar.h"
#include "Func.h"
#include "Function.h"
#include "IR.h"
#include "IREquality.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "IRPrinter.h"
#include "ImageParam.h"
#include "LLVM_Output.h"
#include "Lower.h"
#include "Param.h"
#include "PrintLoopNest.h"
#include "Simplify.h"
#include "Solve.h"
#include "Substitute.h"
#include "Util.h"
namespace Halide {
using std::map;
using std::ofstream;
using std::optional;
using std::pair;
using std::string;
using std::tuple;
using std::unordered_map;
using std::unordered_set;
using std::vector;
using namespace Internal;
namespace {
template<typename DimType>
std::string dump_dim_list(const vector<DimType> &dims) {
std::ostringstream oss;
oss << "Vars:";
for (size_t i = 0; i < dims.size(); i++) {
oss << " " << dims[i].var;
}
oss << "\n";
return oss.str();
}
} // namespace
Func::Func(const string &name)
: func(unique_name(name)) {
}
Func::Func(const Type &required_type, int required_dims, const string &name)
: func({required_type}, required_dims, unique_name(name)) {
}
Func::Func(const std::vector<Type> &required_types, int required_dims, const string &name)
: func(required_types, required_dims, unique_name(name)) {
}
Func::Func()
: func(unique_name('f')) {
}
Func::Func(const Expr &e)
: func(unique_name('f')) {
(*this)(_) = e;
}
Func::Func(Function f)
: func(std::move(f)) {
internal_assert(func.get_contents().defined())
<< "Can't construct Func from undefined Function";
}
const string &Func::name() const {
return func.name();
}
/** Get the pure arguments. */
std::vector<Var> Func::args() const {
const std::vector<std::string> arg_names = func.args();
std::vector<Var> args;
args.reserve(arg_names.size());
for (const auto &arg_name : arg_names) {
args.emplace_back(arg_name);
}
return args;
}
/** The right-hand-side value of the pure definition of this
* function. An error if the Func has no definition, or is defined as
* a Tuple. */
Expr Func::value() const {
user_assert(defined())
<< "Can't call Func::value() on an undefined Func. To check if a Func is defined, call Func::defined()\n";
user_assert(func.outputs() == 1)
<< "Can't call Func::value() on Func \"" << name() << "\", because it has multiple values.\n";
return func.values()[0];
}
/** The values returned by a Func, in Tuple form. */
Tuple Func::values() const {
user_assert(defined())
<< "Can't call Func::values() on an undefined Func. To check if a Func is defined, call Func::defined().\n";
return Tuple(func.values());
}
/** Get the left-hand-side of the update definition. An empty
* vector if there's no update definition. */
const std::vector<Expr> &Func::update_args(int idx) const {
user_assert(has_update_definition())
<< "Can't call Func::update_args() on Func \"" << name()
<< "\" as it has no update definition. "
<< "Use Func::has_update_definition() to check for the existence of an update definition.\n";
user_assert(idx < num_update_definitions())
<< "Update definition index out of bounds.\n";
return func.update(idx).args();
}
/** Get the right-hand-side of the update definition. An error if
* there is no update definition. */
Expr Func::update_value(int idx) const {
user_assert(has_update_definition())
<< "Can't call Func::update_args() on Func \"" << name() << "\" as it has no update definition. "
<< "Use Func::has_update_definition() to check for the existence of an update definition.\n";
user_assert(idx < num_update_definitions())
<< "Update definition index out of bounds.\n";
user_assert(func.update(idx).values().size() == 1)
<< "Can't call Func::update_value() on Func \"" << name() << "\", because it has multiple values.\n";
return func.update(idx).values()[0];
}
/** The update values returned by a Func, in Tuple form. */
Tuple Func::update_values(int idx) const {
user_assert(has_update_definition())
<< "Can't call Func::update_args() on Func \"" << name() << "\" as it has no update definition. "
<< "Use Func::has_update_definition() to check for the existence of an update definition.\n";
user_assert(idx < num_update_definitions())
<< "Update definition index out of bounds.\n";
return Tuple(func.update(idx).values());
}
/** Get the RVars of the reduction domain for the update definition. Returns an
* empty vector if there's no update definition, or if the update definition has
* no domain. Note that the RVars returned are floating RVars, i.e. they don't
* actually have pointer to the reduction domain. */
vector<RVar> Func::rvars(int idx) const {
user_assert(has_update_definition())
<< "Can't call Func::update_args() on Func \"" << name() << "\" as it has no update definition. "
<< "Use Func::has_update_definition() to check for the existence of an update definition.\n";
user_assert(idx < num_update_definitions())
<< "Update definition index out of bounds.\n";
const std::vector<ReductionVariable> rvars = func.update(idx).schedule().rvars();
std::vector<RVar> rvs(rvars.size());
for (size_t i = 0; i < rvars.size(); i++) {
rvs[i] = RVar(rvars[i].var);
}
return rvs;
}
bool Func::defined() const {
return func.has_pure_definition() || func.has_extern_definition();
}
/** Is this function a reduction? */
bool Func::has_update_definition() const {
return func.has_update_definition();
}
/** How many update definitions are there? */
int Func::num_update_definitions() const {
return static_cast<int>(func.updates().size());
}
/** Is this function external? */
bool Func::is_extern() const {
return func.has_extern_definition();
}
/** Add an extern definition for this Func. */
void Func::define_extern(const std::string &function_name,
const std::vector<ExternFuncArgument> &args,
const std::vector<Type> &types,
const std::vector<Var> &arguments,
NameMangling mangling, DeviceAPI device_api) {
func.define_extern(function_name, args, types, arguments, mangling,
device_api);
}
/** Get the types of the buffers returned by an extern definition. */
const Type &Func::type() const {
const auto &types = defined() ? func.output_types() : func.required_types();
if (types.empty()) {
user_error << "Can't call Func::type on Func \"" << name()
<< "\" because it is undefined or has no type requirements.\n";
} else if (types.size() > 1) {
user_error << "Can't call Func::type on Func \"" << name()
<< "\" because it returns a Tuple.\n";
}
return types[0];
}
const std::vector<Type> &Func::types() const {
const auto &types = defined() ? func.output_types() : func.required_types();
user_assert(!types.empty())
<< "Can't call Func::types on Func \"" << name()
<< "\" because it is undefined or has no type requirements.\n";
return types;
}
/** Get the number of outputs this function has. */
int Func::outputs() const {
const auto &types = defined() ? func.output_types() : func.required_types();
user_assert(!types.empty())
<< "Can't call Func::outputs on Func \"" << name()
<< "\" because it is undefined or has no type requirements.\n";
return (int)types.size();
}
/** Get the name of the extern function called for an extern
* definition. */
const std::string &Func::extern_function_name() const {
return func.extern_function_name();
}
int Func::dimensions() const {
const int dims = defined() ? func.dimensions() : func.required_dimensions();
user_assert(dims != AnyDims)
<< "Can't call Func::dimensions on Func \"" << name()
<< "\" because it is undefined or has no dimension requirements.\n";
return dims;
}
FuncRef Func::operator()(vector<Var> args) const {
auto [placeholder_pos, count] = add_implicit_vars(args);
return FuncRef(func, args, placeholder_pos, count);
}
FuncRef Func::operator()(vector<Expr> args) const {
auto [placeholder_pos, count] = add_implicit_vars(args);
return FuncRef(func, args, placeholder_pos, count);
}
std::pair<int, int> Func::add_implicit_vars(vector<Var> &args) const {
int placeholder_pos = -1;
int count = 0;
std::vector<Var>::iterator iter = args.begin();
while (iter != args.end() && !iter->same_as(_)) {
iter++;
}
if (iter != args.end()) {
placeholder_pos = (int)(iter - args.begin());
int i = 0;
iter = args.erase(iter);
// It's important to use func.dimensions() here, *not* this->dimensions(),
// since the latter can return the Func's required dimensions rather than its actual dimensions.
while ((int)args.size() < func.dimensions()) {
debug(2) << "Adding implicit var " << i << " to call to " << name() << "\n";
iter = args.insert(iter, Var::implicit(i++));
iter++;
count++;
}
}
if (defined() && args.size() != (size_t)func.dimensions()) {
user_error << "Func \"" << name() << "\" was called with "
<< args.size() << " arguments, but was defined with " << func.dimensions() << "\n";
}
return {placeholder_pos, count};
}
std::pair<int, int> Func::add_implicit_vars(vector<Expr> &args) const {
int placeholder_pos = -1;
int count = 0;
std::vector<Expr>::iterator iter = args.begin();
while (iter != args.end()) {
const Variable *var = iter->as<Variable>();
if (var && var->name == Var(_).name()) {
break;
}
iter++;
}
if (iter != args.end()) {
placeholder_pos = (int)(iter - args.begin());
int i = 0;
iter = args.erase(iter);
// It's important to use func.dimensions() here, *not* this->dimensions(),
// since the latter can return the Func's required dimensions rather than its actual dimensions.
while ((int)args.size() < func.dimensions()) {
debug(2) << "Adding implicit var " << i << " to call to " << name() << "\n";
iter = args.insert(iter, Var::implicit(i++));
iter++;
count++;
}
}
if (defined() && args.size() != (size_t)func.dimensions()) {
user_error << "Func \"" << name() << "\" was called with "
<< args.size() << " arguments, but was defined with " << func.dimensions() << "\n";
}
return {placeholder_pos, count};
}
namespace {
bool var_name_match(const string &candidate, const string &var) {
internal_assert(var.find('.') == string::npos)
<< "var_name_match expects unqualified names for the second argument. "
<< "Name passed: " << var << "\n";
if (candidate == var) {
return true;
}
return Internal::ends_with(candidate, "." + var);
}
bool dim_match(const Dim &candidate, const VarOrRVar &var) {
if (var_name_match(candidate.var, var.name())) {
user_assert(candidate.is_rvar() == var.is_rvar)
<< (var.is_rvar ? "RVar " : "Var ") << var.name()
<< " used in scheduling directive has the same name as existing "
<< (candidate.is_rvar() ? "RVar " : "Var ") << candidate.var << "\n";
return true;
} else {
return false;
}
}
} // namespace
std::string Stage::name() const {
std::string stage_name = (stage_index == 0) ? function.name() : function.name() + ".update(" + std::to_string(stage_index - 1) + ")";
return stage_name;
}
namespace {
bool is_const_assignment(const string &func_name, const vector<Expr> &args, const vector<Expr> &values) {
// Check if an update definition is a non-recursive and just
// scatters a value that doesn't depend on the reduction
// domain. Such definitions can be treated the same as
// associative/commutative ones. I.e. we can safely split/reorder:
// f(g(r)) = 4;
// More generally, any value that does not recursively load the
// func or use the rvar on the RHS is also fine, because there can
// never be races between two distinct values of the pure var by
// construction (because the pure var must appear as one of the
// args) e.g: f(g(r, x), x) = h(x);
class Checker : public IRVisitor {
using IRVisitor::visit;
void visit(const Variable *op) override {
has_rvar |= op->reduction_domain.defined();
}
void visit(const Call *op) override {
has_self_reference |= (op->call_type == Call::Halide && op->name == func_name);
IRVisitor::visit(op);
}
const string &func_name;
public:
Checker(const string &func_name)
: func_name(func_name) {
}
bool has_self_reference = false;
bool has_rvar = false;
} lhs_checker(func_name), rhs_checker(func_name);
for (const Expr &v : args) {
v.accept(&lhs_checker);
}
for (const Expr &v : values) {
v.accept(&rhs_checker);
}
return !(lhs_checker.has_self_reference ||
rhs_checker.has_self_reference ||
rhs_checker.has_rvar);
}
void check_for_race_conditions_in_split_with_blend(const StageSchedule &sched) {
// Splits with a 'blend' tail strategy do a load and then a store of values
// outside of the region to be computed, so for each split using a 'blend'
// tail strategy, verify that there aren't any parallel vars that stem from
// the same original dimension, so that this load and store doesn't race
// with a true computation of that value happening in some other thread.
// Note that we only need to check vars in the same dimension, because
// allocation bounds inference is done per-dimension and allocates padding
// based on the values actually accessed by the lowered code (i.e. it covers
// the blend region). So for example, an access beyond the end of a scanline
// can't overflow onto the next scanline. Halide will allocate padding, or
// throw a bounds error if it's an input or output.
if (sched.allow_race_conditions()) {
return;
}
std::set<std::string> parallel;
for (const auto &dim : sched.dims()) {
if (is_unordered_parallel(dim.for_type)) {
parallel.insert(dim.var);
}
}
// Process the splits in reverse order to figure out which root vars have a
// parallel child.
for (const auto &split : reverse_view(sched.splits())) {
switch (split.split_type) {
case Split::FuseVars:
if (parallel.count(split.old_var)) {
parallel.insert(split.inner);
parallel.insert(split.old_var);
}
break;
case Split::RenameVar:
if (parallel.count(split.outer)) {
parallel.insert(split.old_var);
}
break;
case Split::SplitVar:
if (parallel.count(split.inner) || parallel.count(split.outer)) {
parallel.insert(split.old_var);
}
break;
}
}
// Now propagate back to all children of the identified root vars, to assert
// that none of them use a blending tail strategy.
for (const auto &split : sched.splits()) {
switch (split.split_type) {
case Split::FuseVars:
if (parallel.count(split.inner) || parallel.count(split.outer)) {
parallel.insert(split.old_var);
}
break;
case Split::RenameVar:
if (parallel.count(split.old_var)) {
parallel.insert(split.outer);
}
break;
case Split::SplitVar:
if (parallel.count(split.old_var)) {
parallel.insert(split.inner);
parallel.insert(split.old_var);
if (split.tail == TailStrategy::ShiftInwardsAndBlend ||
split.tail == TailStrategy::RoundUpAndBlend) {
user_error << "Tail strategy " << split.tail
<< " may not be used to split " << split.old_var
<< " because other vars stemming from the same original "
<< "Var or RVar are marked as parallel."
<< "This could cause a race condition.\n";
}
}
break;
}
}
}
} // namespace
void Stage::set_dim_type(const VarOrRVar &var, ForType t) {
definition.schedule().touched() = true;
bool found = false;
vector<Dim> &dims = definition.schedule().dims();
for (auto &dim : dims) {
if (dim_match(dim, var)) {
found = true;
dim.for_type = t;
// If it's an rvar and the for type is parallel, we need to
// validate that this doesn't introduce a race condition,
// unless it is flagged explicitly or is a associative atomic operation.
if (!dim.is_pure() && var.is_rvar && is_parallel(t)) {
if (!definition.schedule().allow_race_conditions() &&
definition.schedule().atomic()) {
if (!definition.schedule().override_atomic_associativity_test()) {
// We only allow associative atomic operations
const string &func_name = function.name();
vector<Expr> &args = definition.args();
vector<Expr> &values = definition.values();
if (!is_const_assignment(func_name, args, values)) {
// Check whether the operator is associative and determine the operator and
// its identity for each value in the definition if it is a Tuple
const auto &prover_result = prove_associativity(func_name, args, values);
user_assert(prover_result.associative() && prover_result.commutative())
<< "Failed to call atomic() on " << name()
<< " since it can't prove associativity or commutativity of the operator.\n";
internal_assert(prover_result.size() == values.size());
}
}
}
user_assert(definition.schedule().allow_race_conditions() ||
definition.schedule().atomic())
<< "In schedule for " << name()
<< ", marking var " << var.name()
<< " as parallel or vectorized may introduce a race"
<< " condition resulting in incorrect output."
<< " It is possible to parallelize this by using the"
<< " atomic() method if the operation is associative,"
<< " or set override_associativity_test to true in the atomic method"
<< " if you are certain that the operation is associative."
<< " It is also possible to override this error using"
<< " the allow_race_conditions() method. Use allow_race_conditions()"
<< " with great caution, and only when you are willing"
<< " to accept non-deterministic output, or you can prove"
<< " that any race conditions in this code do not change"
<< " the output, or you can prove that there are actually"
<< " no race conditions, and that Halide is being too cautious.\n";
}
}
}
if (!found) {
user_error << "In schedule for " << name()
<< ", could not find dimension "
<< var.name()
<< " to mark as " << t
<< " in vars for function\n"
<< dump_argument_list();
}
if (is_unordered_parallel(t)) {
check_for_race_conditions_in_split_with_blend(definition.schedule());
}
}
void Stage::set_dim_device_api(const VarOrRVar &var, DeviceAPI device_api) {
definition.schedule().touched() = true;
bool found = false;
vector<Dim> &dims = definition.schedule().dims();
for (auto &dim : dims) {
if (dim_match(dim, var)) {
found = true;
dim.device_api = device_api;
}
}
if (!found) {
user_error << "In schedule for " << name()
<< ", could not find dimension "
<< var.name()
<< " to set to device API " << static_cast<int>(device_api)
<< " in vars for function\n"
<< dump_argument_list();
}
}
std::string Stage::dump_argument_list() const {
return dump_dim_list(definition.schedule().dims());
}
namespace {
class SubstituteSelfReference : public IRMutator {
using IRMutator::visit;
const string func;
const Function substitute;
const vector<Var> new_args;
Expr visit(const Call *c) override {
Expr expr = IRMutator::visit(c);
c = expr.as<Call>();
internal_assert(c);
if ((c->call_type == Call::Halide) && (func == c->name)) {
debug(4) << "...Replace call to Func \"" << c->name << "\" with "
<< "\"" << substitute.name() << "\"\n";
vector<Expr> args;
args.insert(args.end(), c->args.begin(), c->args.end());
args.insert(args.end(), new_args.begin(), new_args.end());
expr = Call::make(substitute, args, c->value_index);
}
return expr;
}
public:
SubstituteSelfReference(const string &func, const Function &substitute,
const vector<Var> &new_args)
: func(func), substitute(substitute), new_args(new_args) {
internal_assert(substitute.get_contents().defined());
}
};
/** Substitute all self-reference calls to 'func' with 'substitute' which
* args (LHS) is the old args (LHS) plus 'new_args' in that order.
* Expect this method to be called on the value (RHS) of an update definition. */
vector<Expr> substitute_self_reference(const vector<Expr> &values, const string &func,
const Function &substitute, const vector<Var> &new_args) {
SubstituteSelfReference subs(func, substitute, new_args);
vector<Expr> result;
result.reserve(values.size());
for (const auto &val : values) {
result.push_back(subs(val));
}
return result;
}
} // anonymous namespace
Func Stage::rfactor(const RVar &r, const Var &v) {
definition.schedule().touched() = true;
return rfactor({{r, v}});
}
// Helpers for rfactor implementation
namespace {
optional<Dim> find_dim(const vector<Dim> &items, const VarOrRVar &v) {
const auto has_v = std::find_if(items.begin(), items.end(), [&](auto &x) {
return dim_match(x, v);
});
return has_v == items.end() ? std::nullopt : std::make_optional(*has_v);
}
using SubstitutionMap = std::map<string, Expr>;
/** This is a helper function for building up a substitution map that
* corresponds to pushing down a nest of lets. The lets should be fed
* to this function from innermost to outermost. This is equivalent to
* building a let-nest as a one-hole context and then simplifying.
*
* This looks like it might be quadratic or worse, and technically it is,
* but this isn't a problem for the way it is used inside rfactor. There
* are only a few uses:
*
* 1. Remapping preserved RVars to new RVars
* 2. Remapping factored RVars to new Vars
* 3. Filling the holes in the associative template
* 4. Accumulating the lets from ApplySplit
*
* These are naturally bounded by O(#splits + #dims) which is quite small
* in practice. Classes (1) and (2) cannot blow up expressions since they
* simply rename variables. Class (3) cannot blow up expressions either
* since nothing else can refer to the holes. That leaves only class (1).
* Fortunately, the lets generated by splits are benign. Split factors can't
* refer to RVars, and we won't see the consumed RVars in another split. So
* in total, this avoids any sort of exponentially sized substitution.
*
* @param subst The existing let nest (represented by a SubstitutionMap).
* @param name The name to bind, cannot already exist in the nest.
* @param value The value to bind. Will be substituted into nested values.
*/
void add_let(SubstitutionMap &subst, const string &name, const Expr &value) {
internal_assert(!subst.count(name)) << "would shadow " << name << " in let nest.\n"
<< "\tPresent value: " << subst[name] << "\n"
<< "\tProposed value: " << value;
for (auto &[_, e] : subst) {
e = substitute(name, value, e);
}
subst.emplace(name, value);
}
string dequalify(string name) {
if (const auto it = name.rfind('.'); it != string::npos) {
return name.substr(it + 1);
}
return name;
}
vector<Dim> subst_dims(const SubstitutionMap &substitution_map, const vector<Dim> &dims) {
auto new_dims = dims;
for (auto &dim : new_dims) {
if (const auto it = substitution_map.find(dim.var); it != substitution_map.end()) {
const Variable *new_var = it->second.as<Variable>();
internal_assert(new_var);
dim.var = new_var->name;
}
}
return new_dims;
}
pair<ReductionDomain, SubstitutionMap> project_rdom(const vector<Dim> &dims, const ReductionDomain &rdom, const vector<Split> &splits) {
// The bounds projections maps expressions that reference the old RDom
// bounds to expressions that reference the new RDom bounds (from dims).
// We call this a projection because we are computing the symbolic image
// of the N-dimensional RDom (dimensionality including splits) in the
// M < N - dimensional result.
SubstitutionMap bounds_projection{};
for (const Split &split : reverse_view(splits)) {
for (const auto &[name, value] : compute_loop_bounds_after_split(split, "")) {
add_let(bounds_projection, name, value);
}
}
for (const auto &[var, min, extent] : rdom.domain()) {
add_let(bounds_projection, var + ".loop_min", min);
add_let(bounds_projection, var + ".loop_max", min + extent - 1);
}
// Build the new RDom from the bounds_projection.
vector<ReductionVariable> new_rvars;
for (const Dim &dim : dims) {
const Expr new_min = simplify(bounds_projection.at(dim.var + ".loop_min"));
const Expr new_max = simplify(bounds_projection.at(dim.var + ".loop_max"));
new_rvars.push_back(ReductionVariable{dequalify(dim.var), new_min, (new_max - new_min) + 1});
}
ReductionDomain new_rdom{new_rvars};
new_rdom.where(rdom.predicate());
// Compute a mapping from old dimensions to equivalent values using only
// the new dimensions. For example, if we have an RDom {{0, 20}} and we
// split r.x by 2 into r.xo and r.xi, then this map will contain:
// r.x ~> 2 * r.xo + r.xi
// Certain split tail cases can place additional predicates on the RDom.
// These are handled here, too.
SubstitutionMap dim_projection{};
SubstitutionMap dim_extent_alignment{};
for (const auto &[var, _, extent] : rdom.domain()) {
dim_extent_alignment[var] = extent;
}
for (const Split &split : splits) {
for (const auto &result : apply_split(split, "", dim_extent_alignment)) {
switch (result.type) {
case ApplySplitResult::LetStmt:
add_let(dim_projection, result.name, substitute(bounds_projection, result.value));
break;
case ApplySplitResult::PredicateCalls:
case ApplySplitResult::PredicateProvides:
case ApplySplitResult::Predicate:
new_rdom.where(substitute(bounds_projection, result.value));
break;
case ApplySplitResult::Substitution:
case ApplySplitResult::SubstitutionInCalls:
case ApplySplitResult::SubstitutionInProvides:
case ApplySplitResult::BlendProvides:
// The lets returned by ApplySplit are sufficient
break;
}
}
}
for (size_t i = 0; i < new_rdom.domain().size(); i++) {
add_let(dim_projection, dims[i].var, RVar(new_rdom, i));
}
return {new_rdom, dim_projection};
}
} // namespace
pair<vector<Split>, vector<Split>> Stage::rfactor_validate_args(const std::vector<std::pair<RVar, Var>> &preserved, const AssociativeOp &prover_result) {
const vector<Dim> &dims = definition.schedule().dims();
user_assert(prover_result.associative())
<< "In schedule for " << name() << ": can't perform rfactor() "
<< "because we can't prove associativity of the operator\n"
<< dump_argument_list();
unordered_set<string> is_rfactored;
for (const auto &[rv, v] : preserved) {
// Check that the RVars are in the dims list
const auto &rv_dim = find_dim(dims, rv);
user_assert(rv_dim && rv_dim->is_rvar())
<< "In schedule for " << name() << ": can't perform rfactor() "
<< "on " << rv.name() << " since either it is not in the reduction "
<< "domain, or has already been consumed by another scheduling directive\n"
<< dump_argument_list();
is_rfactored.insert(rv_dim->var);
// Check that the new pure Vars we used to rename the RVar aren't already in the dims list
user_assert(!find_dim(dims, v))
<< "In schedule for " << name() << ": can't perform rfactor() "
<< "on " << rv.name() << " because the name " << v.name()
<< "is already used elsewhere in the Func's schedule.\n"
<< dump_argument_list();
}
// If the operator is associative but non-commutative, rfactor() on inner
// dimensions (excluding the outer dimensions) is not valid.
if (!prover_result.commutative()) {
optional<Dim> last_rvar;
for (const auto &d : reverse_view(dims)) {
bool is_inner = is_rfactored.count(d.var) && last_rvar && !is_rfactored.count(last_rvar->var);
user_assert(!is_inner)
<< "In schedule for " << name() << ": can't rfactor an inner "
<< "dimension " << d.var << " without rfactoring the outer "
<< "dimensions, since the operator is non-commutative.\n"
<< dump_argument_list();
if (d.is_rvar()) {
last_rvar = d;
}
}
}
// Check that no Vars were fused into RVars
vector<Split> var_splits, rvar_splits;
Scope<> rdims;
for (const ReductionVariable &rv : definition.schedule().rvars()) {
rdims.push(rv.var);
}
for (const Split &split : definition.schedule().splits()) {
switch (split.split_type) {
case Split::SplitVar:
if (rdims.contains(split.old_var)) {
rdims.pop(split.old_var);
rdims.push(split.outer);
rdims.push(split.inner);
rvar_splits.emplace_back(split);
} else {
var_splits.emplace_back(split);
}
break;
case Split::FuseVars:
if (rdims.contains(split.outer) || rdims.contains(split.inner)) {
user_assert(rdims.contains(split.outer) && rdims.contains(split.inner))
<< "In schedule for " << name() << ": can't rfactor an Func "
<< "that has fused a Var into an RVar: " << split.outer
<< ", " << split.inner << "\n"
<< dump_argument_list();
rdims.pop(split.outer);
rdims.pop(split.inner);
rdims.push(split.old_var);
rvar_splits.emplace_back(split);
} else {
var_splits.emplace_back(split);
}
break;
case Split::RenameVar:
if (rdims.contains(split.old_var)) {
rdims.pop(split.old_var);
rdims.push(split.outer);
rvar_splits.emplace_back(split);
} else {
var_splits.emplace_back(split);
}
break;
}
}
return std::make_pair(std::move(var_splits), std::move(rvar_splits));
}
Func Stage::rfactor(const vector<pair<RVar, Var>> &preserved) {
user_assert(!definition.is_init()) << "rfactor() must be called on an update definition\n";
definition.schedule().touched() = true;
// Check whether the operator is associative and determine the operator and
// its identity for each value in the definition if it is a Tuple
const auto &prover_result = prove_associativity(function.name(), definition.args(), definition.values());
const auto &[var_splits, rvar_splits] = rfactor_validate_args(preserved, prover_result);
const vector<Expr> dim_vars_exprs = [&] {
vector<Expr> result;
result.insert(result.end(), dim_vars.begin(), dim_vars.end());
return result;
}();
// sort preserved by the dimension ordering
vector<RVar> preserved_rvars;
vector<Var> preserved_vars;
vector<Dim> preserved_rdims;
unordered_set<string> preserved_rdims_set;
vector<Dim> intermediate_rdims;
{
unordered_map<string, int> dim_ordering;
for (size_t i = 0; i < definition.schedule().dims().size(); i++) {
dim_ordering.emplace(definition.schedule().dims()[i].var, i);
}
vector<tuple<RVar, Var, Dim>> preserved_with_dims;
for (const auto &[rv, v] : preserved) {
const optional<Dim> rdim = find_dim(definition.schedule().dims(), rv);
internal_assert(rdim);
preserved_with_dims.emplace_back(rv, v, *rdim);
}
std::sort(preserved_with_dims.begin(), preserved_with_dims.end(), [&](const auto &lhs, const auto &rhs) {
return dim_ordering.at(std::get<2>(lhs).var) < dim_ordering.at(std::get<2>(rhs).var);
});
for (const auto &[rv, v, dim] : preserved_with_dims) {
preserved_rvars.push_back(rv);
preserved_vars.push_back(v);
preserved_rdims.push_back(dim);
preserved_rdims_set.insert(dim.var);
}
for (const Dim &dim : definition.schedule().dims()) {
if (dim.is_rvar() && !preserved_rdims_set.count(dim.var)) {
intermediate_rdims.push_back(dim);
}
}
}
ReductionDomain rdom{definition.schedule().rvars(), definition.predicate(), true};
SubstitutionMap rdom_promises;
for (int i = 0; i < (int)rdom.domain().size(); i++) {
const auto &[var, min, extent] = rdom.domain()[i];
rdom_promises.emplace(var, promise_clamped(RVar(rdom, i), min, min + extent - 1));
}
// Project the RDom into each side
ReductionDomain intermediate_rdom, preserved_rdom;
SubstitutionMap intermediate_map, preserved_map;
{
// Intermediate
std::tie(intermediate_rdom, intermediate_map) = project_rdom(intermediate_rdims, rdom, rvar_splits);
for (size_t i = 0; i < preserved.size(); i++) {
add_let(intermediate_map, preserved_rdims[i].var, preserved_vars[i]);
}
{
Expr pred = intermediate_rdom.predicate();
pred = substitute(rdom_promises, pred);
pred = substitute(intermediate_map, pred);
intermediate_rdom.set_predicate(simplify(pred));
}
// Preserved
std::tie(preserved_rdom, preserved_map) = project_rdom(preserved_rdims, rdom, rvar_splits);
Scope<Interval> intm_rdom;
for (size_t i = 0; i < intermediate_rdom.domain().size(); i++) {
const auto &var = intermediate_rdims[i].var;
const auto &[_, min, extent] = intermediate_rdom.domain()[i];
intm_rdom.push(var, Interval{min, min + extent - 1});
}
{
Expr pred = preserved_rdom.predicate();
pred = substitute(rdom_promises, pred);
pred = substitute(preserved_map, pred);
pred = or_condition_over_domain(pred, intm_rdom);
preserved_rdom.set_predicate(pred);
}
}
// Intermediate func
Func intm(function.name() + "_intm");
// Intermediate pure definition
{
vector<Expr> args = dim_vars_exprs;
args.insert(args.end(), preserved_vars.begin(), preserved_vars.end());
intm(args) = Tuple(prover_result.pattern.identities);
}
// Intermediate update definition
{
vector<Expr> args = definition.args();
args.insert(args.end(), preserved_vars.begin(), preserved_vars.end());
args = substitute(rdom_promises, args);
args = substitute(intermediate_map, args);
vector<Expr> values = definition.values();
values = substitute_self_reference(values, function.name(), intm.function(), preserved_vars);
values = substitute(rdom_promises, values);
values = substitute(intermediate_map, values);
intm.function().define_update(args, values, intermediate_rdom);
// Intermediate schedule
vector<Dim> intm_dims = definition.schedule().dims();
// Replace rvar dims IN the preserved list with their Vars in the INTERMEDIATE Func
for (auto &dim : intm_dims) {
const auto it = std::find_if(preserved_rvars.begin(), preserved_rvars.end(), [&](const auto &rv) {
return dim_match(dim, rv);
});
if (it != preserved_rvars.end()) {
const auto offset = it - preserved_rvars.begin();
const auto &var = preserved_vars[offset];
const auto &pure_dim = find_dim(intm.function().definition().schedule().dims(), var);
internal_assert(pure_dim);
dim = *pure_dim;
}
}
// Add factored pure dims to the INTERMEDIATE func just before outermost
unordered_set<string> dims;
for (const auto &dim : intm_dims) {
dims.insert(dim.var);
}
for (const Var &var : preserved_vars) {
const optional<Dim> &dim = find_dim(intm.function().definition().schedule().dims(), var);
internal_assert(dim) << "Failed to find " << var.name() << " in list of pure dims";
if (!dims.count(dim->var)) {
intm_dims.insert(intm_dims.end() - 1, *dim);