forked from halide/Halide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeGen_C.cpp
More file actions
1682 lines (1510 loc) · 57.8 KB
/
CodeGen_C.cpp
File metadata and controls
1682 lines (1510 loc) · 57.8 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 <iostream>
#include <limits>
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include "Substitute.h"
#include "IROperator.h"
#include "Param.h"
#include "Var.h"
#include "Lerp.h"
#include "Simplify.h"
namespace Halide {
namespace Internal {
using std::ostream;
using std::endl;
using std::string;
using std::vector;
using std::ostringstream;
using std::map;
namespace {
const string buffer_t_definition =
"#ifndef HALIDE_ATTRIBUTE_ALIGN\n"
" #ifdef _MSC_VER\n"
" #define HALIDE_ATTRIBUTE_ALIGN(x) __declspec(align(x))\n"
" #else\n"
" #define HALIDE_ATTRIBUTE_ALIGN(x) __attribute__((aligned(x)))\n"
" #endif\n"
"#endif\n"
"#ifndef BUFFER_T_DEFINED\n"
"#define BUFFER_T_DEFINED\n"
"#include <stdbool.h>\n"
"#include <stdint.h>\n"
"typedef struct buffer_t {\n"
" uint64_t dev;\n"
" uint8_t* host;\n"
" int32_t extent[4];\n"
" int32_t stride[4];\n"
" int32_t min[4];\n"
" int32_t elem_size;\n"
" HALIDE_ATTRIBUTE_ALIGN(1) bool host_dirty;\n"
" HALIDE_ATTRIBUTE_ALIGN(1) bool dev_dirty;\n"
" HALIDE_ATTRIBUTE_ALIGN(1) uint8_t _padding[10 - sizeof(void *)];\n"
"} buffer_t;\n"
"#endif\n";
const string headers =
"#include <iostream>\n"
"#include <math.h>\n"
"#include <float.h>\n"
"#include <assert.h>\n"
"#include <string.h>\n"
"#include <stdio.h>\n"
"#include <stdint.h>\n";
const string globals =
"extern \"C\" {\n"
"void *halide_malloc(void *ctx, size_t);\n"
"void halide_free(void *ctx, void *ptr);\n"
"void *halide_print(void *ctx, const void *str);\n"
"void *halide_error(void *ctx, const void *str);\n"
"int halide_debug_to_file(void *ctx, const char *filename, int, struct buffer_t *buf);\n"
"int halide_start_clock(void *ctx);\n"
"int64_t halide_current_time_ns(void *ctx);\n"
"void halide_profiler_pipeline_end(void *, void *);\n"
"}\n"
"\n"
// TODO: this next chunk is copy-pasted from posix_math.cpp. A
// better solution for the C runtime would be nice.
"#ifdef _WIN32\n"
"float roundf(float);\n"
"double round(double);\n"
"#else\n"
"inline float asinh_f32(float x) {return asinhf(x);}\n"
"inline float acosh_f32(float x) {return acoshf(x);}\n"
"inline float atanh_f32(float x) {return atanhf(x);}\n"
"inline double asinh_f64(double x) {return asinh(x);}\n"
"inline double acosh_f64(double x) {return acosh(x);}\n"
"inline double atanh_f64(double x) {return atanh(x);}\n"
"#endif\n"
"inline float sqrt_f32(float x) {return sqrtf(x);}\n"
"inline float sin_f32(float x) {return sinf(x);}\n"
"inline float asin_f32(float x) {return asinf(x);}\n"
"inline float cos_f32(float x) {return cosf(x);}\n"
"inline float acos_f32(float x) {return acosf(x);}\n"
"inline float tan_f32(float x) {return tanf(x);}\n"
"inline float atan_f32(float x) {return atanf(x);}\n"
"inline float sinh_f32(float x) {return sinhf(x);}\n"
"inline float cosh_f32(float x) {return coshf(x);}\n"
"inline float tanh_f32(float x) {return tanhf(x);}\n"
"inline float hypot_f32(float x, float y) {return hypotf(x, y);}\n"
"inline float exp_f32(float x) {return expf(x);}\n"
"inline float log_f32(float x) {return logf(x);}\n"
"inline float pow_f32(float x, float y) {return powf(x, y);}\n"
"inline float floor_f32(float x) {return floorf(x);}\n"
"inline float ceil_f32(float x) {return ceilf(x);}\n"
"inline float round_f32(float x) {return roundf(x);}\n"
"\n"
"inline double sqrt_f64(double x) {return sqrt(x);}\n"
"inline double sin_f64(double x) {return sin(x);}\n"
"inline double asin_f64(double x) {return asin(x);}\n"
"inline double cos_f64(double x) {return cos(x);}\n"
"inline double acos_f64(double x) {return acos(x);}\n"
"inline double tan_f64(double x) {return tan(x);}\n"
"inline double atan_f64(double x) {return atan(x);}\n"
"inline double sinh_f64(double x) {return sinh(x);}\n"
"inline double cosh_f64(double x) {return cosh(x);}\n"
"inline double tanh_f64(double x) {return tanh(x);}\n"
"inline double hypot_f64(double x, double y) {return hypot(x, y);}\n"
"inline double exp_f64(double x) {return exp(x);}\n"
"inline double log_f64(double x) {return log(x);}\n"
"inline double pow_f64(double x, double y) {return pow(x, y);}\n"
"inline double floor_f64(double x) {return floor(x);}\n"
"inline double ceil_f64(double x) {return ceil(x);}\n"
"inline double round_f64(double x) {return round(x);}\n"
"\n"
"inline float nan_f32() {return NAN;}\n"
"inline float neg_inf_f32() {return -INFINITY;}\n"
"inline float inf_f32() {return INFINITY;}\n"
"inline bool is_nan_f32(float x) {return x != x;}\n"
"inline bool is_nan_f64(double x) {return x != x;}\n"
"inline float float_from_bits(uint32_t bits) {\n"
" union {\n"
" uint32_t as_uint;\n"
" float as_float;\n"
" } u;\n"
" u.as_uint = bits;\n"
" return u.as_float;\n"
"}\n"
"inline int64_t make_int64(int32_t hi, int32_t lo) {\n"
" return (((int64_t)hi) << 32) | (uint32_t)lo;\n"
"}\n"
"inline double make_float64(int32_t i0, int32_t i1) {\n"
" union {\n"
" int32_t as_int32[2];\n"
" double as_double;\n"
" } u;\n"
" u.as_int32[0] = i0;\n"
" u.as_int32[1] = i1;\n"
" return u.as_double;\n"
"}\n"
"\n"
"template<typename T> T max(T a, T b) {if (a > b) return a; return b;}\n"
"template<typename T> T min(T a, T b) {if (a < b) return a; return b;}\n"
// This may look wasteful, but it's the right way to do
// it. Compilers understand memcpy and will convert it to a no-op
// when used in this way. See http://blog.regehr.org/archives/959
// for a detailed comparison of type-punning methods.
"template<typename A, typename B> A reinterpret(B b) {A a; memcpy(&a, &b, sizeof(a)); return a;}\n"
"\n"
"static bool halide_rewrite_buffer(buffer_t *b, int32_t elem_size,\n"
" int32_t min0, int32_t extent0, int32_t stride0,\n"
" int32_t min1, int32_t extent1, int32_t stride1,\n"
" int32_t min2, int32_t extent2, int32_t stride2,\n"
" int32_t min3, int32_t extent3, int32_t stride3) {\n"
" b->min[0] = min0;\n"
" b->min[1] = min1;\n"
" b->min[2] = min2;\n"
" b->min[3] = min3;\n"
" b->extent[0] = extent0;\n"
" b->extent[1] = extent1;\n"
" b->extent[2] = extent2;\n"
" b->extent[3] = extent3;\n"
" b->stride[0] = stride0;\n"
" b->stride[1] = stride1;\n"
" b->stride[2] = stride2;\n"
" b->stride[3] = stride3;\n"
" return true;\n"
"}\n";
}
CodeGen_C::CodeGen_C(ostream &s, OutputKind output_kind, const std::string &guard) : IRPrinter(s), id("$$ BAD ID $$"), output_kind(output_kind) {
if (is_header()) {
// If it's a header, emit an include guard.
stream << "#ifndef HALIDE_" << print_name(guard) << '\n'
<< "#define HALIDE_" << print_name(guard) << '\n';
}
if (!is_header()) {
stream << headers;
}
// Throw in a definition of a buffer_t
stream << buffer_t_definition;
// halide_filter_metadata_t just gets a forward declaration
// (include HalideRuntime.h for the full goodness)
stream << "struct halide_filter_metadata_t;\n";
if (!is_header()) {
stream << globals;
}
// Throw in a default (empty) definition of HALIDE_FUNCTION_ATTRS
// (some hosts may define this to e.g. __attribute__((warn_unused_result)))
stream << "#ifndef HALIDE_FUNCTION_ATTRS\n";
stream << "#define HALIDE_FUNCTION_ATTRS\n";
stream << "#endif\n";
if (!is_c_plus_plus_interface()) {
// Everything from here on out is extern "C".
stream << "#ifdef __cplusplus\n";
stream << "extern \"C\" {\n";
stream << "#endif\n";
}
}
CodeGen_C::~CodeGen_C() {
if (!is_c_plus_plus_interface()) {
stream << "#ifdef __cplusplus\n";
stream << "} // extern \"C\"\n";
stream << "#endif\n";
}
if (is_header()) {
stream << "#endif\n";
}
}
namespace {
string type_to_c_type(Type type, bool include_space, bool c_plus_plus = true) {
bool needs_space = true;
ostringstream oss;
user_assert(type.lanes() == 1) << "Can't use vector types when compiling to C (yet)\n";
if (type.is_float()) {
if (type.bits() == 32) {
oss << "float";
} else if (type.bits() == 64) {
oss << "double";
} else {
user_error << "Can't represent a float with this many bits in C: " << type << "\n";
}
} else if (type.is_handle()) {
needs_space = false;
// If there is no type info or is generating C (not C++) and
// the type is a class or in an inner scope, just use void *.
if (type.handle_type == NULL ||
(!c_plus_plus &&
(!type.handle_type->namespaces.empty() ||
!type.handle_type->enclosing_types.empty() ||
type.handle_type->inner_name.cpp_type_type == halide_cplusplus_type_name::Class))) {
oss << "const void *";
} else {
if (type.handle_type->inner_name.cpp_type_type == halide_cplusplus_type_name::Struct) {
oss << "struct ";
} else if (type.handle_type->inner_name.cpp_type_type == halide_cplusplus_type_name::Class) {
oss << "class ";
}
if (!type.handle_type->namespaces.empty() ||
!type.handle_type->enclosing_types.empty()) {
oss << "::";
for (size_t i = 0; i < type.handle_type->namespaces.size(); i++) {
oss << type.handle_type->namespaces[i] << "::";
}
for (size_t i = 0; i < type.handle_type->enclosing_types.size(); i++) {
oss << type.handle_type->enclosing_types[i].name << "::";
}
}
oss << type.handle_type->inner_name.name;
if (type.handle_type->reference_type == halide_handle_cplusplus_type::LValueReference) {
oss << " &";
} else if (type.handle_type->reference_type == halide_handle_cplusplus_type::LValueReference) {
oss << " &&";
}
for (auto modifier : type.handle_type->cpp_type_modifiers) {
if (modifier & halide_handle_cplusplus_type::Const) {
oss << " const";
}
if (modifier & halide_handle_cplusplus_type::Volatile) {
oss << " volatile";
}
if (modifier & halide_handle_cplusplus_type::Restrict) {
oss << " restrict";
}
if (modifier & halide_handle_cplusplus_type::Pointer) {
oss << " *";
} else {
break;
}
}
}
} else {
switch (type.bits()) {
case 1:
oss << "bool";
break;
case 8: case 16: case 32: case 64:
if (type.is_uint()) oss << 'u';
oss << "int" << type.bits() << "_t";
break;
default:
user_error << "Can't represent an integer with this many bits in C: " << type << "\n";
}
}
if (include_space && needs_space)
oss << " ";
return oss.str();
}
}
string CodeGen_C::print_type(Type type, AppendSpaceIfNeeded space_option) {
return type_to_c_type(type, space_option == AppendSpace);
}
string CodeGen_C::print_reinterpret(Type type, Expr e) {
ostringstream oss;
oss << "reinterpret<" << print_type(type) << ">(" << print_expr(e) << ")";
return oss.str();
}
string CodeGen_C::print_name(const string &name) {
ostringstream oss;
// Prefix an underscore to avoid reserved words (e.g. a variable named "while")
if (isalpha(name[0])) {
oss << '_';
}
for (size_t i = 0; i < name.size(); i++) {
if (name[i] == '.') {
oss << '_';
} else if (name[i] == '$') {
oss << "__";
} else if (name[i] != '_' && !isalnum(name[i])) {
oss << "___";
}
else oss << name[i];
}
return oss.str();
}
namespace {
class ExternCallPrototypes : public IRGraphVisitor {
ostream &stream;
std::set<string> &emitted;
using IRGraphVisitor::visit;
// TODO: This class should likely be able to signal an error if C++
// code shows up and started_in_c_plus_plus isn't true, but the logic
// is orthogonal.
const bool started_in_c_plus_plus;
bool in_c_plus_plus;
void switch_calling_convention(bool c_plus_plus) {
if (in_c_plus_plus != c_plus_plus) {
if (in_c_plus_plus) {
stream << "}\n";
} else {
stream << "extern \"C\" {\n";
}
in_c_plus_plus = c_plus_plus;
}
}
void visit(const Call *op) {
IRGraphVisitor::visit(op);
if (op->call_type == Call::Extern ||
op->call_type == Call::ExternCPlusPlus) {
switch_calling_convention(op->call_type == Call::ExternCPlusPlus);
// TODO: optimize generation of namespacing to reuse namespace decls.
int32_t namespace_count = 0;
std::string name;
if (op->call_type == Call::ExternCPlusPlus) {
std::vector<std::string> namespaces;
name = extract_namespaces(op->name, namespaces);
for (auto const &ns : namespaces) {
stream << "namespace " << ns << " { ";
}
namespace_count = namespaces.size();
} else {
name = op->name;
}
if (!emitted.count(name)) {
stream << type_to_c_type(op->type, true) << " " << name << "(";
if (function_takes_user_context(name)) {
stream << "void *";
if (op->args.size()) {
stream << ", ";
}
}
for (size_t i = 0; i < op->args.size(); i++) {
if (i > 0) {
stream << ", ";
}
if (op->args[i].as<StringImm>()) {
stream << "const char *";
} else {
stream << type_to_c_type(op->args[i].type(), true);
}
}
stream << ");";
for (int32_t i = 0; i < namespace_count; i++) {
stream << " }";
}
stream << "\n";
emitted.insert(op->name); // Keep namespacing here.
}
}
}
public:
ExternCallPrototypes(ostream &s, std::set<string> &emitted, bool in_c_plus_plus)
: stream(s), emitted(emitted), started_in_c_plus_plus(in_c_plus_plus), in_c_plus_plus(in_c_plus_plus) {
size_t j = 0;
// Make sure we don't catch calls that are already in the global declarations
for (size_t i = 0; i < globals.size(); i++) {
char c = globals[i];
if (c == '(' && i > j+1) {
// Could be the end of a function_name.
emitted.insert(globals.substr(j+1, i-j-1));
}
if (('A' <= c && c <= 'Z') ||
('a' <= c && c <= 'z') ||
c == '_' ||
('0' <= c && c <= '9')) {
// Could be part of a function name.
} else {
j = i;
}
}
}
~ExternCallPrototypes() {
switch_calling_convention(started_in_c_plus_plus);
}
};
}
void CodeGen_C::compile(const Module &input) {
for (size_t i = 0; i < input.buffers.size(); i++) {
compile(input.buffers[i]);
}
for (size_t i = 0; i < input.functions.size(); i++) {
compile(input.functions[i]);
}
}
void CodeGen_C::compile(const LoweredFunc &f) {
// Don't put non-external function declarations in headers.
if (is_header() && f.linkage != LoweredFunc::External) {
return;
}
internal_assert(emitted.count(f.name) == 0)
<< "Function '" << f.name << "' has already been emitted.\n";
emitted.insert(f.name);
const std::vector<Argument> &args = f.args;
for (size_t i = 0; i < args.size(); i++) {
if (args[i].type.handle_type != NULL) {
if (!args[i].type.handle_type->namespaces.empty()) {
if (args[i].type.handle_type->inner_name.cpp_type_type != halide_cplusplus_type_name::Simple) {
for (size_t ns = 0; ns < args[i].type.handle_type->namespaces.size(); ns++ ) {
for (size_t indent = 0; indent < ns; indent++) {
stream << " ";
}
stream << indent << "namespace " << args[i].type.handle_type->namespaces[ns] << " {\n";
}
for (size_t indent = 0; indent < args[i].type.handle_type->namespaces.size(); indent++) {
stream << " ";
}
if (args[i].type.handle_type->inner_name.cpp_type_type != halide_cplusplus_type_name::Struct) {
stream << "struct " << args[i].type.handle_type->inner_name.name << ";\n";
} else {
stream << "class " << args[i].type.handle_type->inner_name.name << ";\n";
}
for (size_t ns = 0; ns < args[i].type.handle_type->namespaces.size(); ns++ ) {
for (size_t indent = 0; indent < ns; indent++) {
stream << " ";
}
stream << indent << "}\n";
}
}
}
}
}
have_user_context = false;
for (size_t i = 0; i < args.size(); i++) {
// TODO: check that its type is void *?
have_user_context |= (args[i].name == "__user_context");
}
// Emit prototypes for any extern calls used.
if (!is_header()) {
stream << "\n";
ExternCallPrototypes e(stream, emitted, is_c_plus_plus_interface());
f.body.accept(&e);
stream << "\n";
}
std::vector<std::string> namespaces;
std::string simple_name = extract_namespaces(f.name, namespaces);
if (!is_c_plus_plus_interface()) {
user_assert(namespaces.empty()) <<
"Namespace qualifiers not allowed on function name if not compiling with Target::CPlusPlusNameMangling.\n";
}
if (!namespaces.empty()) {
const char *separator = "";
for (const auto &ns : namespaces) {
stream << separator << "namespace " << ns << " {";
separator = " ";
}
stream << "\n\n";
}
// Emit the function prototype
if (f.linkage != LoweredFunc::External) {
// If the function isn't public, mark it static.
stream << "static ";
}
stream << "int " << simple_name << "(";
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer()) {
stream << "buffer_t *"
<< print_name(args[i].name)
<< "_buffer";
} else {
stream << print_type(args[i].type, AppendSpace)
<< print_name(args[i].name);
}
if (i < args.size()-1) stream << ", ";
}
if (is_header()) {
stream << ") HALIDE_FUNCTION_ATTRS;\n";
} else {
stream << ") HALIDE_FUNCTION_ATTRS {\n";
indent += 1;
// Unpack the buffer_t's
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer()) {
push_buffer(args[i].type, args[i].name);
}
}
// Emit the body
print(f.body);
// Return success.
do_indent();
stream << "return 0;\n";
indent -= 1;
stream << "}\n";
// Done with the buffer_t's, pop the associated symbols.
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer()) {
pop_buffer(args[i].name);
}
}
}
if (is_header()) {
// If this is a header and we are here, we know this is an externally visible Func, so
// declare the argv function.
stream << "int " << simple_name << "_argv(void **args) HALIDE_FUNCTION_ATTRS;\n";
}
// Close namespaces here as metadata must be outside them
if (!namespaces.empty()) {
stream << "\n";
for (size_t i = 0; i < namespaces.size(); i++) {
stream << "}";
}
stream << " // Close namespaces ";
const char *separator = "";
for (const auto &ns : namespaces) {
stream << separator << ns;
separator = "::";
}
stream << "\n\n";
}
if (is_header()) {
// And also the metadata.
stream << "extern const struct halide_filter_metadata_t " << simple_name << "_metadata;\n";
}
}
void CodeGen_C::compile(const Buffer &buffer) {
// Don't define buffers in headers.
if (is_header()) {
return;
}
string name = print_name(buffer.name());
buffer_t b = *(buffer.raw_buffer());
// Figure out the offset of the last pixel.
size_t num_elems = 1;
for (int d = 0; b.extent[d]; d++) {
num_elems += b.stride[d] * (b.extent[d] - 1);
}
// Emit the data
stream << "static uint8_t " << name << "_data[] __attribute__ ((aligned (32))) = {";
for (size_t i = 0; i < num_elems * b.elem_size; i++) {
if (i > 0) stream << ", ";
stream << (int)(b.host[i]);
}
stream << "};\n";
// Emit the buffer_t
user_assert(b.host) << "Can't embed image: " << buffer.name() << " because it has a null host pointer\n";
user_assert(!b.dev_dirty) << "Can't embed image: " << buffer.name() << "because it has a dirty device pointer\n";
stream << "static buffer_t " << name << "_buffer = {"
<< "0, " // dev
<< "&" << name << "_data[0], " // host
<< "{" << b.extent[0] << ", " << b.extent[1] << ", " << b.extent[2] << ", " << b.extent[3] << "}, "
<< "{" << b.stride[0] << ", " << b.stride[1] << ", " << b.stride[2] << ", " << b.stride[3] << "}, "
<< "{" << b.min[0] << ", " << b.min[1] << ", " << b.min[2] << ", " << b.min[3] << "}, "
<< b.elem_size << ", "
<< "0, " // host_dirty
<< "0};\n"; //dev_dirty
// Make a global pointer to it
stream << "static buffer_t *" << name << " = &" << name << "_buffer;\n";
}
void CodeGen_C::push_buffer(Type t, const std::string &buffer_name) {
string name = print_name(buffer_name);
string buf_name = name + "_buffer";
string type = print_type(t);
do_indent();
stream << type
<< " *"
<< name
<< " = ("
<< type
<< " *)("
<< buf_name
<< "->host);\n";
Allocation alloc;
alloc.type = t;
allocations.push(buffer_name, alloc);
do_indent();
stream << "(void)" << name << ";\n";
do_indent();
stream << "const bool "
<< name
<< "_host_and_dev_are_null = ("
<< buf_name << "->host == nullptr) && ("
<< buf_name << "->dev == 0);\n";
do_indent();
stream << "(void)" << name << "_host_and_dev_are_null;\n";
for (int j = 0; j < 4; j++) {
do_indent();
stream << "const int32_t "
<< name
<< "_min_" << j << " = "
<< buf_name
<< "->min[" << j << "];\n";
// emit a void cast to suppress "unused variable" warnings
do_indent();
stream << "(void)" << name << "_min_" << j << ";\n";
}
for (int j = 0; j < 4; j++) {
do_indent();
stream << "const int32_t "
<< name
<< "_extent_" << j << " = "
<< buf_name
<< "->extent[" << j << "];\n";
do_indent();
stream << "(void)" << name << "_extent_" << j << ";\n";
}
for (int j = 0; j < 4; j++) {
do_indent();
stream << "const int32_t "
<< name
<< "_stride_" << j << " = "
<< buf_name
<< "->stride[" << j << "];\n";
do_indent();
stream << "(void)" << name << "_stride_" << j << ";\n";
}
do_indent();
stream << "const int32_t "
<< name
<< "_elem_size = "
<< buf_name
<< "->elem_size;\n";
do_indent();
stream << "(void)" << name << "_elem_size;\n";
}
void CodeGen_C::pop_buffer(const std::string &buffer_name) {
allocations.pop(buffer_name);
}
string CodeGen_C::print_expr(Expr e) {
id = "$$ BAD ID $$";
e.accept(this);
return id;
}
void CodeGen_C::print_stmt(Stmt s) {
s.accept(this);
}
string CodeGen_C::print_assignment(Type t, const std::string &rhs) {
map<string, string>::iterator cached = cache.find(rhs);
if (cached == cache.end()) {
id = unique_name('_');
do_indent();
stream << print_type(t, AppendSpace) << id << " = " << rhs << ";\n";
cache[rhs] = id;
} else {
id = cached->second;
}
return id;
}
void CodeGen_C::open_scope() {
cache.clear();
do_indent();
indent++;
stream << "{\n";
}
void CodeGen_C::close_scope(const std::string &comment) {
cache.clear();
indent--;
do_indent();
if (!comment.empty()) {
stream << "} // " << comment << "\n";
} else {
stream << "}\n";
}
}
void CodeGen_C::visit(const Variable *op) {
id = print_name(op->name);
}
void CodeGen_C::visit(const Cast *op) {
print_assignment(op->type, "(" + print_type(op->type) + ")(" + print_expr(op->value) + ")");
}
void CodeGen_C::visit_binop(Type t, Expr a, Expr b, const char * op) {
string sa = print_expr(a);
string sb = print_expr(b);
print_assignment(t, sa + " " + op + " " + sb);
}
void CodeGen_C::visit(const Add *op) {
visit_binop(op->type, op->a, op->b, "+");
}
void CodeGen_C::visit(const Sub *op) {
visit_binop(op->type, op->a, op->b, "-");
}
void CodeGen_C::visit(const Mul *op) {
visit_binop(op->type, op->a, op->b, "*");
}
void CodeGen_C::visit(const Div *op) {
int bits;
if (is_const_power_of_two_integer(op->b, &bits)) {
ostringstream oss;
oss << print_expr(op->a) << " >> " << bits;
print_assignment(op->type, oss.str());
} else if (op->type.is_int()) {
string a = print_expr(op->a);
string b = print_expr(op->b);
// q = a / b
string q = print_assignment(op->type, a + " / " + b);
// r = a - q * b
string r = print_assignment(op->type, a + " - " + q + " * " + b);
// bs = b >> (8*sizeof(T) - 1)
string bs = print_assignment(op->type, b + " >> (" + print_type(op->type.element_of()) + ")" + std::to_string(op->type.bits() - 1));
// rs = r >> (8*sizeof(T) - 1)
string rs = print_assignment(op->type, r + " >> (" + print_type(op->type.element_of()) + ")" + std::to_string(op->type.bits() - 1));
// id = q - (rs & bs) + (rs & bs)
print_assignment(op->type, q + " - (" + rs + " & " + bs + ") + (" + rs + " & ~" + bs + ")");
} else {
visit_binop(op->type, op->a, op->b, "/");
}
}
void CodeGen_C::visit(const Mod *op) {
int bits;
if (is_const_power_of_two_integer(op->b, &bits)) {
ostringstream oss;
oss << print_expr(op->a) << " & " << ((1 << bits)-1);
print_assignment(op->type, oss.str());
} else if (op->type.is_int()) {
string a = print_expr(op->a);
string b = print_expr(op->b);
// r = a % b
string r = print_assignment(op->type, a + " % " + b);
// rs = r >> (8*sizeof(T) - 1)
string rs = print_assignment(op->type, r + " >> (" + print_type(op->type.element_of()) + ")" + std::to_string(op->type.bits() - 1));
// abs_b = abs(b)
string abs_b = print_expr(cast(op->type, abs(op->b)));
// id = r + (abs_b & rs)
print_assignment(op->type, r + " + (" + abs_b + " & " + rs + ")");
} else {
visit_binop(op->type, op->a, op->b, "%");
}
}
void CodeGen_C::visit(const Max *op) {
print_expr(Call::make(op->type, "max", {op->a, op->b}, Call::Extern));
}
void CodeGen_C::visit(const Min *op) {
print_expr(Call::make(op->type, "min", {op->a, op->b}, Call::Extern));
}
void CodeGen_C::visit(const EQ *op) {
visit_binop(op->type, op->a, op->b, "==");
}
void CodeGen_C::visit(const NE *op) {
visit_binop(op->type, op->a, op->b, "!=");
}
void CodeGen_C::visit(const LT *op) {
visit_binop(op->type, op->a, op->b, "<");
}
void CodeGen_C::visit(const LE *op) {
visit_binop(op->type, op->a, op->b, "<=");
}
void CodeGen_C::visit(const GT *op) {
visit_binop(op->type, op->a, op->b, ">");
}
void CodeGen_C::visit(const GE *op) {
visit_binop(op->type, op->a, op->b, ">=");
}
void CodeGen_C::visit(const Or *op) {
visit_binop(op->type, op->a, op->b, "||");
}
void CodeGen_C::visit(const And *op) {
visit_binop(op->type, op->a, op->b, "&&");
}
void CodeGen_C::visit(const Not *op) {
print_assignment(op->type, "!(" + print_expr(op->a) + ")");
}
void CodeGen_C::visit(const IntImm *op) {
if (op->type == Int(32)) {
id = std::to_string(op->value);
} else {
print_assignment(op->type, "(" + print_type(op->type) + ")(" + std::to_string(op->value) + ")");
}
}
void CodeGen_C::visit(const UIntImm *op) {
print_assignment(op->type, "(" + print_type(op->type) + ")(" + std::to_string(op->value) + ")");
}
void CodeGen_C::visit(const StringImm *op) {
ostringstream oss;
oss << Expr(op);
id = oss.str();
}
// NaN is the only float/double for which this is true... and
// surprisingly, there doesn't seem to be a portable isnan function
// (dsharlet).
template <typename T>
static bool isnan(T x) { return x != x; }
template <typename T>
static bool isinf(T x)
{
return std::numeric_limits<T>::has_infinity && (
x == std::numeric_limits<T>::infinity() ||
x == -std::numeric_limits<T>::infinity());
}
void CodeGen_C::visit(const FloatImm *op) {
if (isnan(op->value)) {
id = "nan_f32()";
} else if (isinf(op->value)) {
if (op->value > 0) {
id = "inf_f32()";
} else {
id = "neg_inf_f32()";
}
} else {
// Write the constant as reinterpreted uint to avoid any bits lost in conversion.
union {
uint32_t as_uint;
float as_float;
} u;
u.as_float = op->value;
ostringstream oss;
oss << "float_from_bits(" << u.as_uint << " /* " << u.as_float << " */)";
id = oss.str();
}
}
void CodeGen_C::visit(const Call *op) {
internal_assert(op->call_type == Call::Extern ||
op->call_type == Call::ExternCPlusPlus ||
op->call_type == Call::PureExtern ||
op->call_type == Call::Intrinsic ||
op->call_type == Call::PureIntrinsic)
<< "Can only codegen extern calls and intrinsics\n";
ostringstream rhs;
// Handle intrinsics first
if (op->is_intrinsic(Call::debug_to_file)) {
internal_assert(op->args.size() == 3);
const StringImm *string_imm = op->args[0].as<StringImm>();
internal_assert(string_imm);
string filename = string_imm->value;
string typecode = print_expr(op->args[1]);
string buffer = print_name(print_expr(op->args[2]));
rhs << "halide_debug_to_file(";
rhs << (have_user_context ? "__user_context_" : "nullptr");
rhs << ", \"" + filename + "\", " + typecode;
rhs << ", (struct buffer_t *)" << buffer;
rhs << ")";
} else if (op->is_intrinsic(Call::bitwise_and)) {
internal_assert(op->args.size() == 2);
string a0 = print_expr(op->args[0]);
string a1 = print_expr(op->args[1]);
rhs << a0 << " & " << a1;
} else if (op->is_intrinsic(Call::bitwise_xor)) {
internal_assert(op->args.size() == 2);
string a0 = print_expr(op->args[0]);
string a1 = print_expr(op->args[1]);
rhs << a0 << " ^ " << a1;
} else if (op->is_intrinsic(Call::bitwise_or)) {
internal_assert(op->args.size() == 2);
string a0 = print_expr(op->args[0]);
string a1 = print_expr(op->args[1]);
rhs << a0 << " | " << a1;
} else if (op->is_intrinsic(Call::bitwise_not)) {
internal_assert(op->args.size() == 1);
rhs << "~" << print_expr(op->args[0]);
} else if (op->is_intrinsic(Call::reinterpret)) {
internal_assert(op->args.size() == 1);
rhs << print_reinterpret(op->type, op->args[0]);
} else if (op->is_intrinsic(Call::shift_left)) {
internal_assert(op->args.size() == 2);
string a0 = print_expr(op->args[0]);
string a1 = print_expr(op->args[1]);
rhs << a0 << " << " << a1;
} else if (op->is_intrinsic(Call::shift_right)) {
internal_assert(op->args.size() == 2);
string a0 = print_expr(op->args[0]);
string a1 = print_expr(op->args[1]);
rhs << a0 << " >> " << a1;
} else if (op->is_intrinsic(Call::rewrite_buffer)) {
int dims = ((int)(op->args.size())-2)/3;
(void)dims; // In case internal_assert is ifdef'd to do nothing
internal_assert((int)(op->args.size()) == dims*3 + 2);
internal_assert(dims <= 4);
vector<string> args(op->args.size());
const Variable *v = op->args[0].as<Variable>();
internal_assert(v);
args[0] = print_name(v->name);
for (size_t i = 1; i < op->args.size(); i++) {
args[i] = print_expr(op->args[i]);
}
rhs << "halide_rewrite_buffer(";
for (size_t i = 0; i < 14; i++) {
if (i > 0) rhs << ", ";
if (i < args.size()) {
rhs << args[i];
} else {
rhs << '0';
}
}
rhs << ")";