-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathCodeGen_LLVM.cpp
5147 lines (4528 loc) · 208 KB
/
CodeGen_LLVM.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 <limits>
#include <memory>
#include <sstream>
#include "CPlusPlusMangle.h"
#include "CSE.h"
#include "CodeGen_Internal.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_Posix.h"
#include "CodeGen_Targets.h"
#include "CompilerLogger.h"
#include "Debug.h"
#include "Deinterleave.h"
#include "EmulateFloat16Math.h"
#include "ExprUsesVar.h"
#include "FindIntrinsics.h"
#include "IREquality.h"
#include "IROperator.h"
#include "IRPrinter.h"
#include "IntegerDivisionTable.h"
#include "JITModule.h"
#include "LLVM_Headers.h"
#include "LLVM_Runtime_Linker.h"
#include "Lerp.h"
#include "MatlabWrapper.h"
#include "Pipeline.h"
#include "Simplify.h"
#include "Util.h"
// MSVC won't set __cplusplus correctly unless certain compiler flags are set
// (and CMake doesn't set those flags for you even if you specify C++17),
// so we need to check against _MSVC_LANG as well, for completeness.
#if !(__cplusplus >= 201703L || _MSVC_LANG >= 201703L)
#error "Halide requires C++17 or later; please upgrade your compiler."
#endif
namespace Halide {
std::unique_ptr<llvm::Module> codegen_llvm(const Module &module, llvm::LLVMContext &context) {
std::unique_ptr<Internal::CodeGen_LLVM> cg(Internal::CodeGen_LLVM::new_for_target(module.target(), context));
return cg->compile(module);
}
namespace Internal {
using namespace llvm;
using std::map;
using std::ostringstream;
using std::pair;
using std::string;
using std::vector;
// Define a local empty inline function for each target
// to disable initialization.
#define LLVM_TARGET(target) \
inline void Initialize##target##Target() { \
}
#include <llvm/Config/Targets.def>
#undef LLVM_TARGET
#define LLVM_ASM_PARSER(target) \
inline void Initialize##target##AsmParser() { \
}
#include <llvm/Config/AsmParsers.def>
#undef LLVM_ASM_PARSER
#define LLVM_ASM_PRINTER(target) \
inline void Initialize##target##AsmPrinter() { \
}
#include <llvm/Config/AsmPrinters.def>
#undef LLVM_ASM_PRINTER
#define InitializeTarget(target) \
LLVMInitialize##target##Target(); \
LLVMInitialize##target##TargetInfo(); \
LLVMInitialize##target##TargetMC();
#define InitializeAsmParser(target) \
LLVMInitialize##target##AsmParser();
#define InitializeAsmPrinter(target) \
LLVMInitialize##target##AsmPrinter();
// Override above empty init function with macro for supported targets.
#ifdef WITH_ARM
#define InitializeARMTarget() InitializeTarget(ARM)
#define InitializeARMAsmParser() InitializeAsmParser(ARM)
#define InitializeARMAsmPrinter() InitializeAsmPrinter(ARM)
#endif
#ifdef WITH_NVPTX
#define InitializeNVPTXTarget() InitializeTarget(NVPTX)
// #define InitializeNVPTXAsmParser() InitializeAsmParser(NVPTX) // there is no ASM parser for NVPTX
#define InitializeNVPTXAsmPrinter() InitializeAsmPrinter(NVPTX)
#endif
#ifdef WITH_AMDGPU
#define InitializeAMDGPUTarget() InitializeTarget(AMDGPU)
#define InitializeAMDGPUAsmParser() InitializeAsmParser(AMDGPU)
#define InitializeAMDGPUAsmPrinter() InitializeAsmParser(AMDGPU)
#endif
#ifdef WITH_AARCH64
#define InitializeAArch64Target() InitializeTarget(AArch64)
#define InitializeAArch64AsmParser() InitializeAsmParser(AArch64)
#define InitializeAArch64AsmPrinter() InitializeAsmPrinter(AArch64)
#endif
#ifdef WITH_HEXAGON
#define InitializeHexagonTarget() InitializeTarget(Hexagon)
#define InitializeHexagonAsmParser() InitializeAsmParser(Hexagon)
#define InitializeHexagonAsmPrinter() InitializeAsmPrinter(Hexagon)
#endif
#ifdef WITH_MIPS
#define InitializeMipsTarget() InitializeTarget(Mips)
#define InitializeMipsAsmParser() InitializeAsmParser(Mips)
#define InitializeMipsAsmPrinter() InitializeAsmPrinter(Mips)
#endif
#ifdef WITH_POWERPC
#define InitializePowerPCTarget() InitializeTarget(PowerPC)
#define InitializePowerPCAsmParser() InitializeAsmParser(PowerPC)
#define InitializePowerPCAsmPrinter() InitializeAsmPrinter(PowerPC)
#endif
#ifdef WITH_RISCV
#define InitializeRISCVTarget() InitializeTarget(RISCV)
#define InitializeRISCVAsmParser() InitializeAsmParser(RISCV)
#define InitializeRISCVAsmPrinter() InitializeAsmPrinter(RISCV)
#endif
#ifdef WITH_X86
#define InitializeX86Target() InitializeTarget(X86)
#define InitializeX86AsmParser() InitializeAsmParser(X86)
#define InitializeX86AsmPrinter() InitializeAsmPrinter(X86)
#endif
#ifdef WITH_WEBASSEMBLY
#define InitializeWebAssemblyTarget() InitializeTarget(WebAssembly)
#define InitializeWebAssemblyAsmParser() InitializeAsmParser(WebAssembly)
#define InitializeWebAssemblyAsmPrinter() InitializeAsmPrinter(WebAssembly)
#endif
namespace {
llvm::Value *CreateConstGEP1_32(IRBuilderBase *builder, Value *ptr, unsigned index) {
#if LLVM_VERSION >= 130
return builder->CreateConstGEP1_32(ptr->getType()->getScalarType()->getPointerElementType(), ptr, index);
#else
return builder->CreateConstGEP1_32(ptr, index);
#endif
}
llvm::Value *CreateInBoundsGEP(IRBuilderBase *builder, Value *ptr, ArrayRef<Value *> index_list) {
#if LLVM_VERSION >= 130
return builder->CreateInBoundsGEP(ptr->getType()->getScalarType()->getPointerElementType(), ptr, index_list);
#else
return builder->CreateInBoundsGEP(ptr, index_list);
#endif
}
// Get the LLVM linkage corresponding to a Halide linkage type.
llvm::GlobalValue::LinkageTypes llvm_linkage(LinkageType t) {
// TODO(dsharlet): For some reason, marking internal functions as
// private linkage on OSX is causing some of the static tests to
// fail. Figure out why so we can remove this.
return llvm::GlobalValue::ExternalLinkage;
// switch (t) {
// case LinkageType::ExternalPlusMetadata:
// case LinkageType::External:
// return llvm::GlobalValue::ExternalLinkage;
// default:
// return llvm::GlobalValue::PrivateLinkage;
// }
}
} // namespace
CodeGen_LLVM::CodeGen_LLVM(const Target &t)
: function(nullptr), context(nullptr),
builder(nullptr),
value(nullptr),
very_likely_branch(nullptr),
default_fp_math_md(nullptr),
strict_fp_math_md(nullptr),
target(t),
void_t(nullptr), i1_t(nullptr), i8_t(nullptr),
i16_t(nullptr), i32_t(nullptr), i64_t(nullptr),
f16_t(nullptr), f32_t(nullptr), f64_t(nullptr),
halide_buffer_t_type(nullptr),
metadata_t_type(nullptr),
argument_t_type(nullptr),
scalar_value_t_type(nullptr),
device_interface_t_type(nullptr),
pseudostack_slot_t_type(nullptr),
wild_u1x_(Variable::make(UInt(1, 0), "*")),
wild_i8x_(Variable::make(Int(8, 0), "*")),
wild_u8x_(Variable::make(UInt(8, 0), "*")),
wild_i16x_(Variable::make(Int(16, 0), "*")),
wild_u16x_(Variable::make(UInt(16, 0), "*")),
wild_i32x_(Variable::make(Int(32, 0), "*")),
wild_u32x_(Variable::make(UInt(32, 0), "*")),
wild_i64x_(Variable::make(Int(64, 0), "*")),
wild_u64x_(Variable::make(UInt(64, 0), "*")),
wild_f32x_(Variable::make(Float(32, 0), "*")),
wild_f64x_(Variable::make(Float(64, 0), "*")),
wild_u1_(Variable::make(UInt(1), "*")),
wild_i8_(Variable::make(Int(8), "*")),
wild_u8_(Variable::make(UInt(8), "*")),
wild_i16_(Variable::make(Int(16), "*")),
wild_u16_(Variable::make(UInt(16), "*")),
wild_i32_(Variable::make(Int(32), "*")),
wild_u32_(Variable::make(UInt(32), "*")),
wild_i64_(Variable::make(Int(64), "*")),
wild_u64_(Variable::make(UInt(64), "*")),
wild_f32_(Variable::make(Float(32), "*")),
wild_f64_(Variable::make(Float(64), "*")),
inside_atomic_mutex_node(false),
emit_atomic_stores(false),
destructor_block(nullptr),
strict_float(t.has_feature(Target::StrictFloat)),
llvm_large_code_model(t.has_feature(Target::LLVMLargeCodeModel)) {
initialize_llvm();
}
void CodeGen_LLVM::set_context(llvm::LLVMContext &context) {
this->context = &context;
}
std::unique_ptr<CodeGen_LLVM> CodeGen_LLVM::new_for_target(const Target &target, llvm::LLVMContext &context) {
std::unique_ptr<CodeGen_LLVM> result;
if (target.arch == Target::X86) {
result = new_CodeGen_X86(target);
} else if (target.arch == Target::ARM) {
result = new_CodeGen_ARM(target);
} else if (target.arch == Target::MIPS) {
result = new_CodeGen_MIPS(target);
} else if (target.arch == Target::POWERPC) {
result = new_CodeGen_PowerPC(target);
} else if (target.arch == Target::Hexagon) {
result = new_CodeGen_Hexagon(target);
} else if (target.arch == Target::WebAssembly) {
result = new_CodeGen_WebAssembly(target);
} else if (target.arch == Target::RISCV) {
result = new_CodeGen_RISCV(target);
}
user_assert(result) << "Unknown target architecture: " << target.to_string() << "\n";
result->set_context(context);
return result;
}
void CodeGen_LLVM::initialize_llvm() {
static std::once_flag init_llvm_once;
std::call_once(init_llvm_once, []() {
// You can hack in command-line args to llvm with the
// environment variable HL_LLVM_ARGS, e.g. HL_LLVM_ARGS="-print-after-all"
std::string args = get_env_variable("HL_LLVM_ARGS");
if (!args.empty()) {
vector<std::string> arg_vec = split_string(args, " ");
vector<const char *> c_arg_vec;
c_arg_vec.push_back("llc");
for (const std::string &s : arg_vec) {
c_arg_vec.push_back(s.c_str());
}
cl::ParseCommandLineOptions((int)(c_arg_vec.size()), &c_arg_vec[0], "Halide compiler\n");
}
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
InitializeNativeTargetAsmParser();
#define LLVM_TARGET(target) \
Initialize##target##Target();
#include <llvm/Config/Targets.def>
#undef LLVM_TARGET
#define LLVM_ASM_PARSER(target) \
Initialize##target##AsmParser();
#include <llvm/Config/AsmParsers.def>
#undef LLVM_ASM_PARSER
#define LLVM_ASM_PRINTER(target) \
Initialize##target##AsmPrinter();
#include <llvm/Config/AsmPrinters.def>
#include <utility>
#undef LLVM_ASM_PRINTER
});
}
void CodeGen_LLVM::init_context() {
// Ensure our IRBuilder is using the current context.
delete builder;
builder = new IRBuilder<>(*context);
// Branch weights for very likely branches
llvm::MDBuilder md_builder(*context);
very_likely_branch = md_builder.createBranchWeights(1 << 30, 0);
default_fp_math_md = md_builder.createFPMath(0.0);
strict_fp_math_md = md_builder.createFPMath(0.0);
builder->setDefaultFPMathTag(default_fp_math_md);
llvm::FastMathFlags fast_flags;
fast_flags.setNoNaNs();
fast_flags.setNoInfs();
fast_flags.setNoSignedZeros();
// Don't use approximate reciprocals for division. It's too inaccurate even for Halide.
// fast_flags.setAllowReciprocal();
// Theoretically, setAllowReassoc could be setUnsafeAlgebra for earlier versions, but that
// turns on all the flags.
fast_flags.setAllowReassoc();
fast_flags.setAllowContract(true);
fast_flags.setApproxFunc();
builder->setFastMathFlags(fast_flags);
// Define some types
void_t = llvm::Type::getVoidTy(*context);
i1_t = llvm::Type::getInt1Ty(*context);
i8_t = llvm::Type::getInt8Ty(*context);
i16_t = llvm::Type::getInt16Ty(*context);
i32_t = llvm::Type::getInt32Ty(*context);
i64_t = llvm::Type::getInt64Ty(*context);
f16_t = llvm::Type::getHalfTy(*context);
f32_t = llvm::Type::getFloatTy(*context);
f64_t = llvm::Type::getDoubleTy(*context);
}
void CodeGen_LLVM::init_module() {
init_context();
// Start with a module containing the initial module for this target.
module = get_initial_module_for_target(target, context);
}
void CodeGen_LLVM::add_external_code(const Module &halide_module) {
for (const ExternalCode &code_blob : halide_module.external_code()) {
if (code_blob.is_for_cpu_target(get_target())) {
add_bitcode_to_module(context, *module, code_blob.contents(), code_blob.name());
}
}
}
CodeGen_LLVM::~CodeGen_LLVM() {
delete builder;
}
namespace {
struct MangledNames {
string simple_name;
string extern_name;
string argv_name;
string metadata_name;
};
MangledNames get_mangled_names(const std::string &name,
LinkageType linkage,
NameMangling mangling,
const std::vector<LoweredArgument> &args,
const Target &target) {
std::vector<std::string> namespaces;
MangledNames names;
names.simple_name = extract_namespaces(name, namespaces);
names.extern_name = names.simple_name;
names.argv_name = names.simple_name + "_argv";
names.metadata_name = names.simple_name + "_metadata";
if (linkage != LinkageType::Internal &&
((mangling == NameMangling::Default &&
target.has_feature(Target::CPlusPlusMangling)) ||
mangling == NameMangling::CPlusPlus)) {
std::vector<ExternFuncArgument> mangle_args;
for (const auto &arg : args) {
if (arg.kind == Argument::InputScalar) {
mangle_args.emplace_back(make_zero(arg.type));
} else if (arg.kind == Argument::InputBuffer ||
arg.kind == Argument::OutputBuffer) {
mangle_args.emplace_back(Buffer<>());
}
}
names.extern_name = cplusplus_function_mangled_name(names.simple_name, namespaces, type_of<int>(), mangle_args, target);
halide_handle_cplusplus_type inner_type(halide_cplusplus_type_name(halide_cplusplus_type_name::Simple, "void"), {}, {},
{halide_handle_cplusplus_type::Pointer, halide_handle_cplusplus_type::Pointer});
Type void_star_star(Handle(1, &inner_type));
names.argv_name = cplusplus_function_mangled_name(names.argv_name, namespaces, type_of<int>(), {ExternFuncArgument(make_zero(void_star_star))}, target);
names.metadata_name = cplusplus_function_mangled_name(names.metadata_name, namespaces, type_of<const struct halide_filter_metadata_t *>(), {}, target);
}
return names;
}
MangledNames get_mangled_names(const LoweredFunc &f, const Target &target) {
return get_mangled_names(f.name, f.linkage, f.name_mangling, f.args, target);
}
} // namespace
llvm::FunctionType *CodeGen_LLVM::signature_to_type(const ExternSignature &signature) {
internal_assert(void_t != nullptr && halide_buffer_t_type != nullptr);
llvm::Type *ret_type =
signature.is_void_return() ? void_t : llvm_type_of(upgrade_type_for_argument_passing(signature.ret_type()));
std::vector<llvm::Type *> llvm_arg_types;
for (const Type &t : signature.arg_types()) {
if (t == type_of<struct halide_buffer_t *>()) {
llvm_arg_types.push_back(halide_buffer_t_type->getPointerTo());
} else {
llvm_arg_types.push_back(llvm_type_of(upgrade_type_for_argument_passing(t)));
}
}
return llvm::FunctionType::get(ret_type, llvm_arg_types, false);
}
/*static*/
std::unique_ptr<llvm::Module> CodeGen_LLVM::compile_trampolines(
const Target &target,
llvm::LLVMContext &context,
const std::string &suffix,
const std::vector<std::pair<std::string, ExternSignature>> &externs) {
std::unique_ptr<CodeGen_LLVM> codegen(new_for_target(target, context));
codegen->init_codegen("trampolines" + suffix);
for (const std::pair<std::string, ExternSignature> &e : externs) {
const std::string &callee_name = e.first;
const std::string wrapper_name = callee_name + suffix;
llvm::FunctionType *fn_type = codegen->signature_to_type(e.second);
// callee might already be present for builtins, e.g. halide_print
llvm::Function *callee = codegen->module->getFunction(callee_name);
if (!callee) {
callee = llvm::Function::Create(fn_type, llvm::Function::ExternalLinkage, callee_name, codegen->module.get());
}
codegen->add_argv_wrapper(callee, wrapper_name, /*result_in_argv*/ true);
}
return codegen->finish_codegen();
}
void CodeGen_LLVM::init_codegen(const std::string &name, bool any_strict_float) {
init_module();
internal_assert(module && context);
debug(1) << "Target triple of initial module: " << module->getTargetTriple() << "\n";
module->setModuleIdentifier(name);
// Add some target specific info to the module as metadata.
module->addModuleFlag(llvm::Module::Warning, "halide_use_soft_float_abi", use_soft_float_abi() ? 1 : 0);
module->addModuleFlag(llvm::Module::Warning, "halide_mcpu", MDString::get(*context, mcpu()));
module->addModuleFlag(llvm::Module::Warning, "halide_mattrs", MDString::get(*context, mattrs()));
module->addModuleFlag(llvm::Module::Warning, "halide_mabi", MDString::get(*context, mabi()));
module->addModuleFlag(llvm::Module::Warning, "halide_use_pic", use_pic() ? 1 : 0);
module->addModuleFlag(llvm::Module::Warning, "halide_use_large_code_model", llvm_large_code_model ? 1 : 0);
module->addModuleFlag(llvm::Module::Warning, "halide_per_instruction_fast_math_flags", any_strict_float);
// Ensure some types we need are defined
halide_buffer_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_buffer_t");
internal_assert(halide_buffer_t_type) << "Did not find halide_buffer_t in initial module";
type_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_type_t");
internal_assert(type_t_type) << "Did not find halide_type_t in initial module";
dimension_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_dimension_t");
internal_assert(dimension_t_type) << "Did not find halide_dimension_t in initial module";
metadata_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_filter_metadata_t");
internal_assert(metadata_t_type) << "Did not find halide_filter_metadata_t in initial module";
argument_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_filter_argument_t");
internal_assert(argument_t_type) << "Did not find halide_filter_argument_t in initial module";
scalar_value_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_scalar_value_t");
internal_assert(scalar_value_t_type) << "Did not find halide_scalar_value_t in initial module";
device_interface_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_device_interface_t");
internal_assert(device_interface_t_type) << "Did not find halide_device_interface_t in initial module";
pseudostack_slot_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_pseudostack_slot_t");
internal_assert(pseudostack_slot_t_type) << "Did not find halide_pseudostack_slot_t in initial module";
semaphore_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_semaphore_t");
internal_assert(semaphore_t_type) << "Did not find halide_semaphore_t in initial module";
semaphore_acquire_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_semaphore_acquire_t");
internal_assert(semaphore_acquire_t_type) << "Did not find halide_semaphore_acquire_t in initial module";
parallel_task_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_parallel_task_t");
internal_assert(parallel_task_t_type) << "Did not find halide_parallel_task_t in initial module";
}
std::unique_ptr<llvm::Module> CodeGen_LLVM::compile(const Module &input) {
init_codegen(input.name(), input.any_strict_float());
internal_assert(module && context && builder)
<< "The CodeGen_LLVM subclass should have made an initial module before calling CodeGen_LLVM::compile\n";
add_external_code(input);
// Generate the code for this module.
debug(1) << "Generating llvm bitcode...\n";
for (const auto &b : input.buffers()) {
compile_buffer(b);
}
for (const auto &f : input.functions()) {
const auto names = get_mangled_names(f, get_target());
run_with_large_stack([&]() {
compile_func(f, names.simple_name, names.extern_name);
});
// If the Func is externally visible, also create the argv wrapper and metadata.
// (useful for calling from JIT and other machine interfaces).
if (f.linkage == LinkageType::ExternalPlusMetadata) {
llvm::Function *wrapper = add_argv_wrapper(function, names.argv_name);
llvm::Function *metadata_getter = embed_metadata_getter(names.metadata_name,
names.simple_name, f.args, input.get_metadata_name_map());
if (target.has_feature(Target::Matlab)) {
define_matlab_wrapper(module.get(), wrapper, metadata_getter);
}
}
}
debug(2) << module.get() << "\n";
return finish_codegen();
}
std::unique_ptr<llvm::Module> CodeGen_LLVM::finish_codegen() {
// Verify the module is ok
internal_assert(!verifyModule(*module, &llvm::errs()));
debug(2) << "Done generating llvm bitcode\n";
// Optimize
CodeGen_LLVM::optimize_module();
if (target.has_feature(Target::EmbedBitcode)) {
std::string halide_command = "halide target=" + target.to_string();
embed_bitcode(module.get(), halide_command);
}
// Disown the module and return it.
return std::move(module);
}
void CodeGen_LLVM::begin_func(LinkageType linkage, const std::string &name,
const std::string &extern_name, const std::vector<LoweredArgument> &args) {
current_function_args = args;
// Deduce the types of the arguments to our function
vector<llvm::Type *> arg_types(args.size());
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer()) {
arg_types[i] = halide_buffer_t_type->getPointerTo();
} else {
arg_types[i] = llvm_type_of(upgrade_type_for_argument_passing(args[i].type));
}
}
FunctionType *func_t = FunctionType::get(i32_t, arg_types, false);
// Make our function. There may already be a declaration of it.
function = module->getFunction(extern_name);
if (!function) {
function = llvm::Function::Create(func_t, llvm_linkage(linkage), extern_name, module.get());
} else {
user_assert(function->isDeclaration())
<< "Another function with the name " << extern_name
<< " already exists in the same module\n";
if (func_t != function->getFunctionType()) {
std::cerr << "Desired function type for " << extern_name << ":\n";
func_t->print(dbgs(), true);
std::cerr << "Declared function type of " << extern_name << ":\n";
function->getFunctionType()->print(dbgs(), true);
user_error << "Cannot create a function with a declaration of mismatched type.\n";
}
}
set_function_attributes_for_target(function, target);
// Mark the buffer args as no alias
for (size_t i = 0; i < args.size(); i++) {
if (args[i].is_buffer()) {
function->addParamAttr(i, Attribute::NoAlias);
}
}
debug(1) << "Generating llvm bitcode prolog for function " << name << "...\n";
// Null out the destructor block.
destructor_block = nullptr;
// Make the initial basic block
BasicBlock *block = BasicBlock::Create(*context, "entry", function);
builder->SetInsertPoint(block);
// Put the arguments in the symbol table
{
size_t i = 0;
for (auto &arg : function->args()) {
if (args[i].is_buffer()) {
sym_push(args[i].name + ".buffer", &arg);
} else {
Type passed_type = upgrade_type_for_argument_passing(args[i].type);
if (args[i].type != passed_type) {
llvm::Value *a = builder->CreateBitCast(&arg, llvm_type_of(args[i].type));
sym_push(args[i].name, a);
} else {
sym_push(args[i].name, &arg);
}
}
i++;
}
}
}
void CodeGen_LLVM::end_func(const std::vector<LoweredArgument> &args) {
return_with_error_code(ConstantInt::get(i32_t, 0));
// Remove the arguments from the symbol table
for (const auto &arg : args) {
if (arg.is_buffer()) {
sym_pop(arg.name + ".buffer");
} else {
sym_pop(arg.name);
}
}
internal_assert(!verifyFunction(*function, &llvm::errs()));
current_function_args.clear();
}
void CodeGen_LLVM::compile_func(const LoweredFunc &f, const std::string &simple_name,
const std::string &extern_name) {
// Generate the function declaration and argument unpacking code.
begin_func(f.linkage, simple_name, extern_name, f.args);
// If building with MSAN, ensure that calls to halide_msan_annotate_buffer_is_initialized()
// happen for every output buffer if the function succeeds.
if (f.linkage != LinkageType::Internal &&
target.has_feature(Target::MSAN)) {
llvm::Function *annotate_buffer_fn =
module->getFunction("halide_msan_annotate_buffer_is_initialized_as_destructor");
internal_assert(annotate_buffer_fn)
<< "Could not find halide_msan_annotate_buffer_is_initialized_as_destructor in module\n";
annotate_buffer_fn->addParamAttr(0, Attribute::NoAlias);
for (const auto &arg : f.args) {
if (arg.kind == Argument::OutputBuffer) {
register_destructor(annotate_buffer_fn, sym_get(arg.name + ".buffer"), OnSuccess);
}
}
}
// Generate the function body.
debug(1) << "Generating llvm bitcode for function " << f.name << "...\n";
f.body.accept(this);
// Clean up and return.
end_func(f.args);
}
// Given a range of iterators of constant ints, get a corresponding vector of llvm::Constant.
template<typename It>
std::vector<llvm::Constant *> get_constants(llvm::Type *t, It begin, It end) {
std::vector<llvm::Constant *> ret;
for (It i = begin; i != end; i++) {
ret.push_back(ConstantInt::get(t, *i));
}
return ret;
}
BasicBlock *CodeGen_LLVM::get_destructor_block() {
if (!destructor_block) {
// Create it if it doesn't exist.
IRBuilderBase::InsertPoint here = builder->saveIP();
destructor_block = BasicBlock::Create(*context, "destructor_block", function);
builder->SetInsertPoint(destructor_block);
// The first instruction in the destructor block is a phi node
// that collects the error code.
PHINode *error_code = builder->CreatePHI(i32_t, 0);
// Calls to destructors will get inserted here.
// The last instruction is the return op that returns it.
builder->CreateRet(error_code);
// Jump back to where we were.
builder->restoreIP(here);
}
internal_assert(destructor_block->getParent() == function);
return destructor_block;
}
Value *CodeGen_LLVM::register_destructor(llvm::Function *destructor_fn, Value *obj, DestructorType when) {
// Create a null-initialized stack slot to track this object
llvm::Type *void_ptr = i8_t->getPointerTo();
llvm::Value *stack_slot = create_alloca_at_entry(void_ptr, 1, true);
// Cast the object to llvm's representation of void *
obj = builder->CreatePointerCast(obj, void_ptr);
// Put it in the stack slot
builder->CreateStore(obj, stack_slot);
// Passing the constant null as the object means the destructor
// will never get called.
{
llvm::Constant *c = dyn_cast<llvm::Constant>(obj);
if (c && c->isNullValue()) {
internal_error << "Destructors must take a non-null object\n";
}
}
// Switch to the destructor block, and add code that cleans up
// this object if the contents of the stack slot is not nullptr.
IRBuilderBase::InsertPoint here = builder->saveIP();
BasicBlock *dtors = get_destructor_block();
builder->SetInsertPoint(dtors->getFirstNonPHI());
PHINode *error_code = dyn_cast<PHINode>(dtors->begin());
internal_assert(error_code) << "The destructor block is supposed to start with a phi node\n";
llvm::Value *should_call = nullptr;
switch (when) {
case Always:
should_call = ConstantInt::get(i1_t, 1);
break;
case OnError:
should_call = builder->CreateIsNotNull(error_code);
break;
case OnSuccess:
should_call = builder->CreateIsNull(error_code);
break;
}
llvm::Function *call_destructor = module->getFunction("call_destructor");
internal_assert(call_destructor);
internal_assert(destructor_fn);
internal_assert(should_call);
Value *args[] = {get_user_context(), destructor_fn, stack_slot, should_call};
builder->CreateCall(call_destructor, args);
// Switch back to the original location
builder->restoreIP(here);
// Return the stack slot so that it's possible to cleanup the object early.
return stack_slot;
}
void CodeGen_LLVM::trigger_destructor(llvm::Function *destructor_fn, Value *stack_slot) {
llvm::Function *call_destructor = module->getFunction("call_destructor");
internal_assert(call_destructor);
internal_assert(destructor_fn);
stack_slot = builder->CreatePointerCast(stack_slot, i8_t->getPointerTo()->getPointerTo());
Value *should_call = ConstantInt::get(i1_t, 1);
Value *args[] = {get_user_context(), destructor_fn, stack_slot, should_call};
builder->CreateCall(call_destructor, args);
}
void CodeGen_LLVM::compile_buffer(const Buffer<> &buf) {
// Embed the buffer declaration as a global.
internal_assert(buf.defined());
user_assert(buf.data())
<< "Can't embed buffer " << buf.name() << " because it has a null host pointer.\n";
user_assert(!buf.device_dirty())
<< "Can't embed Image \"" << buf.name() << "\""
<< " because it has a dirty device pointer\n";
Constant *type_fields[] = {
ConstantInt::get(i8_t, buf.type().code()),
ConstantInt::get(i8_t, buf.type().bits()),
ConstantInt::get(i16_t, buf.type().lanes())};
Constant *shape = nullptr;
if (buf.dimensions()) {
size_t shape_size = buf.dimensions() * sizeof(halide_dimension_t);
vector<char> shape_blob((char *)buf.raw_buffer()->dim, (char *)buf.raw_buffer()->dim + shape_size);
shape = create_binary_blob(shape_blob, buf.name() + ".shape");
shape = ConstantExpr::getPointerCast(shape, dimension_t_type->getPointerTo());
} else {
shape = ConstantPointerNull::get(dimension_t_type->getPointerTo());
}
// For now, we assume buffers that aren't scalar are constant,
// while scalars can be mutated. This accommodates all our existing
// use cases, which is that all buffers are constant, except those
// used to store stateful module information in offloading runtimes.
bool constant = buf.dimensions() != 0;
vector<char> data_blob((const char *)buf.data(), (const char *)buf.data() + buf.size_in_bytes());
Constant *fields[] = {
ConstantInt::get(i64_t, 0), // device
ConstantPointerNull::get(device_interface_t_type->getPointerTo()), // device_interface
create_binary_blob(data_blob, buf.name() + ".data", constant), // host
ConstantInt::get(i64_t, halide_buffer_flag_host_dirty), // flags
ConstantStruct::get(type_t_type, type_fields), // type
ConstantInt::get(i32_t, buf.dimensions()), // dimensions
shape, // dim
ConstantPointerNull::get(i8_t->getPointerTo()), // padding
};
Constant *buffer_struct = ConstantStruct::get(halide_buffer_t_type, fields);
// Embed the halide_buffer_t and make it point to the data array.
GlobalVariable *global = new GlobalVariable(*module, halide_buffer_t_type,
false, GlobalValue::PrivateLinkage,
nullptr, buf.name() + ".buffer");
global->setInitializer(buffer_struct);
// Finally, dump it in the symbol table
Constant *zero[] = {ConstantInt::get(i32_t, 0)};
Constant *global_ptr = ConstantExpr::getInBoundsGetElementPtr(halide_buffer_t_type, global, zero);
sym_push(buf.name() + ".buffer", global_ptr);
}
Constant *CodeGen_LLVM::embed_constant_scalar_value_t(const Expr &e) {
if (!e.defined()) {
return Constant::getNullValue(scalar_value_t_type->getPointerTo());
}
internal_assert(!e.type().is_handle()) << "Should never see Handle types here.";
llvm::Value *val = codegen(e);
llvm::Constant *constant = dyn_cast<llvm::Constant>(val);
internal_assert(constant);
// Verify that the size of the LLVM value is the size we expected.
internal_assert((uint64_t)constant->getType()->getPrimitiveSizeInBits() == (uint64_t)e.type().bits());
// 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. LLVM doesn't support
// unions directly, so 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));
vector<Constant *> array_entries(array_size, Constant::getNullValue(constant->getType()));
array_entries[0] = constant;
llvm::ArrayType *array_type = ArrayType::get(constant->getType(), array_size);
GlobalVariable *storage = new GlobalVariable(
*module,
array_type,
/*isConstant*/ true,
GlobalValue::PrivateLinkage,
ConstantArray::get(array_type, array_entries));
// Ensure that the storage is aligned for halide_scalar_value_t
storage->setAlignment(llvm::Align((int)sizeof(halide_scalar_value_t)));
Constant *zero[] = {ConstantInt::get(i32_t, 0)};
return ConstantExpr::getBitCast(
ConstantExpr::getInBoundsGetElementPtr(array_type, storage, zero),
scalar_value_t_type->getPointerTo());
}
Constant *CodeGen_LLVM::embed_constant_expr(Expr e, llvm::Type *t) {
internal_assert(t != scalar_value_t_type);
if (!e.defined()) {
return Constant::getNullValue(t->getPointerTo());
}
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 for estimates.";
}
llvm::Value *val = codegen(e);
llvm::Constant *constant = dyn_cast<llvm::Constant>(val);
internal_assert(constant);
GlobalVariable *storage = new GlobalVariable(
*module,
constant->getType(),
/*isConstant*/ true,
GlobalValue::PrivateLinkage,
constant);
Constant *zero[] = {ConstantInt::get(i32_t, 0)};
return ConstantExpr::getBitCast(
ConstantExpr::getInBoundsGetElementPtr(constant->getType(), storage, zero),
t->getPointerTo());
}
// Make a wrapper to call the function with an array of pointer
// args. This is easier for the JIT to call than a function with an
// unknown (at compile time) argument list. If result_in_argv is false,
// the internal function result is returned as the wrapper function
// result; if result_in_argv is true, the internal function result
// is stored as the last item in the argv list (which must be one
// longer than the number of arguments), and the wrapper's actual
// return type is always 'void'.
llvm::Function *CodeGen_LLVM::add_argv_wrapper(llvm::Function *fn,
const std::string &name,
bool result_in_argv) {
llvm::Type *wrapper_result_type = result_in_argv ? void_t : i32_t;
llvm::Type *wrapper_args_t[] = {i8_t->getPointerTo()->getPointerTo()};
llvm::FunctionType *wrapper_func_t = llvm::FunctionType::get(wrapper_result_type, wrapper_args_t, false);
llvm::Function *wrapper_func = llvm::Function::Create(wrapper_func_t, llvm::GlobalValue::ExternalLinkage, name, module.get());
llvm::BasicBlock *wrapper_block = llvm::BasicBlock::Create(module->getContext(), "entry", wrapper_func);
builder->SetInsertPoint(wrapper_block);
llvm::Value *arg_array = iterator_to_pointer(wrapper_func->arg_begin());
std::vector<llvm::Value *> wrapper_args;
for (llvm::Function::arg_iterator i = fn->arg_begin(); i != fn->arg_end(); i++) {
// Get the address of the nth argument
llvm::Value *ptr = CreateConstGEP1_32(builder, arg_array, wrapper_args.size());
ptr = builder->CreateLoad(ptr->getType()->getPointerElementType(), ptr);
if (i->getType() == halide_buffer_t_type->getPointerTo()) {
// Cast the argument to a halide_buffer_t *
wrapper_args.push_back(builder->CreatePointerCast(ptr, halide_buffer_t_type->getPointerTo()));
} else {
// Cast to the appropriate type and load
ptr = builder->CreatePointerCast(ptr, i->getType()->getPointerTo());
wrapper_args.push_back(builder->CreateLoad(ptr->getType()->getPointerElementType(), ptr));
}
}
debug(4) << "Creating call from wrapper to actual function\n";
llvm::CallInst *result = builder->CreateCall(fn, wrapper_args);
// This call should never inline
result->setIsNoInline();
if (result_in_argv) {
llvm::Value *result_in_argv_ptr = CreateConstGEP1_32(builder, arg_array, wrapper_args.size());
if (fn->getReturnType() != void_t) {
result_in_argv_ptr = builder->CreateLoad(result_in_argv_ptr->getType()->getPointerElementType(), result_in_argv_ptr);
// Cast to the appropriate type and store
result_in_argv_ptr = builder->CreatePointerCast(result_in_argv_ptr, fn->getReturnType()->getPointerTo());
builder->CreateStore(result, result_in_argv_ptr);
}
builder->CreateRetVoid();
} else {
// We could probably support other types as return values,
// but int32 results are all that have actually been tested.
internal_assert(fn->getReturnType() == i32_t);
builder->CreateRet(result);
}
internal_assert(!verifyFunction(*wrapper_func, &llvm::errs()));
return wrapper_func;
}
llvm::Function *CodeGen_LLVM::embed_metadata_getter(const std::string &metadata_name,
const std::string &function_name, const std::vector<LoweredArgument> &args,
const std::map<std::string, std::string> &metadata_name_map) {
Constant *zero = ConstantInt::get(i32_t, 0);
const int num_args = (int)args.size();
auto map_string = [&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;
};
vector<Constant *> arguments_array_entries;
for (int arg = 0; arg < num_args; ++arg) {
StructType *type_t_type = get_llvm_struct_type_by_name(module.get(), "struct.halide_type_t");
internal_assert(type_t_type) << "Did not find halide_type_t in module.\n";
Constant *type_fields[] = {
ConstantInt::get(i8_t, args[arg].type.code()),
ConstantInt::get(i8_t, args[arg].type.bits()),
ConstantInt::get(i16_t, 1)};
Constant *type = ConstantStruct::get(type_t_type, type_fields);
auto argument_estimates = args[arg].argument_estimates;
if (args[arg].type.is_handle()) {
// Handle values are always emitted into metadata as "undefined", regardless of
// what sort of Expr is provided.
argument_estimates = ArgumentEstimates{};
}
Constant *buffer_estimates_array_ptr;
if (args[arg].is_buffer() && !argument_estimates.buffer_estimates.empty()) {
internal_assert((int)argument_estimates.buffer_estimates.size() == args[arg].dimensions);
vector<Constant *> buffer_estimates_array_entries;
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);
}
buffer_estimates_array_entries.push_back(embed_constant_expr(min, i64_t));