-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathIROperator.cpp
2758 lines (2399 loc) · 93.1 KB
/
IROperator.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 <atomic>
#include <cmath>
#include <iostream>
#include <sstream>
#include <utility>
#include "CSE.h"
#include "ConstantBounds.h"
#include "Debug.h"
#include "Func.h"
#include "IREquality.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "IRPrinter.h"
#include "Interval.h"
#include "Util.h"
#include "Var.h"
using namespace Halide::Internal;
namespace Halide {
// Evaluate a float polynomial efficiently, taking instruction latency
// into account. The high order terms come first. n is the number of
// terms, which is the degree plus one.
namespace {
Expr evaluate_polynomial(Expr x, float *coeff, int n) {
internal_assert(n >= 2);
Expr x2 = x * x;
Expr even_terms = coeff[0];
Expr odd_terms = coeff[1];
for (int i = 2; i < n; i++) {
if ((i & 1) == 0) {
if (coeff[i] == 0.0f) {
even_terms *= x2;
} else {
even_terms = even_terms * x2 + coeff[i];
}
} else {
if (coeff[i] == 0.0f) {
odd_terms *= x2;
} else {
odd_terms = odd_terms * x2 + coeff[i];
}
}
}
if ((n & 1) == 0) {
return even_terms * std::move(x) + odd_terms;
} else {
return odd_terms * std::move(x) + even_terms;
}
}
Expr stringify(const std::vector<Expr> &args) {
if (args.empty()) {
return Expr("");
}
return Call::make(type_of<const char *>(), Call::stringify,
args, Call::PureIntrinsic);
}
Expr combine_strings(const std::vector<Expr> &args) {
if (args.empty()) {
return Expr("");
}
// Insert spaces between each expr.
std::vector<Expr> strings(args.size() * 2);
for (size_t i = 0; i < args.size(); i++) {
strings[i * 2] = args[i];
if (i < args.size() - 1) {
strings[i * 2 + 1] = Expr(" ");
} else {
strings[i * 2 + 1] = Expr("\n");
}
}
// Now combine all adjacent string literals, which is
// useful to reduce emitted code size when printing
size_t i = 0;
while (i < strings.size() - 1) {
const auto *cur_str = strings[i].as<StringImm>();
const auto *next_str = strings[i + 1].as<StringImm>();
if (cur_str && next_str) {
strings[i] = StringImm::make(cur_str->value + next_str->value);
strings.erase(strings.begin() + i + 1);
continue;
}
i++;
}
return stringify(strings);
}
} // namespace
namespace Internal {
bool is_const(const Expr &e) {
if (e.as<IntImm>() ||
e.as<UIntImm>() ||
e.as<FloatImm>() ||
e.as<StringImm>()) {
return true;
} else if (const Cast *c = e.as<Cast>()) {
return is_const(c->value);
} else if (const Ramp *r = e.as<Ramp>()) {
return is_const(r->base) && is_const(r->stride);
} else if (const Broadcast *b = e.as<Broadcast>()) {
return is_const(b->value);
} else {
return false;
}
}
bool is_const(const Expr &e, int64_t value) {
if (const IntImm *i = e.as<IntImm>()) {
return i->value == value;
} else if (const UIntImm *i = e.as<UIntImm>()) {
return (value >= 0) && (i->value == (uint64_t)value);
} else if (const FloatImm *i = e.as<FloatImm>()) {
return i->value == value;
} else if (const Cast *c = e.as<Cast>()) {
return is_const(c->value, value);
} else if (const Broadcast *b = e.as<Broadcast>()) {
return is_const(b->value, value);
} else {
return false;
}
}
bool is_no_op(const Stmt &s) {
if (!s.defined()) {
return true;
}
const Evaluate *e = s.as<Evaluate>();
return e && is_pure(e->value);
}
namespace {
class ExprIsPure : public IRGraphVisitor {
using IRVisitor::visit;
void visit(const Call *op) override {
if (!op->is_pure()) {
result = false;
} else {
IRGraphVisitor::visit(op);
}
}
void visit(const Load *op) override {
if (!op->image.defined() && !op->param.defined()) {
// It's a load from an internal buffer, which could
// mutate.
result = false;
} else {
IRGraphVisitor::visit(op);
}
}
public:
bool result = true;
};
} // namespace
bool is_pure(const Expr &e) {
ExprIsPure pure;
e.accept(&pure);
return pure.result;
}
const int64_t *as_const_int(const Expr &e) {
if (!e.defined()) {
return nullptr;
} else if (const Broadcast *b = e.as<Broadcast>()) {
return as_const_int(b->value);
} else if (const IntImm *i = e.as<IntImm>()) {
return &(i->value);
} else {
return nullptr;
}
}
const uint64_t *as_const_uint(const Expr &e) {
if (!e.defined()) {
return nullptr;
} else if (const Broadcast *b = e.as<Broadcast>()) {
return as_const_uint(b->value);
} else if (const UIntImm *i = e.as<UIntImm>()) {
return &(i->value);
} else {
return nullptr;
}
}
const double *as_const_float(const Expr &e) {
if (!e.defined()) {
return nullptr;
} else if (const Broadcast *b = e.as<Broadcast>()) {
return as_const_float(b->value);
} else if (const FloatImm *f = e.as<FloatImm>()) {
return &(f->value);
} else {
return nullptr;
}
}
bool is_const_power_of_two_integer(const Expr &e, int *bits) {
if (!(e.type().is_int() || e.type().is_uint())) {
return false;
}
const Broadcast *b = e.as<Broadcast>();
if (b) {
return is_const_power_of_two_integer(b->value, bits);
}
const Cast *c = e.as<Cast>();
if (c) {
return is_const_power_of_two_integer(c->value, bits);
}
uint64_t val = 0;
if (const int64_t *i = as_const_int(e)) {
if (*i < 0) {
return false;
}
val = (uint64_t)(*i);
} else if (const uint64_t *u = as_const_uint(e)) {
val = *u;
}
if (val && ((val & (val - 1)) == 0)) {
*bits = 0;
for (; val; val >>= 1) {
if (val == 1) {
return true;
}
(*bits)++;
}
}
return false;
}
bool is_positive_const(const Expr &e) {
if (const IntImm *i = e.as<IntImm>()) {
return i->value > 0;
}
if (const UIntImm *u = e.as<UIntImm>()) {
return u->value > 0;
}
if (const FloatImm *f = e.as<FloatImm>()) {
return f->value > 0.0f;
}
if (const Cast *c = e.as<Cast>()) {
Type to = c->type;
Type from = c->value.type();
if (!to.is_int_or_uint() || to.can_represent(from)) {
// Either the cast does not lose information, or it's a
// non-integral cast, so no overflow behavior to worry about.
return is_positive_const(c->value);
}
}
if (const Ramp *r = e.as<Ramp>()) {
// slightly conservative
return is_positive_const(r->base) && is_positive_const(r->stride);
}
if (const Broadcast *b = e.as<Broadcast>()) {
return is_positive_const(b->value);
}
return false;
}
bool is_negative_const(const Expr &e) {
if (const IntImm *i = e.as<IntImm>()) {
return i->value < 0;
}
if (const FloatImm *f = e.as<FloatImm>()) {
return f->value < 0.0f;
}
if (const Cast *c = e.as<Cast>()) {
Type to = c->type;
Type from = c->value.type();
if (to.is_uint()) {
// Early out.
return false;
}
if (!to.is_int_or_uint() || to.can_represent(from)) {
// Either the cast does not lose information, or it's a
// non-integral cast, so no overflow behavior to worry about.
return is_negative_const(c->value);
}
}
if (const Ramp *r = e.as<Ramp>()) {
// slightly conservative
return is_negative_const(r->base) && is_negative_const(r->stride);
}
if (const Broadcast *b = e.as<Broadcast>()) {
return is_negative_const(b->value);
}
return false;
}
bool is_undef(const Expr &e) {
if (const Call *c = e.as<Call>()) {
return c->is_intrinsic(Call::undef);
}
return false;
}
bool is_const_zero(const Expr &e) {
if (const IntImm *int_imm = e.as<IntImm>()) {
return int_imm->value == 0;
}
if (const UIntImm *uint_imm = e.as<UIntImm>()) {
return uint_imm->value == 0;
}
if (const FloatImm *float_imm = e.as<FloatImm>()) {
return float_imm->value == 0.0;
}
if (const Cast *c = e.as<Cast>()) {
return is_const_zero(c->value);
}
if (const Broadcast *b = e.as<Broadcast>()) {
return is_const_zero(b->value);
}
if (const Call *c = e.as<Call>()) {
return (c->is_intrinsic(Call::bool_to_mask) || c->is_intrinsic(Call::cast_mask)) &&
is_const_zero(c->args[0]);
}
return false;
}
bool is_const_one(const Expr &e) {
if (const IntImm *int_imm = e.as<IntImm>()) {
return int_imm->value == 1;
}
if (const UIntImm *uint_imm = e.as<UIntImm>()) {
return uint_imm->value == 1;
}
if (const FloatImm *float_imm = e.as<FloatImm>()) {
return float_imm->value == 1.0;
}
if (const Cast *c = e.as<Cast>()) {
return is_const_one(c->value);
}
if (const Broadcast *b = e.as<Broadcast>()) {
return is_const_one(b->value);
}
if (const Call *c = e.as<Call>()) {
return (c->is_intrinsic(Call::bool_to_mask) || c->is_intrinsic(Call::cast_mask)) &&
is_const_one(c->args[0]);
}
return false;
}
namespace {
template<typename T>
Expr make_const_helper(Type t, T val) {
if (t.is_vector()) {
return Broadcast::make(make_const(t.element_of(), val), t.lanes());
} else if (t.is_int()) {
return IntImm::make(t, (int64_t)val);
} else if (t.is_uint()) {
return UIntImm::make(t, (uint64_t)val);
} else if (t.is_float()) {
return FloatImm::make(t, (double)val);
} else {
internal_error << "Can't make a constant of type " << t << "\n";
return Expr();
}
}
} // namespace
Expr make_const(Type t, int64_t val) {
return make_const_helper(t, val);
}
Expr make_const(Type t, uint64_t val) {
return make_const_helper(t, val);
}
Expr make_const(Type t, double val) {
return make_const_helper(t, val);
}
Expr make_bool(bool val, int w) {
return make_const(UInt(1, w), val);
}
Expr make_zero(Type t) {
if (t.is_handle()) {
return reinterpret(t, make_zero(UInt(64)));
} else {
return make_const(t, 0);
}
}
Expr make_one(Type t) {
return make_const(t, 1);
}
Expr make_two(Type t) {
return make_const(t, 2);
}
Expr make_signed_integer_overflow(Type type) {
static std::atomic<int> counter{0};
return Call::make(type, Call::signed_integer_overflow, {counter++}, Call::Intrinsic);
}
bool is_signed_integer_overflow(const Expr &expr) {
const Call *call = expr.as<Call>();
return call && call->is_intrinsic(Call::signed_integer_overflow);
}
Expr const_true(int w) {
return make_one(UInt(1, w));
}
Expr const_false(int w) {
return make_zero(UInt(1, w));
}
Expr lossless_cast(Type t, Expr e, std::map<Expr, ConstantInterval, ExprCompare> *cache) {
if (!e.defined() || t == e.type()) {
return e;
} else if (t.can_represent(e.type())) {
return cast(t, std::move(e));
} else if (const Cast *c = e.as<Cast>()) {
if (c->type.can_represent(c->value.type())) {
return lossless_cast(t, c->value, cache);
}
} else if (const Broadcast *b = e.as<Broadcast>()) {
Expr v = lossless_cast(t.element_of(), b->value, cache);
if (v.defined()) {
return Broadcast::make(v, b->lanes);
}
} else if (const IntImm *i = e.as<IntImm>()) {
if (t.can_represent(i->value)) {
return make_const(t, i->value);
}
} else if (const UIntImm *i = e.as<UIntImm>()) {
if (t.can_represent(i->value)) {
return make_const(t, i->value);
}
} else if (const FloatImm *f = e.as<FloatImm>()) {
if (t.can_represent(f->value)) {
return make_const(t, f->value);
}
} else if (const Shuffle *shuf = e.as<Shuffle>()) {
std::vector<Expr> vecs;
for (const auto &vec : shuf->vectors) {
vecs.emplace_back(lossless_cast(t.with_lanes(vec.type().lanes()), vec, cache));
if (!vecs.back().defined()) {
return Expr();
}
}
return Shuffle::make(vecs, shuf->indices);
} else if (t.is_int_or_uint()) {
// Check the bounds. If they're small enough, we can throw narrowing
// casts around e, or subterms.
ConstantInterval ci = constant_integer_bounds(e, Scope<ConstantInterval>::empty_scope(), cache);
if (t.can_represent(ci)) {
// There are certain IR nodes where if the result is expressible
// using some type, and the args are expressible using that type,
// then the operation can just be done in that type.
if (const Add *op = e.as<Add>()) {
Expr a = lossless_cast(t, op->a, cache);
Expr b = lossless_cast(t, op->b, cache);
if (a.defined() && b.defined()) {
return Add::make(a, b);
}
} else if (const Sub *op = e.as<Sub>()) {
Expr a = lossless_cast(t, op->a, cache);
Expr b = lossless_cast(t, op->b, cache);
if (a.defined() && b.defined()) {
return Sub::make(a, b);
}
} else if (const Mul *op = e.as<Mul>()) {
Expr a = lossless_cast(t, op->a, cache);
Expr b = lossless_cast(t, op->b, cache);
if (a.defined() && b.defined()) {
return Mul::make(a, b);
}
} else if (const Min *op = e.as<Min>()) {
Expr a = lossless_cast(t, op->a, cache);
Expr b = lossless_cast(t, op->b, cache);
if (a.defined() && b.defined()) {
debug(0) << a << " " << b << "\n";
return Min::make(a, b);
}
} else if (const Max *op = e.as<Max>()) {
Expr a = lossless_cast(t, op->a, cache);
Expr b = lossless_cast(t, op->b, cache);
if (a.defined() && b.defined()) {
return Max::make(a, b);
}
} else if (const Mod *op = e.as<Mod>()) {
Expr a = lossless_cast(t, op->a, cache);
Expr b = lossless_cast(t, op->b, cache);
if (a.defined() && b.defined()) {
return Mod::make(a, b);
}
} else if (const Call *op = Call::as_intrinsic(e, {Call::widening_add, Call::widen_right_add})) {
Expr a = lossless_cast(t, op->args[0], cache);
Expr b = lossless_cast(t, op->args[1], cache);
if (a.defined() && b.defined()) {
return Add::make(a, b);
}
} else if (const Call *op = Call::as_intrinsic(e, {Call::widening_sub, Call::widen_right_sub})) {
Expr a = lossless_cast(t, op->args[0], cache);
Expr b = lossless_cast(t, op->args[1], cache);
if (a.defined() && b.defined()) {
return Sub::make(a, b);
}
} else if (const Call *op = Call::as_intrinsic(e, {Call::widening_mul, Call::widen_right_mul})) {
Expr a = lossless_cast(t, op->args[0], cache);
Expr b = lossless_cast(t, op->args[1], cache);
if (a.defined() && b.defined()) {
return Mul::make(a, b);
}
} else if (const Call *op = Call::as_intrinsic(e, {Call::shift_left, Call::widening_shift_left,
Call::shift_right, Call::widening_shift_right})) {
Expr a = lossless_cast(t, op->args[0], cache);
Expr b = lossless_cast(t, op->args[1], cache);
if (a.defined() && b.defined()) {
ConstantInterval cb = constant_integer_bounds(b, Scope<ConstantInterval>::empty_scope(), cache);
if (cb > -t.bits() && cb < t.bits()) {
if (op->is_intrinsic({Call::shift_left, Call::widening_shift_left})) {
return a << b;
} else if (op->is_intrinsic({Call::shift_right, Call::widening_shift_right})) {
return a >> b;
}
}
}
} else if (const VectorReduce *op = e.as<VectorReduce>()) {
if (op->op == VectorReduce::Add ||
op->op == VectorReduce::Min ||
op->op == VectorReduce::Max) {
Expr v = lossless_cast(t.with_lanes(op->value.type().lanes()), op->value, cache);
if (v.defined()) {
return VectorReduce::make(op->op, v, op->type.lanes());
}
}
}
// At this point we know the expression fits in the target type, but
// what we really want is for the expression to be computed in the
// target type. So we can add a cast to the target type if we want
// here, but it only makes sense to do it if the expression type has
// the same or fewer bits than the target type.
if (e.type().bits() <= t.bits()) {
return cast(t, e);
}
}
}
return Expr();
}
Expr lossless_negate(const Expr &x) {
if (const Mul *m = x.as<Mul>()) {
// Check the terms can't multiply to produce the most negative value.
if (x.type().is_int() &&
!x.type().can_represent(-constant_integer_bounds(x))) {
return Expr();
}
Expr b = lossless_negate(m->b);
if (b.defined()) {
return Mul::make(m->a, b);
}
Expr a = lossless_negate(m->a);
if (a.defined()) {
return Mul::make(a, m->b);
}
} else if (const Call *m = Call::as_intrinsic(x, {Call::widening_mul})) {
Expr b = lossless_negate(m->args[1]);
if (b.defined()) {
return widening_mul(m->args[0], b);
}
Expr a = lossless_negate(m->args[0]);
if (a.defined()) {
return widening_mul(a, m->args[1]);
}
} else if (const IntImm *i = x.as<IntImm>()) {
if (!i->type.is_min(i->value)) {
return IntImm::make(i->type, -i->value);
}
} else if (const FloatImm *f = x.as<FloatImm>()) {
return FloatImm::make(f->type, -f->value);
} else if (const Cast *c = x.as<Cast>()) {
Expr value = lossless_negate(c->value);
if (value.defined()) {
// This logic is only sound if we know the cast can't overflow.
value = lossless_cast(c->type, value);
if (value.defined()) {
return value;
}
}
} else if (const Ramp *r = x.as<Ramp>()) {
Expr base = lossless_negate(r->base);
Expr stride = lossless_negate(r->stride);
// slightly conservative
if (base.defined() && stride.defined()) {
return Ramp::make(base, stride, r->lanes);
}
} else if (const Broadcast *b = x.as<Broadcast>()) {
Expr value = lossless_negate(b->value);
if (value.defined()) {
return Broadcast::make(value, b->lanes);
}
}
return Expr();
}
void check_representable(Type dst, int64_t x) {
if (dst.is_handle()) {
user_assert(dst.can_represent(x))
<< "Integer constant " << x
<< " will be implicitly coerced to type " << dst
<< ", but Halide does not support pointer arithmetic.\n";
} else {
user_assert(dst.can_represent(x))
<< "Integer constant " << x
<< " will be implicitly coerced to type " << dst
<< ", which changes its value to " << make_const(dst, x)
<< ".\n";
}
}
void match_lanes(Expr &a, Expr &b) {
// Broadcast scalar to match vector
if (a.type().is_scalar() && b.type().is_vector()) {
a = Broadcast::make(std::move(a), b.type().lanes());
} else if (a.type().is_vector() && b.type().is_scalar()) {
b = Broadcast::make(std::move(b), a.type().lanes());
} else {
internal_assert(a.type().lanes() == b.type().lanes()) << "Can't match types of differing widths";
}
}
void match_types(Expr &a, Expr &b) {
if (a.type() == b.type()) {
return;
}
user_assert(!a.type().is_handle() && !b.type().is_handle())
<< "Can't do arithmetic on opaque pointer types: "
<< a << ", " << b << "\n";
match_lanes(a, b);
Type ta = a.type(), tb = b.type();
// If type broadcasting has made the types match no additional casts are needed
if (ta == tb) {
return;
}
if (!ta.is_float() && tb.is_float()) {
// int(a) * float(b) -> float(b)
// uint(a) * float(b) -> float(b)
a = cast(tb, std::move(a));
} else if (ta.is_float() && !tb.is_float()) {
b = cast(ta, std::move(b));
} else if (ta.is_float() && tb.is_float()) {
// float(a) * float(b) -> float(max(a, b))
if (ta.bits() > tb.bits()) {
b = cast(ta, std::move(b));
} else {
a = cast(tb, std::move(a));
}
} else if (ta.is_uint() && tb.is_uint()) {
// uint(a) * uint(b) -> uint(max(a, b))
if (ta.bits() > tb.bits()) {
b = cast(ta, std::move(b));
} else {
a = cast(tb, std::move(a));
}
} else if (!ta.is_float() && !tb.is_float()) {
// int(a) * (u)int(b) -> int(max(a, b))
int bits = std::max(ta.bits(), tb.bits());
int lanes = a.type().lanes();
a = cast(Int(bits, lanes), std::move(a));
b = cast(Int(bits, lanes), std::move(b));
} else {
internal_error << "Could not match types: " << ta << ", " << tb << "\n";
}
}
// Cast to the wider type of the two. Already guaranteed to leave
// signed/unsigned on number of lanes unchanged.
void match_bits(Expr &x, Expr &y) {
// The signedness doesn't match, so just match the bits.
if (x.type().bits() < y.type().bits()) {
x = cast(x.type().with_bits(y.type().bits()), x);
} else if (y.type().bits() < x.type().bits()) {
y = cast(y.type().with_bits(x.type().bits()), y);
}
}
void match_types_bitwise(Expr &x, Expr &y, const char *op_name) {
user_assert(x.defined() && y.defined()) << op_name << " of undefined Expr\n";
user_assert(x.type().is_int() || x.type().is_uint())
<< "The first argument to " << op_name << " must be an integer or unsigned integer";
user_assert(y.type().is_int() || y.type().is_uint())
<< "The second argument to " << op_name << " must be an integer or unsigned integer";
user_assert(y.type().is_int() == x.type().is_int())
<< "Arguments to " << op_name
<< " must be both be signed or both be unsigned.\n"
<< "LHS type: " << x.type() << " RHS type: " << y.type() << "\n"
<< "LHS value: " << x << " RHS value: " << y << "\n";
// Broadcast scalar to match vector
if (x.type().is_scalar() && y.type().is_vector()) {
x = Broadcast::make(std::move(x), y.type().lanes());
} else if (x.type().is_vector() && y.type().is_scalar()) {
y = Broadcast::make(std::move(y), x.type().lanes());
} else {
internal_assert(x.type().lanes() == y.type().lanes()) << "Can't match types of differing widths";
}
// Cast to the wider type of the two.
match_bits(x, y);
}
// Fast math ops based on those from Syrah (http://github.com/boulos/syrah). Thanks, Solomon!
// Factor a float into 2^exponent * reduced, where reduced is between 0.75 and 1.5
void range_reduce_log(const Expr &input, Expr *reduced, Expr *exponent) {
Type type = input.type();
Type int_type = Int(32, type.lanes());
Expr int_version = reinterpret(int_type, input);
// single precision = SEEE EEEE EMMM MMMM MMMM MMMM MMMM MMMM
// exponent mask = 0111 1111 1000 0000 0000 0000 0000 0000
// 0x7 0xF 0x8 0x0 0x0 0x0 0x0 0x0
// non-exponent = 1000 0000 0111 1111 1111 1111 1111 1111
// = 0x8 0x0 0x7 0xF 0xF 0xF 0xF 0xF
Expr non_exponent_mask = make_const(int_type, 0x807fffff);
// Extract a version with no exponent (between 1.0 and 2.0)
Expr no_exponent = int_version & non_exponent_mask;
// If > 1.5, we want to divide by two, to normalize back into the
// range (0.75, 1.5). We can detect this by sniffing the high bit
// of the mantissa.
Expr new_exponent = no_exponent >> 22;
Expr new_biased_exponent = 127 - new_exponent;
Expr old_biased_exponent = int_version >> 23;
*exponent = old_biased_exponent - new_biased_exponent;
Expr blended = (int_version & non_exponent_mask) | (new_biased_exponent << 23);
*reduced = reinterpret(type, blended);
}
Expr halide_log(const Expr &x_full) {
Type type = x_full.type();
internal_assert(type.element_of() == Float(32));
Expr nan = Call::make(type, "nan_f32", {}, Call::PureExtern);
Expr neg_inf = Call::make(type, "neg_inf_f32", {}, Call::PureExtern);
Expr use_nan = x_full < 0.0f; // log of a negative returns nan
Expr use_neg_inf = x_full == 0.0f; // log of zero is -inf
Expr exceptional = use_nan | use_neg_inf;
// Avoid producing nans or infs by generating ln(1.0f) instead and
// then fixing it later.
Expr patched = select(exceptional, make_one(type), x_full);
Expr reduced, exponent;
range_reduce_log(patched, &reduced, &exponent);
// Very close to the Taylor series for log about 1, but tuned to
// have minimum relative error in the reduced domain (0.75 - 1.5).
float coeff[] = {
0.05111976432738144643f,
-0.11793923497136414580f,
0.14971993724699017569f,
-0.16862004708254804686f,
0.19980668101718729313f,
-0.24991211576292837737f,
0.33333435275479328386f,
-0.50000106292873236491f,
1.0f,
0.0f};
Expr x1 = reduced - 1.0f;
Expr result = evaluate_polynomial(x1, coeff, sizeof(coeff) / sizeof(coeff[0]));
result += cast(type, exponent) * logf(2.0);
result = select(exceptional, select(use_nan, nan, neg_inf), result);
// This introduces lots of common subexpressions
result = common_subexpression_elimination(result);
return result;
}
Expr halide_exp(const Expr &x_full) {
Type type = x_full.type();
internal_assert(type.element_of() == Float(32));
float ln2_part1 = 0.6931457519f;
float ln2_part2 = 1.4286067653e-6f;
float one_over_ln2 = 1.0f / logf(2.0f);
Expr scaled = x_full * one_over_ln2;
Expr k_real = floor(scaled);
Expr k = cast(Int(32, type.lanes()), k_real);
Expr x = x_full - k_real * ln2_part1;
x -= k_real * ln2_part2;
float coeff[] = {
0.00031965933071842413f,
0.00119156835564003744f,
0.00848988645943932717f,
0.04160188091348320655f,
0.16667983794100929562f,
0.49999899033463041098f,
1.0f,
1.0f};
Expr result = evaluate_polynomial(x, coeff, sizeof(coeff) / sizeof(coeff[0]));
// Compute 2^k.
int fpbias = 127;
Expr biased = k + fpbias;
Expr inf = Call::make(type, "inf_f32", {}, Call::PureExtern);
// Shift the bits up into the exponent field and reinterpret this
// thing as float.
Expr two_to_the_n = reinterpret(type, biased << 23);
result *= two_to_the_n;
// Catch overflow and underflow
result = select(biased < 255, result, inf);
result = select(biased > 0, result, make_zero(type));
// This introduces lots of common subexpressions
result = common_subexpression_elimination(result);
return result;
}
Expr halide_erf(const Expr &x_full) {
user_assert(x_full.type() == Float(32)) << "halide_erf only works for Float(32)";
// Extract the sign and magnitude.
Expr sign = select(x_full < 0, -1.0f, 1.0f);
Expr x = abs(x_full);
// An approximation very similar to one from Abramowitz and
// Stegun, but tuned for values > 1. Takes the form 1 - P(x)^-16.
float c1[] = {0.0000818502f,
-0.0000026500f,
0.0009353904f,
0.0081960206f,
0.0430054424f,
0.0703310579f,
1.0f};
Expr approx1 = evaluate_polynomial(x, c1, sizeof(c1) / sizeof(c1[0]));
approx1 = 1.0f - pow(approx1, -16);
// An odd polynomial tuned for values < 1. Similar to the Taylor
// expansion of erf.
float c2[] = {-0.0005553339f,
0.0048937243f,
-0.0266849239f,
0.1127890132f,
-0.3761207240f,
1.1283789803f};
Expr approx2 = evaluate_polynomial(x * x, c2, sizeof(c2) / sizeof(c2[0]));
approx2 *= x;
// Switch between the two approximations based on the magnitude.
Expr y = select(x > 1.0f, approx1, approx2);
Expr result = common_subexpression_elimination(sign * y);
return result;
}
Expr raise_to_integer_power(Expr e, int64_t p) {
Expr result;
if (p == 0) {
result = make_one(e.type());
} else if (p == 1) {
result = std::move(e);
} else if (p < 0) {
result = make_one(e.type());
result /= raise_to_integer_power(std::move(e), -p);
} else {
// p is at least 2
if (p & 1) {
Expr y = raise_to_integer_power(e, p >> 1);
result = y * y * std::move(e);
} else {
e = raise_to_integer_power(std::move(e), p >> 1);
result = e * e;
}
}
return result;
}
void split_into_ands(const Expr &cond, std::vector<Expr> &result) {
if (!cond.defined()) {
return;
}
internal_assert(cond.type().is_bool()) << "Should be a boolean condition\n";
if (const And *a = cond.as<And>()) {
split_into_ands(a->a, result);
split_into_ands(a->b, result);
} else if (!is_const_one(cond)) {
result.push_back(cond);
}
}
Expr BufferBuilder::build() const {
std::vector<Expr> args(10);
if (buffer_memory.defined()) {
args[0] = buffer_memory;
} else {
Expr sz = Call::make(Int(32), Call::size_of_halide_buffer_t, {}, Call::Intrinsic);
args[0] = Call::make(type_of<struct halide_buffer_t *>(), Call::alloca, {sz}, Call::Intrinsic);
}
std::string shape_var_name = unique_name('t');
Expr shape_var = Variable::make(type_of<halide_dimension_t *>(), shape_var_name);
if (shape_memory.defined()) {
args[1] = shape_memory;
} else if (dimensions == 0) {
args[1] = make_zero(type_of<halide_dimension_t *>());
} else {
args[1] = shape_var;
}
if (host.defined()) {
args[2] = host;
} else {
args[2] = make_zero(type_of<void *>());
}
if (device.defined()) {
args[3] = device;
} else {
args[3] = make_zero(UInt(64));
}
if (device_interface.defined()) {
args[4] = device_interface;
} else {
args[4] = make_zero(type_of<struct halide_device_interface_t *>());
}
args[5] = (int)type.code();
args[6] = type.bits();
args[7] = dimensions;
std::vector<Expr> shape;
for (size_t i = 0; i < (size_t)dimensions; i++) {
if (i < mins.size()) {
shape.push_back(mins[i]);
} else {
shape.emplace_back(0);
}
if (i < extents.size()) {
shape.push_back(extents[i]);
} else {
shape.emplace_back(0);
}
if (i < strides.size()) {
shape.push_back(strides[i]);
} else {
shape.emplace_back(0);