-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathCodeGen_C.cpp
More file actions
2735 lines (2430 loc) · 105 KB
/
CodeGen_C.cpp
File metadata and controls
2735 lines (2430 loc) · 105 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 <array>
#include <iostream>
#include <limits>
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include "Deinterleave.h"
#include "FindIntrinsics.h"
#include "IROperator.h"
#include "Lerp.h"
#include "Param.h"
#include "Simplify.h"
#include "StrictifyFloat.h"
#include "Substitute.h"
#include "Type.h"
#include "Util.h"
#include "Var.h"
namespace Halide {
namespace Internal {
using std::map;
using std::ostream;
using std::ostringstream;
using std::string;
using std::vector;
extern "C" unsigned char halide_internal_initmod_inlined_c[];
extern "C" unsigned char halide_internal_runtime_header_HalideRuntime_h[];
extern "C" unsigned char halide_internal_runtime_header_HalideRuntimeCuda_h[];
extern "C" unsigned char halide_internal_runtime_header_HalideRuntimeHexagonHost_h[];
extern "C" unsigned char halide_internal_runtime_header_HalideRuntimeMetal_h[];
extern "C" unsigned char halide_internal_runtime_header_HalideRuntimeOpenCL_h[];
extern "C" unsigned char halide_internal_runtime_header_HalideRuntimeQurt_h[];
extern "C" unsigned char halide_internal_runtime_header_HalideRuntimeD3D12Compute_h[];
extern "C" unsigned char halide_internal_runtime_header_HalideRuntimeWebGPU_h[];
extern "C" unsigned char halide_c_template_CodeGen_C_prologue[];
extern "C" unsigned char halide_c_template_CodeGen_C_vectors[];
namespace {
// HALIDE_MUST_USE_RESULT defined here is intended to exactly
// duplicate the definition in HalideRuntime.h (so that either or
// both can be present, in any order).
const char *const kDefineMustUseResult = R"INLINE_CODE(#ifndef HALIDE_MUST_USE_RESULT
#ifdef __has_attribute
#if __has_attribute(nodiscard)
#define HALIDE_MUST_USE_RESULT [[nodiscard]]
#elif __has_attribute(warn_unused_result)
#define HALIDE_MUST_USE_RESULT __attribute__((warn_unused_result))
#else
#define HALIDE_MUST_USE_RESULT
#endif
#else
#define HALIDE_MUST_USE_RESULT
#endif
#endif
)INLINE_CODE";
const char *const constexpr_argument_info_docs = R"INLINE_CODE(
/**
* This function returns a constexpr array of information about a Halide-generated
* function's argument signature (e.g., number of arguments, type of each, etc).
* While this is a subset of the information provided by the existing _metadata
* function, it has the distinct advantage of allowing one to use the information
* it at compile time (rather than runtime). This can be quite useful for producing
* e.g. automatic call wrappers, etc.
*
* For instance, to compute the number of Buffers in a Function, one could do something
* like:
*
* using namespace HalideFunctionInfo;
*
* template<size_t arg_count>
* constexpr size_t count_buffers(const std::array<ArgumentInfo, arg_count> args) {
* size_t buffer_count = 0;
* for (const auto a : args) {
* if (a.kind == InputBuffer || a.kind == OutputBuffer) {
* buffer_count++;
* }
* }
* return buffer_count;
* }
*
* constexpr size_t count = count_buffers(metadata_tester_argument_info());
*
* The value of `count` will be computed entirely at compile-time, with no runtime
* impact aside from the numerical value of the constant.
*/
)INLINE_CODE";
class TypeInfoGatherer : public IRGraphVisitor {
private:
using IRGraphVisitor::include;
using IRGraphVisitor::visit;
void include_type(const Type &t) {
if (t.is_vector()) {
if (t.is_bool()) {
// bool vectors are always emitted as uint8 in the C++ backend
// TODO: on some architectures, we could do better by choosing
// a bitwidth that matches the other vectors in use; EliminateBoolVectors
// could be used for this with a bit of work.
vector_types_used.insert(UInt(8).with_lanes(t.lanes()));
} else if (!t.is_handle()) {
// Vector-handle types can be seen when processing (e.g.)
// require() statements that are vectorized, but they
// will all be scalarized away prior to use, so don't emit
// them.
vector_types_used.insert(t);
if (t.is_int()) {
// If we are including an int-vector type, also include
// the same-width uint-vector type; there are various operations
// that can use uint vectors for intermediate results (e.g. lerp(),
// but also Mod, which can generate a call to abs() for int types,
// which always produces uint results for int inputs in Halide);
// it's easier to just err on the side of extra vectors we don't
// use since they are just type declarations.
vector_types_used.insert(t.with_code(halide_type_uint));
}
}
}
}
void include_lerp_types(const Type &t) {
if (t.is_vector() && t.is_int_or_uint() && (t.bits() >= 8 && t.bits() <= 32)) {
include_type(t.widen());
}
}
protected:
void include(const Expr &e) override {
include_type(e.type());
IRGraphVisitor::include(e);
}
// GCC's __builtin_shuffle takes an integer vector of
// the size of its input vector. Make sure this type exists.
void visit(const Shuffle *op) override {
vector_types_used.insert(Int(32, op->vectors[0].type().lanes()));
IRGraphVisitor::visit(op);
}
void visit(const For *op) override {
for_types_used.insert(op->for_type);
IRGraphVisitor::visit(op);
}
void visit(const Ramp *op) override {
include_type(op->type.with_lanes(op->lanes));
IRGraphVisitor::visit(op);
}
void visit(const Broadcast *op) override {
include_type(op->type.with_lanes(op->lanes));
IRGraphVisitor::visit(op);
}
void visit(const Cast *op) override {
include_type(op->type);
IRGraphVisitor::visit(op);
}
void visit(const Call *op) override {
include_type(op->type);
if (op->is_intrinsic(Call::lerp)) {
// lower_lerp() can synthesize wider vector types.
for (const auto &a : op->args) {
include_lerp_types(a.type());
}
} else if (op->is_intrinsic()) {
Expr lowered = lower_intrinsic(op);
if (lowered.defined()) {
lowered.accept(this);
return;
}
}
IRGraphVisitor::visit(op);
}
public:
std::set<ForType> for_types_used;
std::set<Type> vector_types_used;
};
} // namespace
CodeGen_C::CodeGen_C(ostream &s, const Target &t, OutputKind output_kind, const std::string &guard)
: IRPrinter(s), id("$$ BAD ID $$"), target(t), output_kind(output_kind) {
if (output_kind == CPlusPlusFunctionInfoHeader) {
// If it's a header, emit an include guard.
stream << "#ifndef HALIDE_FUNCTION_INFO_" << c_print_name(guard) << "\n"
<< "#define HALIDE_FUNCTION_INFO_" << c_print_name(guard) << "\n";
stream << R"INLINE_CODE(
/* MACHINE GENERATED By Halide. */
#if !(__cplusplus >= 201703L || _MSVC_LANG >= 201703L)
#error "This file requires C++17 or later; please upgrade your compiler."
#endif
#include "HalideRuntime.h"
)INLINE_CODE";
return;
}
if (is_header()) {
// If it's a header, emit an include guard.
stream << "#ifndef HALIDE_" << c_print_name(guard) << "\n"
<< "#define HALIDE_" << c_print_name(guard) << "\n"
<< "#include <stdint.h>\n"
<< "\n"
<< "// Forward declarations of the types used in the interface\n"
<< "// to the Halide pipeline.\n"
<< "//\n";
if (target.has_feature(Target::NoRuntime)) {
stream << "// For the definitions of these structs, include HalideRuntime.h\n";
} else {
stream << "// Definitions for these structs are below.\n";
}
stream << "\n"
<< "// Halide's representation of a multi-dimensional array.\n"
<< "// Halide::Runtime::Buffer is a more user-friendly wrapper\n"
<< "// around this. Its declaration is in HalideBuffer.h\n"
<< "struct halide_buffer_t;\n"
<< "\n"
<< "// Metadata describing the arguments to the generated function.\n"
<< "// Used to construct calls to the _argv version of the function.\n"
<< "struct halide_filter_metadata_t;\n"
<< "\n";
// We just forward declared the following types:
forward_declared.insert(type_of<halide_buffer_t *>().handle_type);
forward_declared.insert(type_of<halide_filter_metadata_t *>().handle_type);
} else if (is_extern_decl()) {
// Extern decls to be wrapped inside other code (eg python extensions);
// emit the forward decls with a minimum of noise. Note that we never
// mess with legacy buffer types in this case.
stream << "struct halide_buffer_t;\n"
<< "struct halide_filter_metadata_t;\n"
<< "\n";
forward_declared.insert(type_of<halide_buffer_t *>().handle_type);
forward_declared.insert(type_of<halide_filter_metadata_t *>().handle_type);
} else {
// Include declarations of everything generated C source might want
stream
<< halide_c_template_CodeGen_C_prologue << "\n"
<< halide_internal_runtime_header_HalideRuntime_h << "\n"
<< halide_internal_initmod_inlined_c << "\n";
stream << "\n";
}
stream << kDefineMustUseResult << "\n";
// 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";
}
CodeGen_C::~CodeGen_C() {
set_name_mangling_mode(NameMangling::Default);
if (is_header()) {
if (!target.has_feature(Target::NoRuntime)) {
stream << "\n"
<< "// The generated object file that goes with this header\n"
<< "// includes a full copy of the Halide runtime so that it\n"
<< "// can be used standalone. Declarations for the functions\n"
<< "// in the Halide runtime are below.\n";
if (target.os == Target::Windows) {
stream
<< "//\n"
<< "// The inclusion of this runtime means that it is not legal\n"
<< "// to link multiple Halide-generated object files together.\n"
<< "// This problem is Windows-specific. On other platforms, we\n"
<< "// use weak linkage.\n";
} else {
stream
<< "//\n"
<< "// The runtime is defined using weak linkage, so it is legal\n"
<< "// to link multiple Halide-generated object files together,\n"
<< "// or to clobber any of these functions with your own\n"
<< "// definition.\n";
}
stream << "//\n"
<< "// To generate an object file without a full copy of the\n"
<< "// runtime, use the -no_runtime target flag. To generate a\n"
<< "// standalone Halide runtime to use with such object files\n"
<< "// use the -r flag with any Halide generator binary, e.g.:\n"
<< "// $ ./my_generator -r halide_runtime -o . target=host\n"
<< "\n"
<< halide_internal_runtime_header_HalideRuntime_h << "\n";
if (target.has_feature(Target::CUDA)) {
stream << halide_internal_runtime_header_HalideRuntimeCuda_h << "\n";
}
if (target.has_feature(Target::HVX)) {
stream << halide_internal_runtime_header_HalideRuntimeHexagonHost_h << "\n";
}
if (target.has_feature(Target::Metal)) {
stream << halide_internal_runtime_header_HalideRuntimeMetal_h << "\n";
}
if (target.has_feature(Target::OpenCL)) {
stream << halide_internal_runtime_header_HalideRuntimeOpenCL_h << "\n";
}
if (target.has_feature(Target::D3D12Compute)) {
stream << halide_internal_runtime_header_HalideRuntimeD3D12Compute_h << "\n";
}
if (target.has_feature(Target::WebGPU)) {
stream << halide_internal_runtime_header_HalideRuntimeWebGPU_h << "\n";
}
}
stream << "#endif\n";
}
}
void CodeGen_C::add_platform_prologue() {
// nothing
}
void CodeGen_C::add_vector_typedefs(const std::set<Type> &vector_types) {
if (!vector_types.empty()) {
// Voodoo fix: on at least one config (our arm32 buildbot running gcc 5.4),
// emitting this long text string was regularly garbled in a predictable pattern;
// flushing the stream before or after heals it. Since C++ codegen is rarely
// on a compilation critical path, we'll just band-aid it in this way.
stream << std::flush;
stream << halide_c_template_CodeGen_C_vectors;
stream << std::flush;
for (const auto &t : vector_types) {
string name = print_type(t, DoNotAppendSpace);
string scalar_name = print_type(t.element_of(), DoNotAppendSpace);
stream << "#if halide_cpp_use_native_vector(" << scalar_name << ", " << t.lanes() << ")\n";
stream << "using " << name << " = NativeVector<" << scalar_name << ", " << t.lanes() << ">;\n";
stream << "using " << name << "_ops = NativeVectorOps<" << scalar_name << ", " << t.lanes() << ">;\n";
// Useful for debugging which Vector implementation is being selected
// stream << "#pragma message \"using NativeVector for " << t << "\"\n";
stream << "#else\n";
stream << "using " << name << " = CppVector<" << scalar_name << ", " << t.lanes() << ">;\n";
stream << "using " << name << "_ops = CppVectorOps<" << scalar_name << ", " << t.lanes() << ">;\n";
// Useful for debugging which Vector implementation is being selected
// stream << "#pragma message \"using CppVector for " << t << "\"\n";
stream << "#endif\n";
}
}
using_vector_typedefs = true;
}
void CodeGen_C::set_name_mangling_mode(NameMangling mode) {
if (extern_c_open && mode != NameMangling::C) {
stream << R"INLINE_CODE(
#ifdef __cplusplus
} // extern "C"
#endif
)INLINE_CODE";
extern_c_open = false;
} else if (!extern_c_open && mode == NameMangling::C) {
stream << R"INLINE_CODE(
#ifdef __cplusplus
extern "C" {
#endif
)INLINE_CODE";
extern_c_open = true;
}
}
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, const Expr &e) {
ostringstream oss;
if (type.is_handle() || e.type().is_handle()) {
// Use a c-style cast if either src or dest is a handle --
// note that although Halide declares a "Handle" to always be 64 bits,
// the source "handle" might actually be a 32-bit pointer (from
// a function parameter), so calling reinterpret<> (which just memcpy's)
// would be garbage-producing.
oss << "(" << print_type(type) << ")";
} else {
oss << "reinterpret<" << print_type(type) << ">";
}
// If we are generating a typed nullptr, just emit that as a literal, with no intermediate,
// to avoid ugly code like
//
// uint64_t _32 = (uint64_t)(0ull);
// auto *_33 = (void *)(_32);
//
// and instead just do
// auto *_33 = (void *)(nullptr);
if (type.is_handle() && is_const_zero(e)) {
oss << "(nullptr)";
} else {
oss << "(" << print_expr(e) << ")";
}
return oss.str();
}
string CodeGen_C::print_name(const string &name) {
return c_print_name(name);
}
namespace {
class ExternCallPrototypes : public IRGraphVisitor {
struct NamespaceOrCall {
const Call *call; // nullptr if this is a subnamespace
std::map<string, NamespaceOrCall> names;
NamespaceOrCall(const Call *call = nullptr)
: call(call) {
}
};
std::map<string, NamespaceOrCall> c_plus_plus_externs;
std::map<string, const Call *> c_externs;
std::set<std::string> processed;
std::set<std::string> internal_linkage;
std::set<std::string> destructors;
using IRGraphVisitor::visit;
void visit(const Call *op) override {
IRGraphVisitor::visit(op);
if (!processed.count(op->name)) {
if (op->call_type == Call::Extern || op->call_type == Call::PureExtern) {
c_externs.insert({op->name, op});
} else if (op->call_type == Call::ExternCPlusPlus) {
std::vector<std::string> namespaces;
std::string name = extract_namespaces(op->name, namespaces);
std::map<string, NamespaceOrCall> *namespace_map = &c_plus_plus_externs;
for (const auto &ns : namespaces) {
auto insertion = namespace_map->insert({ns, NamespaceOrCall()});
namespace_map = &insertion.first->second.names;
}
namespace_map->insert({name, NamespaceOrCall(op)});
}
processed.insert(op->name);
}
if (op->is_intrinsic(Call::register_destructor)) {
internal_assert(op->args.size() == 2);
const StringImm *fn = op->args[0].as<StringImm>();
internal_assert(fn);
destructors.insert(fn->value);
}
}
void visit(const Allocate *op) override {
IRGraphVisitor::visit(op);
if (!op->free_function.empty()) {
destructors.insert(op->free_function);
}
}
void emit_function_decl(ostream &stream, const Call *op, const std::string &name) const {
// op->name (rather than the name arg) since we need the fully-qualified C++ name
if (internal_linkage.count(op->name)) {
stream << "static ";
}
stream << type_to_c_type(op->type, /* append_space */ true) << name << "(";
if (function_takes_user_context(name)) {
stream << "void *";
if (!op->args.empty()) {
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 << ");\n";
}
void emit_namespace_or_call(ostream &stream, const NamespaceOrCall &ns_or_call, const std::string &name) const {
if (ns_or_call.call == nullptr) {
stream << "namespace " << name << " {\n";
for (const auto &ns_or_call_inner : ns_or_call.names) {
emit_namespace_or_call(stream, ns_or_call_inner.second, ns_or_call_inner.first);
}
stream << "} // namespace " << name << "\n";
} else {
emit_function_decl(stream, ns_or_call.call, name);
}
}
public:
ExternCallPrototypes() {
// Make sure we don't catch calls that are already in the global declarations
const char *strs[] = {(const char *)halide_c_template_CodeGen_C_prologue,
(const char *)halide_internal_runtime_header_HalideRuntime_h,
(const char *)halide_internal_initmod_inlined_c};
for (const char *str : strs) {
size_t j = 0;
for (size_t i = 0; str[i]; i++) {
char c = str[i];
if (c == '(' && i > j + 1) {
// Could be the end of a function_name.
string name(str + j + 1, i - j - 1);
processed.insert(name);
}
if (('A' <= c && c <= 'Z') ||
('a' <= c && c <= 'z') ||
c == '_' ||
('0' <= c && c <= '9')) {
// Could be part of a function name.
} else {
j = i;
}
}
}
}
void set_internal_linkage(const std::string &name) {
internal_linkage.insert(name);
}
bool has_c_declarations() const {
return !c_externs.empty() || !destructors.empty();
}
bool has_c_plus_plus_declarations() const {
return !c_plus_plus_externs.empty();
}
void emit_c_declarations(ostream &stream) const {
for (const auto &call : c_externs) {
emit_function_decl(stream, call.second, call.first);
}
for (const auto &d : destructors) {
stream << "void " << d << "(void *, void *);\n";
}
stream << "\n";
}
void emit_c_plus_plus_declarations(ostream &stream) const {
for (const auto &ns_or_call : c_plus_plus_externs) {
emit_namespace_or_call(stream, ns_or_call.second, ns_or_call.first);
}
stream << "\n";
}
};
} // namespace
void CodeGen_C::forward_declare_type_if_needed(const Type &t) {
if (!t.handle_type ||
forward_declared.count(t.handle_type) ||
t.handle_type->inner_name.cpp_type_type == halide_cplusplus_type_name::Simple) {
return;
}
for (const auto &ns : t.handle_type->namespaces) {
stream << "namespace " << ns << " { ";
}
switch (t.handle_type->inner_name.cpp_type_type) {
case halide_cplusplus_type_name::Simple:
// nothing
break;
case halide_cplusplus_type_name::Struct:
stream << "struct " << t.handle_type->inner_name.name << ";";
break;
case halide_cplusplus_type_name::Class:
stream << "class " << t.handle_type->inner_name.name << ";";
break;
case halide_cplusplus_type_name::Union:
stream << "union " << t.handle_type->inner_name.name << ";";
break;
case halide_cplusplus_type_name::Enum:
internal_error << "Passing pointers to enums is unsupported\n";
break;
}
for (const auto &ns : t.handle_type->namespaces) {
(void)ns;
stream << " }";
}
stream << "\n";
forward_declared.insert(t.handle_type);
}
void CodeGen_C::emit_argv_wrapper(const std::string &function_name,
const std::vector<LoweredArgument> &args) {
if (is_header_or_extern_decl()) {
stream << "\nHALIDE_FUNCTION_ATTRS\nint " << function_name << "_argv(void **args);\n";
return;
}
stream << "\nHALIDE_FUNCTION_ATTRS\nint " << function_name << "_argv(void **args) {\n";
indent += 1;
stream << get_indent() << "return " << function_name << "(\n";
indent += 1;
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer()) {
stream << get_indent() << "(halide_buffer_t *)args[" << i << "]";
} else {
stream << get_indent() << "*(" << type_to_c_type(args[i].type, false) << " const *)args[" << i << "]";
}
if (i + 1 < args.size()) {
stream << ",";
}
stream << "\n";
}
indent -= 1;
stream << ");\n";
indent -= 1;
stream << "}";
}
void CodeGen_C::emit_metadata_getter(const std::string &function_name,
const std::vector<LoweredArgument> &args,
const MetadataNameMap &metadata_name_map) {
if (is_header_or_extern_decl()) {
stream << "\nHALIDE_FUNCTION_ATTRS\nconst struct halide_filter_metadata_t *" << function_name << "_metadata();\n";
return;
}
auto map_name = [&metadata_name_map](const std::string &from) -> std::string {
auto it = metadata_name_map.find(from);
return it == metadata_name_map.end() ? from : it->second;
};
stream << "\nHALIDE_FUNCTION_ATTRS\nconst struct halide_filter_metadata_t *" << function_name << "_metadata() {\n";
indent += 1;
static const char *const kind_names[] = {
"halide_argument_kind_input_scalar",
"halide_argument_kind_input_buffer",
"halide_argument_kind_output_buffer",
};
static const char *const type_code_names[] = {
"halide_type_int",
"halide_type_uint",
"halide_type_float",
"halide_type_handle",
"halide_type_bfloat",
};
std::set<int64_t> constant_int64_in_use;
const auto emit_constant_int64 = [this, &constant_int64_in_use](Expr e) -> std::string {
if (!e.defined()) {
return "nullptr";
}
internal_assert(!e.type().is_handle()) << "Should never see Handle types here.";
if (!is_const(e)) {
e = simplify(e);
internal_assert(is_const(e)) << "Should only see constant values here.";
}
const IntImm *int_imm = e.as<IntImm>();
internal_assert(int_imm && int_imm->type == Int(64));
const std::string id = "const_" + std::to_string(int_imm->value);
if (!constant_int64_in_use.count(int_imm->value)) {
stream << get_indent() << "static const int64_t " << id << " = " << int_imm->value << "LL;\n";
constant_int64_in_use.insert(int_imm->value);
}
return "&" + id;
};
int next_scalar_value_id = 0;
const auto emit_constant_scalar_value = [this, &next_scalar_value_id](Expr e) -> std::string {
if (!e.defined()) {
return "nullptr";
}
internal_assert(!e.type().is_handle()) << "Should never see Handle types here.";
if (!is_const(e)) {
e = simplify(e);
internal_assert(is_const(e)) << "Should only see constant values here.";
}
const IntImm *int_imm = e.as<IntImm>();
const UIntImm *uint_imm = e.as<UIntImm>();
const FloatImm *float_imm = e.as<FloatImm>();
internal_assert(int_imm || uint_imm || float_imm);
std::string value;
if (int_imm) {
value = std::to_string(int_imm->value);
} else if (uint_imm) {
value = std::to_string(uint_imm->value);
} else if (float_imm) {
value = std::to_string(float_imm->value);
}
std::string c_type = type_to_c_type(e.type(), false);
std::string id = "halide_scalar_value_" + std::to_string(next_scalar_value_id++);
// It's important that we allocate a full scalar_value_t_type here,
// even if the type of the value is smaller; downstream consumers should
// be able to correctly load an entire scalar_value_t_type regardless of its
// type, and if we emit just (say) a uint8 value here, the pointer may be
// misaligned and/or the storage after may be unmapped. We'll fake it by
// making a constant array of the elements we need, setting the first to the
// constant we want, and setting the rest to all-zeros. (This happens to work because
// sizeof(halide_scalar_value_t) is evenly divisible by sizeof(any-union-field.)
const size_t value_size = e.type().bytes();
internal_assert(value_size > 0 && value_size <= sizeof(halide_scalar_value_t));
const size_t array_size = sizeof(halide_scalar_value_t) / value_size;
internal_assert(array_size * value_size == sizeof(halide_scalar_value_t));
stream << get_indent() << "alignas(alignof(halide_scalar_value_t)) static const " << c_type << " " << id << "[" << array_size << "] = {" << value;
for (size_t i = 1; i < array_size; i++) {
stream << ", 0";
}
stream << "};\n";
return "(const halide_scalar_value_t *)&" + id;
};
for (const auto &arg : args) {
const auto legalized_name = c_print_name(map_name(arg.name));
auto argument_estimates = arg.argument_estimates;
if (arg.type.is_handle()) {
// Handle values are always emitted into metadata as "undefined", regardless of
// what sort of Expr is provided.
argument_estimates = ArgumentEstimates{};
}
const auto defined_count = [](const Region &r) -> size_t {
size_t c = 0;
for (const auto &be : r) {
c += be.min.defined() ? 1 : 0;
c += be.extent.defined() ? 1 : 0;
}
return c;
};
std::string buffer_estimates_array_ptr = "nullptr";
if (arg.is_buffer() && defined_count(argument_estimates.buffer_estimates) > 0) {
internal_assert((int)argument_estimates.buffer_estimates.size() == arg.dimensions);
std::vector<std::string> constants;
for (const auto &be : argument_estimates.buffer_estimates) {
Expr min = be.min;
if (min.defined()) {
min = cast<int64_t>(min);
}
Expr extent = be.extent;
if (extent.defined()) {
extent = cast<int64_t>(extent);
}
constants.push_back(emit_constant_int64(min));
constants.push_back(emit_constant_int64(extent));
}
stream << get_indent() << "static const int64_t * const buffer_estimates_" << legalized_name << "[" << (int)arg.dimensions * 2 << "] = {\n";
indent += 1;
for (const auto &c : constants) {
stream << get_indent() << c << ",\n";
}
indent -= 1;
stream << get_indent() << "};\n";
} else {
stream << get_indent() << "int64_t const *const *buffer_estimates_" << legalized_name << " = nullptr;\n";
}
auto scalar_def = emit_constant_scalar_value(argument_estimates.scalar_def);
auto scalar_min = emit_constant_scalar_value(argument_estimates.scalar_min);
auto scalar_max = emit_constant_scalar_value(argument_estimates.scalar_max);
auto scalar_estimate = emit_constant_scalar_value(argument_estimates.scalar_estimate);
stream << get_indent() << "const halide_scalar_value_t *scalar_def_" << legalized_name << " = " << scalar_def << ";\n";
stream << get_indent() << "const halide_scalar_value_t *scalar_min_" << legalized_name << " = " << scalar_min << ";\n";
stream << get_indent() << "const halide_scalar_value_t *scalar_max_" << legalized_name << " = " << scalar_max << ";\n";
stream << get_indent() << "const halide_scalar_value_t *scalar_estimate_" << legalized_name << " = " << scalar_estimate << ";\n";
}
stream << get_indent() << "static const halide_filter_argument_t args[" << args.size() << "] = {\n";
indent += 1;
for (const auto &arg : args) {
const auto name = map_name(arg.name);
const auto legalized_name = c_print_name(name);
stream << get_indent() << "{\n";
indent += 1;
stream << get_indent() << "\"" << name << "\",\n";
internal_assert(arg.kind < sizeof(kind_names) / sizeof(kind_names[0]));
stream << get_indent() << kind_names[arg.kind] << ",\n";
stream << get_indent() << (int)arg.dimensions << ",\n";
internal_assert(arg.type.code() < sizeof(type_code_names) / sizeof(type_code_names[0]));
stream << get_indent() << "{" << type_code_names[arg.type.code()] << ", " << arg.type.bits() << ", " << arg.type.lanes() << "},\n";
stream << get_indent() << "scalar_def_" << legalized_name << ",\n";
stream << get_indent() << "scalar_min_" << legalized_name << ",\n";
stream << get_indent() << "scalar_max_" << legalized_name << ",\n";
stream << get_indent() << "scalar_estimate_" << legalized_name << ",\n";
stream << get_indent() << "buffer_estimates_" << legalized_name << ",\n";
stream << get_indent() << "},\n";
indent -= 1;
}
stream << get_indent() << "};\n";
indent -= 1;
stream << get_indent() << "static const halide_filter_metadata_t md = {\n";
indent += 1;
stream << get_indent() << "halide_filter_metadata_t::VERSION,\n";
stream << get_indent() << args.size() << ",\n";
stream << get_indent() << "args,\n";
stream << get_indent() << "\"" << target.to_string() << "\",\n";
stream << get_indent() << "\"" << function_name << "\",\n";
stream << get_indent() << "};\n";
indent -= 1;
stream << get_indent() << "return &md;\n";
indent -= 1;
stream << "}\n";
}
void CodeGen_C::emit_constexpr_function_info(const std::string &function_name,
const std::vector<LoweredArgument> &args,
const MetadataNameMap &metadata_name_map) {
internal_assert(!extern_c_open)
<< "emit_constexpr_function_info() must not be called from inside an extern \"C\" block";
if (!is_header()) {
return;
}
auto map_name = [&metadata_name_map](const std::string &from) -> std::string {
auto it = metadata_name_map.find(from);
return it == metadata_name_map.end() ? from : it->second;
};
static const std::array<const char *, 3> kind_names = {
"::HalideFunctionInfo::InputScalar",
"::HalideFunctionInfo::InputBuffer",
"::HalideFunctionInfo::OutputBuffer",
};
static const std::array<const char *, 5> type_code_names = {
"halide_type_int",
"halide_type_uint",
"halide_type_float",
"halide_type_handle",
"halide_type_bfloat",
};
stream << constexpr_argument_info_docs;
stream << "inline constexpr std::array<::HalideFunctionInfo::ArgumentInfo, " << args.size() << "> "
<< function_name << "_argument_info() {\n";
indent += 1;
stream << get_indent() << "return {{\n";
indent += 1;
for (const auto &arg : args) {
internal_assert(arg.kind < kind_names.size());
internal_assert(arg.type.code() < type_code_names.size());
const auto name = map_name(arg.name);
stream << get_indent() << "{\"" << name << "\", " << kind_names[arg.kind] << ", " << (int)arg.dimensions
<< ", halide_type_t{" << type_code_names[arg.type.code()] << ", " << arg.type.bits()
<< ", " << arg.type.lanes() << "}},\n";
}
indent -= 1;
stream << get_indent() << "}};\n";
indent -= 1;
internal_assert(indent == 0);
stream << "}\n";
}
void CodeGen_C::emit_halide_free_helper(const std::string &alloc_name, const std::string &free_function) {
stream << get_indent() << "HalideFreeHelper<" << free_function << "> "
<< alloc_name << "_free(_ucon, " << alloc_name << ");\n";
}
void CodeGen_C::compile(const Module &input) {
add_platform_prologue();
TypeInfoGatherer type_info;
for (const auto &f : input.functions()) {
if (f.body.defined()) {
f.body.accept(&type_info);
}
}
uses_gpu_for_loops = (type_info.for_types_used.count(ForType::GPUBlock) ||
type_info.for_types_used.count(ForType::GPUThread) ||
type_info.for_types_used.count(ForType::GPULane));
// Forward-declare all the types we need; this needs to happen before
// we emit function prototypes, since those may need the types.
if (output_kind != CPlusPlusFunctionInfoHeader) {
stream << "\n";
for (const auto &f : input.functions()) {
for (const auto &arg : f.args) {
forward_declare_type_if_needed(arg.type);
}
}
stream << "\n";
}
if (!is_header_or_extern_decl()) {
add_vector_typedefs(type_info.vector_types_used);
// Emit prototypes for all external and internal-only functions.
// Gather them up and do them all up front, to reduce duplicates,
// and to make it simpler to get internal-linkage functions correct.
ExternCallPrototypes e;
for (const auto &f : input.functions()) {
f.body.accept(&e);
if (f.linkage == LinkageType::Internal) {
// We can't tell at the call site if a LoweredFunc is intended to be internal
// or not, so mark them explicitly.
e.set_internal_linkage(f.name);
}
}
if (e.has_c_plus_plus_declarations()) {
set_name_mangling_mode(NameMangling::CPlusPlus);
e.emit_c_plus_plus_declarations(stream);
}
if (e.has_c_declarations()) {
set_name_mangling_mode(NameMangling::C);
e.emit_c_declarations(stream);
}
// Add a check to make sure we compile strict_float C++ code appropriately
if (input.any_strict_float()) {
stream << "#if defined(__FAST_MATH__) || defined(_M_FP_FAST)\n"
<< "#warning \"This Halide module uses strict float intrinsics or the strict_float target flag, but is being compiled with fast-math flags. Floating point math will not actually be strict.\"\n"
<< "#endif\n";
}
}
for (const auto &b : input.buffers()) {
compile(b);
}
const auto metadata_name_map = input.get_metadata_name_map();
for (const auto &f : input.functions()) {
compile(f, metadata_name_map);
}
}
Stmt CodeGen_C::preprocess_function_body(const Stmt &stmt) {
return stmt;
}
void CodeGen_C::compile(const LoweredFunc &f, const MetadataNameMap &metadata_name_map) {
// Don't put non-external function declarations in headers.
if (is_header_or_extern_decl() && f.linkage == LinkageType::Internal) {
return;
}
const std::vector<LoweredArgument> &args = f.args;
have_user_context = false;
for (const auto &arg : args) {
// TODO: check that its type is void *?
have_user_context |= (arg.name == "__user_context");
}
NameMangling name_mangling = f.name_mangling;
if (name_mangling == NameMangling::Default) {
name_mangling = (target.has_feature(Target::CPlusPlusMangling) || output_kind == CPlusPlusFunctionInfoHeader ? NameMangling::CPlusPlus : NameMangling::C);
}
set_name_mangling_mode(name_mangling);
std::vector<std::string> namespaces;
std::string simple_name = c_print_name(extract_namespaces(f.name, namespaces), false);
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()) {
for (const auto &ns : namespaces) {
stream << "namespace " << ns << " {\n";
}
stream << "\n";
}
if (output_kind != CPlusPlusFunctionInfoHeader) {
const auto emit_arg_decls = [&](const Type &ucon_type = Type()) {