/
VectorizeLoops.cpp
1630 lines (1440 loc) · 61.8 KB
/
VectorizeLoops.cpp
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 <utility>
#include "CSE.h"
#include "CodeGen_GPU_Dev.h"
#include "Deinterleave.h"
#include "ExprUsesVar.h"
#include "IREquality.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "IRPrinter.h"
#include "Scope.h"
#include "Simplify.h"
#include "Solve.h"
#include "Substitute.h"
#include "VectorizeLoops.h"
namespace Halide {
namespace Internal {
using std::map;
using std::pair;
using std::string;
using std::vector;
namespace {
Expr get_lane(const Expr &e, int l) {
return Shuffle::make_slice(e, l, 0, 1);
}
/** Find the exact max and min lanes of a vector expression. Not
* conservative like bounds_of_expr, but uses similar rules for some
* common node types where it can be exact. If e is a nested vector,
* the result will be the bounds of the vectors in each lane. */
Interval bounds_of_nested_lanes(const Expr &e) {
if (const Add *add = e.as<Add>()) {
if (const Broadcast *b = add->b.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(add->a);
return {ia.min + b->value, ia.max + b->value};
} else if (const Broadcast *b = add->a.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(add->b);
return {b->value + ia.min, b->value + ia.max};
}
} else if (const Sub *sub = e.as<Sub>()) {
if (const Broadcast *b = sub->b.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(sub->a);
return {ia.min - b->value, ia.max - b->value};
} else if (const Broadcast *b = sub->a.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(sub->b);
return {b->value - ia.max, b->value - ia.max};
}
} else if (const Mul *mul = e.as<Mul>()) {
if (const Broadcast *b = mul->b.as<Broadcast>()) {
if (is_positive_const(b->value)) {
Interval ia = bounds_of_nested_lanes(mul->a);
return {ia.min * b->value, ia.max * b->value};
} else if (is_negative_const(b->value)) {
Interval ia = bounds_of_nested_lanes(mul->a);
return {ia.max * b->value, ia.min * b->value};
}
} else if (const Broadcast *b = mul->a.as<Broadcast>()) {
if (is_positive_const(b->value)) {
Interval ia = bounds_of_nested_lanes(mul->b);
return {b->value * ia.min, b->value * ia.max};
} else if (is_negative_const(b->value)) {
Interval ia = bounds_of_nested_lanes(mul->b);
return {b->value * ia.max, b->value * ia.min};
}
}
} else if (const Div *div = e.as<Div>()) {
if (const Broadcast *b = div->b.as<Broadcast>()) {
if (is_positive_const(b->value)) {
Interval ia = bounds_of_nested_lanes(div->a);
return {ia.min / b->value, ia.max / b->value};
} else if (is_negative_const(b->value)) {
Interval ia = bounds_of_nested_lanes(div->a);
return {ia.max / b->value, ia.min / b->value};
}
}
} else if (const And *and_ = e.as<And>()) {
if (const Broadcast *b = and_->b.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(and_->a);
return {ia.min && b->value, ia.max && b->value};
} else if (const Broadcast *b = and_->a.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(and_->b);
return {ia.min && b->value, ia.max && b->value};
}
} else if (const Or *or_ = e.as<Or>()) {
if (const Broadcast *b = or_->b.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(or_->a);
return {ia.min && b->value, ia.max && b->value};
} else if (const Broadcast *b = or_->a.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(or_->b);
return {ia.min && b->value, ia.max && b->value};
}
} else if (const Min *min = e.as<Min>()) {
if (const Broadcast *b = min->b.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(min->a);
return {Min::make(ia.min, b->value), Min::make(ia.max, b->value)};
} else if (const Broadcast *b = min->a.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(min->b);
return {Min::make(ia.min, b->value), Min::make(ia.max, b->value)};
}
} else if (const Max *max = e.as<Max>()) {
if (const Broadcast *b = max->b.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(max->a);
return {Max::make(ia.min, b->value), Max::make(ia.max, b->value)};
} else if (const Broadcast *b = max->a.as<Broadcast>()) {
Interval ia = bounds_of_nested_lanes(max->b);
return {Max::make(ia.min, b->value), Max::make(ia.max, b->value)};
}
} else if (const Not *not_ = e.as<Not>()) {
Interval ia = bounds_of_nested_lanes(not_->a);
return {!ia.max, !ia.min};
} else if (const Ramp *r = e.as<Ramp>()) {
Expr last_lane_idx = make_const(r->base.type(), r->lanes - 1);
if (is_positive_const(r->stride)) {
return {r->base, r->base + last_lane_idx * r->stride};
} else if (is_negative_const(r->stride)) {
return {r->base + last_lane_idx * r->stride, r->base};
}
} else if (const LE *le = e.as<LE>()) {
// The least true this can be is if we maximize the LHS and minimize the RHS.
// The most true this can be is if we minimize the LHS and maximize the RHS.
// This is only exact if one of the two sides is a Broadcast.
Interval ia = bounds_of_nested_lanes(le->a);
Interval ib = bounds_of_nested_lanes(le->b);
if (ia.is_single_point() || ib.is_single_point()) {
return {ia.max <= ib.min, ia.min <= ib.max};
}
} else if (const LT *lt = e.as<LT>()) {
// The least true this can be is if we maximize the LHS and minimize the RHS.
// The most true this can be is if we minimize the LHS and maximize the RHS.
// This is only exact if one of the two sides is a Broadcast.
Interval ia = bounds_of_nested_lanes(lt->a);
Interval ib = bounds_of_nested_lanes(lt->b);
if (ia.is_single_point() || ib.is_single_point()) {
return {ia.max < ib.min, ia.min < ib.max};
}
} else if (const Broadcast *b = e.as<Broadcast>()) {
return {b->value, b->value};
} else if (const Let *let = e.as<Let>()) {
Interval ia = bounds_of_nested_lanes(let->value);
Interval ib = bounds_of_nested_lanes(let->body);
if (expr_uses_var(ib.min, let->name)) {
ib.min = Let::make(let->name, let->value, ib.min);
}
if (expr_uses_var(ib.max, let->name)) {
ib.max = Let::make(let->name, let->value, ib.max);
}
return ib;
}
// If all else fails, just take the explicit min and max over the
// lanes
if (e.type().is_bool()) {
Expr min_lane = VectorReduce::make(VectorReduce::And, e, 1);
Expr max_lane = VectorReduce::make(VectorReduce::Or, e, 1);
return {min_lane, max_lane};
} else {
Expr min_lane = VectorReduce::make(VectorReduce::Min, e, 1);
Expr max_lane = VectorReduce::make(VectorReduce::Max, e, 1);
return {min_lane, max_lane};
}
};
/** Similar to bounds_of_nested_lanes, but it recursively reduces
* the bounds of nested vectors to scalars. */
Interval bounds_of_lanes(const Expr &e) {
Interval bounds = bounds_of_nested_lanes(e);
if (!bounds.min.type().is_scalar()) {
bounds.min = bounds_of_lanes(bounds.min).min;
}
if (!bounds.max.type().is_scalar()) {
bounds.max = bounds_of_lanes(bounds.max).max;
}
return bounds;
}
// A ramp with the lanes repeated inner_repetitions times, and then
// the whole vector repeated outer_repetitions times.
// E.g: <0 0 2 2 4 4 6 6 0 0 2 2 4 4 6 6>.
struct InterleavedRamp {
Expr base, stride;
int lanes, inner_repetitions, outer_repetitions;
};
bool equal_or_zero(int a, int b) {
return a == 0 || b == 0 || a == b;
}
bool is_interleaved_ramp(const Expr &e, const Scope<Expr> &scope, InterleavedRamp *result) {
if (const Ramp *r = e.as<Ramp>()) {
const Broadcast *b_base = r->base.as<Broadcast>();
const Broadcast *b_stride = r->stride.as<Broadcast>();
if (r->base.type().is_scalar()) {
result->base = r->base;
result->stride = r->stride;
result->lanes = r->lanes;
result->inner_repetitions = 1;
result->outer_repetitions = 1;
return true;
} else if (b_base && b_stride && b_base->lanes == b_stride->lanes) {
// Ramp of broadcast
result->base = b_base->value;
result->stride = b_stride->value;
result->lanes = r->lanes;
result->inner_repetitions = b_base->lanes;
result->outer_repetitions = 1;
return true;
}
} else if (const Broadcast *b = e.as<Broadcast>()) {
if (b->value.type().is_scalar()) {
result->base = b->value;
result->stride = 0;
result->lanes = b->lanes;
result->inner_repetitions = 0;
result->outer_repetitions = 0;
return true;
} else if (is_interleaved_ramp(b->value, scope, result)) {
// Broadcast of interleaved ramp
result->outer_repetitions *= b->lanes;
return true;
}
} else if (const Add *add = e.as<Add>()) {
InterleavedRamp ra;
if (is_interleaved_ramp(add->a, scope, &ra) &&
is_interleaved_ramp(add->b, scope, result) &&
equal_or_zero(ra.inner_repetitions, result->inner_repetitions) &&
equal_or_zero(ra.outer_repetitions, result->outer_repetitions)) {
result->base = simplify(result->base + ra.base);
result->stride = simplify(result->stride + ra.stride);
result->inner_repetitions = std::max(result->inner_repetitions, ra.inner_repetitions);
result->outer_repetitions = std::max(result->outer_repetitions, ra.outer_repetitions);
return true;
}
} else if (const Sub *sub = e.as<Sub>()) {
InterleavedRamp ra;
if (is_interleaved_ramp(sub->a, scope, &ra) &&
is_interleaved_ramp(sub->b, scope, result) &&
equal_or_zero(ra.inner_repetitions, result->inner_repetitions) &&
equal_or_zero(ra.outer_repetitions, result->outer_repetitions)) {
result->base = simplify(ra.base - result->base);
result->stride = simplify(ra.stride - result->stride);
result->inner_repetitions = std::max(result->inner_repetitions, ra.inner_repetitions);
result->outer_repetitions = std::max(result->outer_repetitions, ra.outer_repetitions);
return true;
}
} else if (const Mul *mul = e.as<Mul>()) {
const int64_t *b = nullptr;
if (is_interleaved_ramp(mul->a, scope, result) &&
(b = as_const_int(mul->b))) {
result->base = simplify(result->base * (int)(*b));
result->stride = simplify(result->stride * (int)(*b));
return true;
}
} else if (const Div *div = e.as<Div>()) {
const int64_t *b = nullptr;
if (is_interleaved_ramp(div->a, scope, result) &&
(b = as_const_int(div->b)) &&
is_const_one(result->stride) &&
(result->inner_repetitions == 1 ||
result->inner_repetitions == 0) &&
can_prove((result->base % (int)(*b)) == 0)) {
// TODO: Generalize this. Currently only matches
// ramp(base*b, 1, lanes) / b
// broadcast(base * b, lanes) / b
result->base = simplify(result->base / (int)(*b));
result->inner_repetitions *= (int)(*b);
return true;
}
} else if (const Mod *mod = e.as<Mod>()) {
const int64_t *b = nullptr;
if (is_interleaved_ramp(mod->a, scope, result) &&
(b = as_const_int(mod->b)) &&
(result->outer_repetitions == 1 ||
result->outer_repetitions == 0) &&
can_prove(((int)(*b) % result->stride) == 0)) {
// ramp(base, 2, lanes) % 8
result->base = simplify(result->base % (int)(*b));
result->stride = simplify(result->stride % (int)(*b));
result->outer_repetitions *= (int)(*b);
return true;
}
} else if (const Variable *var = e.as<Variable>()) {
if (scope.contains(var->name)) {
return is_interleaved_ramp(scope.get(var->name), scope, result);
}
}
return false;
}
// Allocations inside vectorized loops grow an additional inner
// dimension to represent the separate copy of the allocation per
// vector lane. This means loads and stores to them need to be
// rewritten slightly.
class RewriteAccessToVectorAlloc : public IRMutator {
Expr var;
string alloc;
int lanes;
using IRMutator::visit;
Expr mutate_index(const string &a, Expr index) {
index = mutate(index);
if (a == alloc) {
return index * lanes + var;
} else {
return index;
}
}
ModulusRemainder mutate_alignment(const string &a, const ModulusRemainder &align) {
if (a == alloc) {
return align * lanes;
} else {
return align;
}
}
Expr visit(const Load *op) override {
return Load::make(op->type, op->name, mutate_index(op->name, op->index),
op->image, op->param, mutate(op->predicate), mutate_alignment(op->name, op->alignment));
}
Stmt visit(const Store *op) override {
return Store::make(op->name, mutate(op->value), mutate_index(op->name, op->index),
op->param, mutate(op->predicate), mutate_alignment(op->name, op->alignment));
}
public:
RewriteAccessToVectorAlloc(const string &v, string a, int l)
: var(Variable::make(Int(32), v)), alloc(std::move(a)), lanes(l) {
}
};
class UsesGPUVars : public IRVisitor {
private:
using IRVisitor::visit;
void visit(const Variable *op) override {
if (CodeGen_GPU_Dev::is_gpu_var(op->name)) {
debug(3) << "Found gpu loop var: " << op->name << "\n";
uses_gpu = true;
}
}
public:
bool uses_gpu = false;
};
bool uses_gpu_vars(const Expr &s) {
UsesGPUVars uses;
s.accept(&uses);
return uses.uses_gpu;
}
class SerializeLoops : public IRMutator {
using IRMutator::visit;
Stmt visit(const For *op) override {
if (op->for_type == ForType::Vectorized) {
return For::make(op->name, op->min, op->extent,
ForType::Serial, op->device_api, mutate(op->body));
}
return IRMutator::visit(op);
}
};
// Wrap a vectorized predicate around a Load/Store node.
class PredicateLoadStore : public IRMutator {
string var;
Expr vector_predicate;
int lanes;
bool valid;
bool vectorized;
using IRMutator::visit;
Expr merge_predicate(Expr pred, const Expr &new_pred) {
if (pred.type().lanes() == new_pred.type().lanes()) {
Expr res = simplify(pred && new_pred);
return res;
}
valid = false;
return pred;
}
Expr visit(const Load *op) override {
valid = valid && ((op->predicate.type().lanes() == lanes) || (op->predicate.type().is_scalar() && !expr_uses_var(op->index, var)));
if (!valid) {
return op;
}
Expr predicate, index;
if (!op->index.type().is_scalar()) {
internal_assert(op->predicate.type().lanes() == lanes);
internal_assert(op->index.type().lanes() == lanes);
predicate = mutate(op->predicate);
index = mutate(op->index);
} else if (expr_uses_var(op->index, var)) {
predicate = mutate(Broadcast::make(op->predicate, lanes));
index = mutate(Broadcast::make(op->index, lanes));
} else {
return IRMutator::visit(op);
}
predicate = merge_predicate(predicate, vector_predicate);
if (!valid) {
return op;
}
vectorized = true;
return Load::make(op->type, op->name, index, op->image, op->param, predicate, op->alignment);
}
Stmt visit(const Store *op) override {
valid = valid && ((op->predicate.type().lanes() == lanes) || (op->predicate.type().is_scalar() && !expr_uses_var(op->index, var)));
if (!valid) {
return op;
}
Expr predicate, value, index;
if (!op->index.type().is_scalar()) {
internal_assert(op->predicate.type().lanes() == lanes);
internal_assert(op->index.type().lanes() == lanes);
internal_assert(op->value.type().lanes() == lanes);
predicate = mutate(op->predicate);
value = mutate(op->value);
index = mutate(op->index);
} else if (expr_uses_var(op->index, var)) {
predicate = mutate(Broadcast::make(op->predicate, lanes));
value = mutate(Broadcast::make(op->value, lanes));
index = mutate(Broadcast::make(op->index, lanes));
} else {
return IRMutator::visit(op);
}
predicate = merge_predicate(predicate, vector_predicate);
if (!valid) {
return op;
}
vectorized = true;
return Store::make(op->name, value, index, op->param, predicate, op->alignment);
}
Expr visit(const Call *op) override {
// We should not vectorize calls with side-effects
valid = valid && op->is_pure();
return IRMutator::visit(op);
}
Expr visit(const VectorReduce *op) override {
// We can't predicate vector reductions.
valid = valid && is_const_one(vector_predicate);
return op;
}
public:
PredicateLoadStore(string v, const Expr &vpred)
: var(std::move(v)), vector_predicate(vpred), lanes(vpred.type().lanes()), valid(true), vectorized(false) {
internal_assert(lanes > 1);
}
bool is_vectorized() const {
return valid && vectorized;
}
};
Stmt vectorize_statement(const Stmt &stmt);
struct VectorizedVar {
string name;
Expr min;
int lanes;
};
// Substitutes a vector for a scalar var in a Stmt. Used on the
// body of every vectorized loop.
class VectorSubs : public IRMutator {
// A list of vectorized loop vars encountered so far. The last
// element corresponds to the most inner vectorized loop.
std::vector<VectorizedVar> vectorized_vars;
// What we're replacing it with. Usually a combination of ramps
// and broadcast. It depends on the current loop level and
// is updated when vectorized_vars list is updated.
std::map<string, Expr> replacements;
// A scope containing lets and letstmts whose values became
// vectors. Contains are original, non-vectorized expressions.
Scope<Expr> scope;
// Based on the same set of Exprs, but indexed by the vectorized
// var name and holding vectorized expression.
Scope<Expr> vector_scope;
// A stack of all containing lets. We need to reinject the scalar
// version of them if we scalarize inner code.
vector<pair<string, Expr>> containing_lets;
// Widen an expression to the given number of lanes.
Expr widen(Expr e, int lanes) {
if (e.type().lanes() == lanes) {
return e;
} else if (lanes % e.type().lanes() == 0) {
return Broadcast::make(e, lanes / e.type().lanes());
} else {
internal_error << "Mismatched vector lanes in VectorSubs " << e.type().lanes()
<< " " << lanes << "\n";
}
return Expr();
}
using IRMutator::visit;
Expr visit(const Cast *op) override {
Expr value = mutate(op->value);
if (value.same_as(op->value)) {
return op;
} else {
Type t = op->type.with_lanes(value.type().lanes());
return Cast::make(t, value);
}
}
string get_widened_var_name(const string &name) {
return name + ".widened." + vectorized_vars.back().name;
}
Expr visit(const Variable *op) override {
if (replacements.count(op->name) > 0) {
return replacements[op->name];
} else if (scope.contains(op->name)) {
string widened_name = get_widened_var_name(op->name);
return Variable::make(vector_scope.get(widened_name).type(), widened_name);
} else {
return op;
}
}
template<typename T>
Expr mutate_binary_operator(const T *op) {
Expr a = mutate(op->a), b = mutate(op->b);
if (a.same_as(op->a) && b.same_as(op->b)) {
return op;
} else {
int w = std::max(a.type().lanes(), b.type().lanes());
return T::make(widen(a, w), widen(b, w));
}
}
Expr visit(const Add *op) override {
return mutate_binary_operator(op);
}
Expr visit(const Sub *op) override {
return mutate_binary_operator(op);
}
Expr visit(const Mul *op) override {
return mutate_binary_operator(op);
}
Expr visit(const Div *op) override {
return mutate_binary_operator(op);
}
Expr visit(const Mod *op) override {
return mutate_binary_operator(op);
}
Expr visit(const Min *op) override {
return mutate_binary_operator(op);
}
Expr visit(const Max *op) override {
return mutate_binary_operator(op);
}
Expr visit(const EQ *op) override {
return mutate_binary_operator(op);
}
Expr visit(const NE *op) override {
return mutate_binary_operator(op);
}
Expr visit(const LT *op) override {
return mutate_binary_operator(op);
}
Expr visit(const LE *op) override {
return mutate_binary_operator(op);
}
Expr visit(const GT *op) override {
return mutate_binary_operator(op);
}
Expr visit(const GE *op) override {
return mutate_binary_operator(op);
}
Expr visit(const And *op) override {
return mutate_binary_operator(op);
}
Expr visit(const Or *op) override {
return mutate_binary_operator(op);
}
Expr visit(const Select *op) override {
Expr condition = mutate(op->condition);
Expr true_value = mutate(op->true_value);
Expr false_value = mutate(op->false_value);
if (condition.same_as(op->condition) &&
true_value.same_as(op->true_value) &&
false_value.same_as(op->false_value)) {
return op;
} else {
int lanes = std::max(true_value.type().lanes(), false_value.type().lanes());
lanes = std::max(lanes, condition.type().lanes());
// Widen the true and false values, but we don't have to widen the condition
true_value = widen(true_value, lanes);
false_value = widen(false_value, lanes);
return Select::make(condition, true_value, false_value);
}
}
Expr visit(const Load *op) override {
Expr predicate = mutate(op->predicate);
Expr index = mutate(op->index);
if (predicate.same_as(op->predicate) && index.same_as(op->index)) {
return op;
} else {
int w = index.type().lanes();
predicate = widen(predicate, w);
return Load::make(op->type.with_lanes(w), op->name, index, op->image,
op->param, predicate, op->alignment);
}
}
Expr visit(const Call *op) override {
// Widen the call by changing the lanes of all of its
// arguments and its return type
// Mutate the args
auto [new_args, changed] = mutate_with_changes(op->args);
int max_lanes = 0;
for (const auto &new_arg : new_args) {
max_lanes = std::max(new_arg.type().lanes(), max_lanes);
}
if (!changed) {
return op;
} else if (op->name == Call::trace) {
const int64_t *event = as_const_int(op->args[6]);
internal_assert(event != nullptr);
if (*event == halide_trace_begin_realization || *event == halide_trace_end_realization) {
// Call::trace vectorizes uniquely for begin/end realization, because the coordinates
// for these are actually min/extent pairs; we need to maintain the proper dimensionality
// count and instead aggregate the widened values into a single pair.
for (size_t i = 1; i <= 2; i++) {
const Call *make_struct = Call::as_intrinsic(new_args[i], {Call::make_struct});
internal_assert(make_struct);
if (i == 1) {
// values should always be empty for these events
internal_assert(make_struct->args.empty());
continue;
}
vector<Expr> call_args(make_struct->args.size());
for (size_t j = 0; j < call_args.size(); j += 2) {
Expr min_v = widen(make_struct->args[j], max_lanes);
Expr extent_v = widen(make_struct->args[j + 1], max_lanes);
Expr min_scalar = get_lane(min_v, 0);
Expr max_scalar = min_scalar + get_lane(extent_v, 0);
for (int k = 1; k < max_lanes; ++k) {
Expr min_k = get_lane(min_v, k);
Expr extent_k = get_lane(extent_v, k);
min_scalar = min(min_scalar, min_k);
max_scalar = max(max_scalar, min_k + extent_k);
}
call_args[j] = min_scalar;
call_args[j + 1] = max_scalar - min_scalar;
}
new_args[i] = Call::make(make_struct->type.element_of(), Call::make_struct, call_args, Call::Intrinsic);
}
} else {
// Call::trace vectorizes uniquely, because we want a
// single trace call for the entire vector, instead of
// scalarizing the call and tracing each element.
for (size_t i = 1; i <= 2; i++) {
// Each struct should be a struct-of-vectors, not a
// vector of distinct structs.
const Call *make_struct = Call::as_intrinsic(new_args[i], {Call::make_struct});
internal_assert(make_struct);
// Widen the call args to have the same lanes as the max lanes found
vector<Expr> call_args(make_struct->args.size());
for (size_t j = 0; j < call_args.size(); j++) {
call_args[j] = widen(make_struct->args[j], max_lanes);
}
new_args[i] = Call::make(make_struct->type.element_of(), Call::make_struct,
call_args, Call::Intrinsic);
}
// One of the arguments to the trace helper
// records the number of vector lanes in the type being
// stored.
new_args[5] = max_lanes;
// One of the arguments to the trace helper
// records the number entries in the coordinates (which we just widened)
if (max_lanes > 1) {
new_args[9] = new_args[9] * max_lanes;
}
}
return Call::make(op->type, Call::trace, new_args, op->call_type);
} else if (op->is_intrinsic(Call::if_then_else) && op->args.size() == 2) {
Expr cond = widen(new_args[0], max_lanes);
Expr true_value = widen(new_args[1], max_lanes);
const Load *load = true_value.as<Load>();
if (load) {
return Load::make(op->type.with_lanes(max_lanes), load->name, load->index, load->image, load->param, cond, load->alignment);
}
}
// Widen the args to have the same lanes as the max lanes found
for (auto &arg : new_args) {
arg = widen(arg, max_lanes);
}
Type new_op_type = op->type.with_lanes(max_lanes);
if (op->is_intrinsic(Call::prefetch)) {
// We don't want prefetch args to ve vectorized, but we can't just skip the mutation
// (otherwise we can end up with dead loop variables. Instead, use extract_lane() on each arg
// to scalarize it again.
for (auto &arg : new_args) {
if (arg.type().is_vector()) {
arg = extract_lane(arg, 0);
}
}
new_op_type = op->type;
}
return Call::make(new_op_type, op->name, new_args,
op->call_type, op->func, op->value_index, op->image, op->param);
}
Expr visit(const Let *op) override {
// Vectorize the let value and check to see if it was vectorized by
// this mutator. The type of the expression might already be vector
// width.
Expr mutated_value = simplify(mutate(op->value));
bool was_vectorized = (!op->value.type().is_vector() &&
mutated_value.type().is_vector());
// If the value was vectorized by this mutator, add a new name to
// the scope for the vectorized value expression.
string vectorized_name;
if (was_vectorized) {
vectorized_name = get_widened_var_name(op->name);
scope.push(op->name, op->value);
vector_scope.push(vectorized_name, mutated_value);
}
Expr mutated_body = mutate(op->body);
InterleavedRamp ir;
if (is_interleaved_ramp(mutated_value, vector_scope, &ir)) {
return substitute(vectorized_name, mutated_value, mutated_body);
} else if (mutated_value.same_as(op->value) &&
mutated_body.same_as(op->body)) {
return op;
} else if (was_vectorized) {
scope.pop(op->name);
vector_scope.pop(vectorized_name);
return Let::make(vectorized_name, mutated_value, mutated_body);
} else {
return Let::make(op->name, mutated_value, mutated_body);
}
}
Stmt visit(const LetStmt *op) override {
Expr mutated_value = simplify(mutate(op->value));
string vectorized_name = op->name;
// Check if the value was vectorized by this mutator.
bool was_vectorized = (!op->value.type().is_vector() &&
mutated_value.type().is_vector());
if (was_vectorized) {
vectorized_name = get_widened_var_name(op->name);
scope.push(op->name, op->value);
vector_scope.push(vectorized_name, mutated_value);
// Also keep track of the original let, in case inner code scalarizes.
containing_lets.emplace_back(op->name, op->value);
}
Stmt mutated_body = mutate(op->body);
if (was_vectorized) {
containing_lets.pop_back();
scope.pop(op->name);
vector_scope.pop(vectorized_name);
}
InterleavedRamp ir;
if (is_interleaved_ramp(mutated_value, vector_scope, &ir)) {
return substitute(vectorized_name, mutated_value, mutated_body);
} else if (mutated_value.same_as(op->value) &&
mutated_body.same_as(op->body)) {
return op;
} else {
return LetStmt::make(vectorized_name, mutated_value, mutated_body);
}
}
Stmt visit(const Provide *op) override {
internal_error << "Vectorizing a Provide node is unimplemented. "
<< "Vectorization usually runs after storage flattening.\n";
return Stmt();
}
Stmt visit(const Store *op) override {
Expr predicate = mutate(op->predicate);
Expr value = mutate(op->value);
Expr index = mutate(op->index);
if (predicate.same_as(op->predicate) && value.same_as(op->value) && index.same_as(op->index)) {
return op;
} else {
int lanes = std::max(predicate.type().lanes(), std::max(value.type().lanes(), index.type().lanes()));
return Store::make(op->name, widen(value, lanes), widen(index, lanes),
op->param, widen(predicate, lanes), op->alignment);
}
}
Stmt visit(const AssertStmt *op) override {
return (op->condition.type().lanes() > 1) ? scalarize(op) : op;
}
Stmt visit(const IfThenElse *op) override {
Expr cond = mutate(op->condition);
int lanes = cond.type().lanes();
debug(3) << "Vectorizing \n"
<< "Old: " << op->condition << "\n"
<< "New: " << cond << "\n";
Stmt then_case = mutate(op->then_case);
Stmt else_case = mutate(op->else_case);
if (lanes > 1) {
// We have an if statement with a vector condition,
// which would mean control flow divergence within the
// SIMD lanes.
bool vectorize_predicate = true;
Stmt predicated_stmt;
if (vectorize_predicate) {
PredicateLoadStore p(vectorized_vars.front().name, cond);
predicated_stmt = p.mutate(then_case);
vectorize_predicate = p.is_vectorized();
}
if (vectorize_predicate && else_case.defined()) {
PredicateLoadStore p(vectorized_vars.front().name, !cond);
predicated_stmt = Block::make(predicated_stmt, p.mutate(else_case));
vectorize_predicate = p.is_vectorized();
}
debug(4) << "IfThenElse should vectorize predicate "
<< "? " << vectorize_predicate << "; cond: " << cond << "\n";
debug(4) << "Predicated stmt:\n"
<< predicated_stmt << "\n";
// First check if the condition is marked as likely.
if (const Call *likely = Call::as_intrinsic(cond, {Call::likely, Call::likely_if_innermost})) {
// The meaning of the likely intrinsic is that
// Halide should optimize for the case in which
// *every* likely value is true. We can do that by
// generating a scalar condition that checks if
// the least-true lane is true.
Expr all_true = bounds_of_lanes(likely->args[0]).min;
// Wrap it in the same flavor of likely
all_true = Call::make(Bool(), likely->name,
{all_true}, Call::PureIntrinsic);
if (!vectorize_predicate) {
// We should strip the likelies from the case
// that's going to scalarize, because it's no
// longer likely.
Stmt without_likelies =
IfThenElse::make(unwrap_tags(op->condition),
op->then_case, op->else_case);
// scalarize() will put back all vectorized loops around the statement as serial,
// but it still may happen that there are vectorized loops inside of the statement
// itself which we may want to handle. All the context is invalid though, so
// we just start anew for this specific statement.
Stmt scalarized = scalarize(without_likelies, false);
scalarized = vectorize_statement(scalarized);
Stmt stmt =
IfThenElse::make(all_true,
then_case,
scalarized);
debug(4) << "...With all_true likely: \n"
<< stmt << "\n";
return stmt;
} else {
Stmt stmt =
IfThenElse::make(all_true,
then_case,
predicated_stmt);
debug(4) << "...Predicated IfThenElse: \n"
<< stmt << "\n";
return stmt;
}
} else {
// It's some arbitrary vector condition.
if (!vectorize_predicate) {
debug(4) << "...Scalarizing vector predicate: \n"
<< Stmt(op) << "\n";
return scalarize(op);
} else {
Stmt stmt = predicated_stmt;
debug(4) << "...Predicated IfThenElse: \n"
<< stmt << "\n";
return stmt;
}
}
} else {
// It's an if statement on a scalar, we're ok to vectorize the innards.
debug(3) << "Not scalarizing if then else\n";
if (cond.same_as(op->condition) &&
then_case.same_as(op->then_case) &&
else_case.same_as(op->else_case)) {
return op;
} else {
return IfThenElse::make(cond, then_case, else_case);
}
}
}
Stmt visit(const For *op) override {
ForType for_type = op->for_type;
Expr min = mutate(op->min);
Expr extent = mutate(op->extent);
Stmt body = op->body;
if (min.type().is_vector()) {
// Rebase the loop to zero and try again
Expr var = Variable::make(Int(32), op->name);
Stmt body = substitute(op->name, var + op->min, op->body);
Stmt transformed = For::make(op->name, 0, op->extent, for_type, op->device_api, body);
return mutate(transformed);
}
if (extent.type().is_vector()) {
// We'll iterate up to the max over the lanes, but
// inject an if statement inside the loop that stops
// each lane from going too far.
extent = bounds_of_lanes(extent).max;
Expr var = Variable::make(Int(32), op->name);
body = IfThenElse::make(likely(var < op->min + op->extent), body);
}
if (op->for_type == ForType::Vectorized) {
const IntImm *extent_int = extent.as<IntImm>();
if (!extent_int || extent_int->value <= 1) {
user_error << "Loop over " << op->name
<< " has extent " << extent
<< ". Can only vectorize loops over a "
<< "constant extent > 1\n";
}
vectorized_vars.push_back({op->name, min, (int)extent_int->value});
update_replacements();
// Go over lets which were vectorized and update them according to the current
// loop level.
for (auto it = scope.cbegin(); it != scope.cend(); ++it) {
string vectorized_name = get_widened_var_name(it.name());
Expr vectorized_value = mutate(it.value());
vector_scope.push(vectorized_name, vectorized_value);
}
body = mutate(body);
// Append vectorized lets for this loop level.
for (auto it = scope.cbegin(); it != scope.cend(); ++it) {
string vectorized_name = get_widened_var_name(it.name());
Expr vectorized_value = vector_scope.get(vectorized_name);
vector_scope.pop(vectorized_name);
InterleavedRamp ir;
if (is_interleaved_ramp(vectorized_value, vector_scope, &ir)) {
body = substitute(vectorized_name, vectorized_value, body);
} else {
body = LetStmt::make(vectorized_name, vectorized_value, body);
}
}
vectorized_vars.pop_back();
update_replacements();
return body;
} else {
body = mutate(body);