forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegen.cpp
5854 lines (5457 loc) · 223 KB
/
codegen.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
// This file is a part of Julia. License is MIT: http://julialang.org/license
#include "llvm-version.h"
#include "platform.h"
#include "options.h"
#if defined(_OS_WINDOWS_)
// trick pre-llvm36 into skipping the generation of _chkstk calls
// since it has some codegen issues associated with them:
// (a) assumed to be within 32-bit offset
// (b) bad asm is generated for certain code patterns:
// see https://github.com/JuliaLang/julia/pull/11644#issuecomment-112276813
// also MCJIT debugging support on windows needs ELF (currently)
#define FORCE_ELF
#endif
#if defined(_CPU_X86_)
#define JL_NEED_FLOATTEMP_VAR 1
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/JITEventListener.h>
#include <llvm/IR/IntrinsicInst.h>
#ifdef LLVM38
#include <llvm/Analysis/BasicAliasAnalysis.h>
#include <llvm/Analysis/TypeBasedAliasAnalysis.h>
#endif
#ifdef LLVM37
#include "llvm/IR/LegacyPassManager.h"
#else
#include <llvm/PassManager.h>
#endif
#include <llvm/Target/TargetSubtargetInfo.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/Bitcode/ReaderWriter.h>
#ifdef LLVM37
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/Object/SymbolSize.h>
#else
#include <llvm/Target/TargetLibraryInfo.h>
#endif
#ifdef LLVM35
#include <llvm/IR/Verifier.h>
#include <llvm/Object/ObjectFile.h>
#include <llvm/IR/DIBuilder.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/AsmParser/Parser.h>
#else
#include <llvm/Assembly/Parser.h>
#include <llvm/Analysis/Verifier.h>
#endif
#include <llvm/DebugInfo/DIContext.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/Attributes.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/MDBuilder.h>
#include <llvm/IR/Value.h>
#ifndef LLVM35
#include <llvm/DebugInfo.h>
#include <llvm/DIBuilder.h>
#endif
#include <llvm/Target/TargetOptions.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Transforms/Instrumentation.h>
#include <llvm/Transforms/Vectorize.h>
#ifdef LLVM39
#include <llvm/Transforms/Scalar/GVN.h>
#endif
#include <llvm/Support/Host.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/PrettyStackTrace.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Transforms/Utils/Cloning.h>
#if defined(USE_ORCJIT)
#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
#include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
#include "llvm/ExecutionEngine/Orc/LazyEmittingLayer.h"
#include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h"
#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
#elif defined(USE_MCJIT)
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ADT/DenseMapInfo.h>
#include <llvm/Object/ObjectFile.h>
#else
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/ExecutionEngine/JITMemoryManager.h>
#include <llvm/ExecutionEngine/Interpreter.h>
#endif
using namespace llvm;
#if defined(_OS_WINDOWS_) && !defined(NOMINMAX)
#define NOMINMAX
#endif
#include "julia.h"
#include "julia_internal.h"
#include "codegen_internal.h"
#include <setjmp.h>
#include <string>
#include <sstream>
#include <fstream>
#include <map>
#include <vector>
#include <set>
#include <cstdio>
#include <cassert>
// LLVM version compatibility macros
#ifdef LLVM37
using namespace llvm::legacy;
#define LLVM37_param(x) (x),
#else
#define LLVM37_param(x)
#endif
#ifndef LLVM35
#define AddrSpaceCastInst BitCastInst
#endif
#if !defined(_COMPILER_MICROSOFT_) && __cplusplus < 201103L && !defined(static_assert)
# define static_assert(...)
#endif
extern "C" {
#include "builtin_proto.h"
#ifdef HAVE_SSP
extern uintptr_t __stack_chk_guard;
extern void __stack_chk_fail();
#else
JL_DLLEXPORT uintptr_t __stack_chk_guard = (uintptr_t)0xBAD57ACCBAD67ACC; // 0xBADSTACKBADSTACK
JL_DLLEXPORT void __stack_chk_fail()
{
/* put your panic function or similar in here */
fprintf(stderr, "fatal error: stack corruption detected\n");
gc_debug_critical_error();
abort(); // end with abort, since the compiler destroyed the stack upon entry to this function, there's no going back now
}
#endif
#ifdef _OS_WINDOWS_
#if defined(_CPU_X86_64_)
#if defined(_COMPILER_MINGW_)
extern void ___chkstk_ms(void);
#else
extern void __chkstk(void);
#endif
#else
#if defined(_COMPILER_MINGW_)
#undef _alloca
extern void _alloca(void);
#else
extern void _chkstk(void);
#endif
#endif
//void *force_chkstk(void) {
// return alloca(40960);
//}
#endif
}
#if defined(_COMPILER_MICROSOFT_) && !defined(__alignof__)
#define __alignof__ __alignof
#endif
#define DISABLE_FLOAT16
// llvm state
#ifdef LLVM39
JL_DLLEXPORT LLVMContext jl_LLVMContext;
#else
JL_DLLEXPORT LLVMContext &jl_LLVMContext = getGlobalContext();
#endif
static IRBuilder<> builder(jl_LLVMContext);
static bool nested_compile = false;
static TargetMachine *jl_TargetMachine;
extern JITEventListener *CreateJuliaJITEventListener();
namespace llvm {
extern Pass *createLowerSimdLoopPass();
extern bool annotateSimdLoop(BasicBlock *latch);
}
// for image reloading
static bool imaging_mode = false;
static Module *shadow_output;
#define jl_Module ctx->f->getParent()
#define jl_builderModule builder.GetInsertBlock()->getParent()->getParent()
static MDBuilder *mbuilder;
static std::map<int, std::string> argNumberStrings;
#ifdef LLVM38
static legacy::PassManager *PM;
#else
static PassManager *PM;
#endif
#ifdef LLVM37
// No DataLayout pass needed anymore.
#elif defined(LLVM35)
static DataLayoutPass *jl_data_layout;
#else
static DataLayout *jl_data_layout;
#endif
// types
static Type *T_jlvalue;
static Type *T_pjlvalue;
static Type *T_ppjlvalue;
static Type *jl_parray_llvmt;
static FunctionType *jl_func_sig;
static FunctionType *jl_func_sig_sparams;
static Type *T_pvoidfunc;
static IntegerType *T_int1;
static IntegerType *T_int8;
static IntegerType *T_int16;
static IntegerType *T_int32;
static IntegerType *T_int64;
static IntegerType *T_uint8;
static IntegerType *T_uint16;
static IntegerType *T_uint32;
static IntegerType *T_uint64;
static IntegerType *T_char;
static IntegerType *T_size;
static Type *T_float16;
static Type *T_float32;
static Type *T_float64;
static Type *T_float128;
static Type *T_pint8;
static Type *T_pint16;
static Type *T_pint32;
static Type *T_pint64;
static Type *T_psize;
static Type *T_pfloat32;
static Type *T_pfloat64;
static Type *T_ppint8;
static Type *T_pppint8;
static Type *T_void;
// type-based alias analysis nodes. Indentation of comments indicates hierarchy.
static MDNode *tbaa_gcframe; // GC frame
static MDNode *tbaa_user; // User data that is mutable
static MDNode *tbaa_immut; // User data inside a heap-allocated immutable
static MDNode *tbaa_value; // Julia value
static MDNode *tbaa_array; // Julia array
static MDNode *tbaa_arrayptr; // The pointer inside a jl_array_t
static MDNode *tbaa_arraysize; // A size in a jl_array_t
static MDNode *tbaa_arraylen; // The len in a jl_array_t
static MDNode *tbaa_arrayflags; // The flags in a jl_array_t
static MDNode *tbaa_sveclen; // The len in a jl_svec_t
static MDNode *tbaa_func; // A jl_function_t
static MDNode *tbaa_datatype; // A jl_datatype_t
static MDNode *tbaa_const; // Memory that is immutable by the time LLVM can see it
// Basic DITypes
#ifdef LLVM37
static DICompositeType *jl_value_dillvmt;
static DIDerivedType *jl_pvalue_dillvmt;
static DIDerivedType *jl_ppvalue_dillvmt;
static DISubroutineType *jl_di_func_sig;
#else
static DICompositeType jl_value_dillvmt;
static DIDerivedType jl_pvalue_dillvmt;
static DIDerivedType jl_ppvalue_dillvmt;
#ifdef LLVM36
DISubroutineType jl_di_func_sig;
#else
DICompositeType jl_di_func_sig;
#endif
#endif
// constants
static Value *V_null;
static Type *NoopType;
static Value *literal_pointer_val(jl_value_t *p);
extern "C" {
JL_DLLEXPORT Type *julia_type_to_llvm(jl_value_t *jt, bool *isboxed=NULL);
}
static bool type_is_ghost(Type *ty)
{
return (ty == T_void || ty->isEmptyTy());
}
// global vars
static GlobalVariable *jltrue_var;
static GlobalVariable *jlfalse_var;
static GlobalVariable *jlemptysvec_var;
static GlobalVariable *jlemptytuple_var;
static GlobalVariable *jldiverr_var;
static GlobalVariable *jlundeferr_var;
static GlobalVariable *jldomerr_var;
static GlobalVariable *jlovferr_var;
static GlobalVariable *jlinexacterr_var;
static GlobalVariable *jlRTLD_DEFAULT_var;
#ifdef _OS_WINDOWS_
static GlobalVariable *jlexe_var;
static GlobalVariable *jldll_var;
#if defined(_CPU_X86_64_) && !defined(USE_MCJIT)
extern JITMemoryManager *createJITMemoryManagerWin();
#endif
#endif //_OS_WINDOWS_
#if defined(_OS_DARWIN_) && defined(LLVM37) && defined(LLVM_SHLIB)
#define CUSTOM_MEMORY_MANAGER createRTDyldMemoryManagerOSX
extern RTDyldMemoryManager *createRTDyldMemoryManagerOSX();
#elif defined(_OS_LINUX_) && defined(LLVM37) && defined(JL_UNW_HAS_FORMAT_IP)
#define CUSTOM_MEMORY_MANAGER createRTDyldMemoryManagerUnix
extern RTDyldMemoryManager *createRTDyldMemoryManagerUnix();
#endif
static Function *jltls_states_func;
#ifndef JULIA_ENABLE_THREADING
static GlobalVariable *jltls_states_var;
#else
// Imaging mode only
static GlobalVariable *jltls_states_func_ptr = NULL;
static size_t jltls_states_func_idx = 0;
static GlobalVariable *jl_gc_signal_page_ptr = NULL;
static size_t jl_gc_signal_page_idx = 0;
#endif
// important functions
static Function *jlnew_func;
static Function *jlthrow_func;
static Function *jlerror_func;
static Function *jltypeerror_func;
static Function *jlundefvarerror_func;
static Function *jlboundserror_func;
static Function *jluboundserror_func;
static Function *jlvboundserror_func;
static Function *jlboundserrorv_func;
static Function *jlcheckassign_func;
static Function *jldeclareconst_func;
static Function *jlgetbindingorerror_func;
static Function *jlpref_func;
static Function *jlpset_func;
static Function *jltopeval_func;
static Function *jlcopyast_func;
static Function *jltuple_func;
static Function *jlnsvec_func;
static Function *jlapplygeneric_func;
static Function *jlgetfield_func;
static Function *jlmethod_func;
static Function *jlgenericfunction_func;
static Function *jlenter_func;
static Function *jlleave_func;
static Function *jlegal_func;
static Function *jlallocobj_func;
static Function *jlalloc1w_func;
static Function *jlalloc2w_func;
static Function *jlalloc3w_func;
static Function *jl_alloc_svec_func;
static Function *jlsubtype_func;
static Function *setjmp_func;
static Function *memcmp_func;
static Function *box_int8_func;
static Function *box_uint8_func;
static Function *box_int16_func;
static Function *box_uint16_func;
static Function *box_int32_func;
static Function *box_char_func;
static Function *box_uint32_func;
static Function *box_int64_func;
static Function *box_uint64_func;
static Function *box_float32_func;
static Function *box_float64_func;
static Function *box_gensym_func;
static Function *box8_func;
static Function *box16_func;
static Function *box32_func;
static Function *box64_func;
static Function *queuerootfun;
static Function *expect_func;
static Function *jldlsym_func;
static Function *jlnewbits_func;
static Function *jltypeassert_func;
#ifndef LLVM36
static Function *jlpow_func;
static Function *jlpowf_func;
#endif
//static Function *jlgetnthfield_func;
static Function *jlgetnthfieldchecked_func;
//static Function *jlsetnthfield_func;
#ifdef _OS_WINDOWS_
static Function *resetstkoflw_func;
#endif
static Function *diff_gc_total_bytes_func;
static Function *jlarray_data_owner_func;
// placeholder functions
static Function *gcroot_func;
static Function *gcstore_func;
static Function *gckill_func;
static Function *jlcall_frame_func;
static std::vector<Type *> two_pvalue_llvmt;
static std::vector<Type *> three_pvalue_llvmt;
static std::map<jl_fptr_t, Function*> builtin_func_map;
// --- code generation ---
extern "C" {
int globalUnique = 0;
}
#include "jitlayers.cpp"
// metadata tracking for a llvm Value* during codegen
struct jl_cgval_t {
Value *V; // may be of type T* or T, or set to NULL if ghost (or if the value has not been initialized yet, for a variable definition)
jl_value_t *constant; // constant value (rooted in linfo.def.roots)
Value *gcroot; // the gcroot associated with V (if it has one)
jl_value_t *typ; // the original type of V, never NULL
//Type *T; // cached result of julia_type_to_llvm(typ)
bool isboxed; // whether this value is a jl_value_t* allocated on the heap with the right type tag
bool isghost; // whether this value is "ghost"
bool ispointer; // whether this value is actually pointer to the value
bool isimmutable; // V points to something that is definitely immutable (e.g. single-assignment, but including memory)
jl_cgval_t(Value *V, Value *gcroot, bool isboxed, jl_value_t *typ) : // general constructor (with pointer type auto-detect)
V(V), // V is allowed to be NULL in a jl_varinfo_t context, but not during codegen contexts
constant(NULL),
gcroot(gcroot),
typ(typ),
//T(julia_type_to_llvm(typ)),
isboxed(isboxed),
isghost(false),
ispointer(isboxed),
isimmutable(isboxed && jl_is_immutable_datatype(typ))
{
}
jl_cgval_t(jl_value_t *typ) : // ghost value constructor
V(NULL),
constant(((jl_datatype_t*)typ)->instance),
gcroot(NULL),
typ(typ),
//T(T_void),
isboxed(false),
isghost(true),
ispointer(false),
isimmutable(true)
{
assert(jl_is_datatype(typ));
assert(constant);
}
jl_cgval_t(const jl_cgval_t &v, jl_value_t *typ) : // copy constructor with new type
V(v.V),
constant(v.constant),
gcroot(v.gcroot),
typ(typ),
//T(V.T),
isboxed(v.isboxed),
isghost(v.isghost),
ispointer(v.ispointer),
isimmutable(v.isimmutable)
{
assert(isboxed || v.typ == typ); // expect a badly or equivalently typed version
}
jl_cgval_t() : // undef / unreachable / default constructor
V(UndefValue::get(T_void)),
constant(NULL),
gcroot(NULL),
typ(jl_bottom_type),
isboxed(false),
isghost(true),
ispointer(false),
isimmutable(true)
{
}
};
// per-local-variable information
struct jl_varinfo_t {
Value *memloc; // an address, if the var is in a jl_value_t* gc stack slot or jl_box_t* Box object (marked tbaa_const, if appropriate)
jl_cgval_t value; // a value, if the var is unboxed or SSA (and thus memloc == NULL)
#ifdef LLVM37
DILocalVariable *dinfo;
#else
DIVariable dinfo;
#endif
bool isAssigned;
bool isSA;
bool isVolatile;
bool isArgument;
bool escapes;
bool usedUndef;
bool used;
jl_varinfo_t() : memloc(NULL), value(jl_cgval_t()),
#ifdef LLVM37
dinfo(NULL),
#else
dinfo(DIVariable()),
#endif
isAssigned(true), isSA(false),
isVolatile(false), isArgument(false),
escapes(true), usedUndef(false), used(false)
{
}
};
// --- helpers for reloading IR image
static void jl_dump_shadow(char *fname, int jit_model, const char *sysimg_data, size_t sysimg_len, bool dump_as_bc);
extern "C"
void jl_dump_bitcode(char *fname, const char *sysimg_data, size_t sysimg_len)
{
jl_dump_shadow(fname, 0, sysimg_data, sysimg_len, true);
}
extern "C"
void jl_dump_objfile(char *fname, int jit_model, const char *sysimg_data, size_t sysimg_len)
{
jl_dump_shadow(fname, jit_model, sysimg_data, sysimg_len, false);
}
// aggregate of array metadata
typedef struct {
Value *dataptr;
Value *len;
std::vector<Value*> sizes;
jl_value_t *ty;
} jl_arrayvar_t;
// information about the context of a piece of code: its enclosing
// function and module, and visible local variables and labels.
typedef struct {
Function *f;
// local var info. globals are not in here.
std::vector<jl_varinfo_t> slots;
std::vector<jl_cgval_t> gensym_SAvalues;
std::vector<bool> gensym_assigned;
std::map<int, jl_arrayvar_t> *arrayvars;
std::map<int, BasicBlock*> *labels;
std::map<int, Value*> *handlers;
jl_module_t *module;
jl_lambda_info_t *linfo;
const char *name;
StringRef file;
Value *spvals_ptr;
Value *argArray;
Value *argCount;
std::string funcName;
int vaSlot; // name of vararg argument
bool vaStack; // varargs stack-allocated
bool sret;
int nReqArgs;
std::vector<bool> boundsCheck;
std::vector<bool> inbounds;
CallInst *ptlsStates;
#ifdef JULIA_ENABLE_THREADING
Value *signalPage;
#endif
llvm::DIBuilder *dbuilder;
bool debug_enabled;
std::vector<CallInst*> to_inline;
} jl_codectx_t;
static jl_cgval_t emit_expr(jl_value_t *expr, jl_codectx_t *ctx);
static Value *emit_local_root(jl_codectx_t *ctx, jl_varinfo_t *vi = NULL);
static void mark_gc_use(const jl_cgval_t &v);
static Value *make_jlcall(ArrayRef<const jl_cgval_t*> args, jl_codectx_t *ctx);
static Value *global_binding_pointer(jl_module_t *m, jl_sym_t *s,
jl_binding_t **pbnd, bool assign, jl_codectx_t *ctx);
static jl_cgval_t emit_checked_var(Value *bp, jl_sym_t *name, jl_codectx_t *ctx, bool isvol=false);
static Value *emit_condition(jl_value_t *cond, const std::string &msg, jl_codectx_t *ctx);
static void allocate_gc_frame(BasicBlock *b0, jl_codectx_t *ctx);
static void jl_finalize_module(std::unique_ptr<Module> m, bool shadow);
static GlobalVariable *prepare_global(GlobalVariable *G, Module *M = jl_builderModule);
// --- convenience functions for tagging llvm values with julia types ---
static AllocaInst *emit_static_alloca(Type *lty, int arraysize, jl_codectx_t *ctx)
{
return new AllocaInst(lty, ConstantInt::get(T_int32, arraysize), "", /*InsertBefore=*/ctx->ptlsStates);
}
static AllocaInst *emit_static_alloca(Type *lty, jl_codectx_t *ctx)
{
return emit_static_alloca(lty, 1, ctx);
}
static AllocaInst *emit_static_alloca(Type *lty)
{
return new AllocaInst(lty, "",
/*InsertBefore=*/&*builder.GetInsertBlock()->getParent()->getEntryBlock().getFirstInsertionPt());
}
static inline jl_cgval_t ghostValue(jl_value_t *typ)
{
if (typ == jl_bottom_type)
return jl_cgval_t(); // Undef{}
return jl_cgval_t(typ);
}
static inline jl_cgval_t ghostValue(jl_datatype_t *typ)
{
return ghostValue((jl_value_t*)typ);
}
static inline jl_cgval_t mark_julia_slot(Value *v, jl_value_t *typ)
{
// eagerly put this back onto the stack
assert(v->getType() != T_pjlvalue);
jl_cgval_t tagval(v, NULL, false, typ);
tagval.ispointer = true;
tagval.isimmutable = true;
return tagval;
}
static inline jl_cgval_t mark_julia_type(Value *v, bool isboxed, jl_value_t *typ, jl_codectx_t *ctx, bool needsroot = true)
{
Type *T = julia_type_to_llvm(typ);
if (type_is_ghost(T)) {
return ghostValue(typ);
}
if (v && T->isAggregateType() && !isboxed) {
assert(v->getType() != T_pjlvalue);
// eagerly put this back onto the stack
// llvm mem2reg pass will remove this if unneeded
Value *loc = emit_static_alloca(T);
builder.CreateStore(v, loc);
return mark_julia_slot(loc, typ);
}
Value *froot = NULL;
if (needsroot && isboxed) {
froot = emit_local_root(ctx);
builder.CreateStore(v, froot);
}
return jl_cgval_t(v, froot, isboxed, typ);
}
static inline jl_cgval_t mark_julia_type(Value *v, bool isboxed, jl_datatype_t *typ, jl_codectx_t *ctx, bool needsroot = true)
{
return mark_julia_type(v, isboxed, (jl_value_t*)typ, ctx, needsroot);
}
static inline jl_cgval_t remark_julia_type(const jl_cgval_t &v, jl_value_t *typ)
{
Type *T = julia_type_to_llvm(typ);
if (type_is_ghost(T)) {
return ghostValue(typ);
}
return jl_cgval_t(v, typ);
}
static inline jl_cgval_t mark_julia_const(jl_value_t *jv)
{
jl_value_t *typ;
if (jl_is_datatype(jv) || jl_is_uniontype(jv) || jl_is_typector(jv))
typ = (jl_value_t*)jl_wrap_Type(jv);
else
typ = jl_typeof(jv);
if (type_is_ghost(julia_type_to_llvm(typ))) {
return ghostValue(typ);
}
jl_cgval_t constant(NULL, NULL, true, typ);
constant.constant = jv;
return constant;
}
// --- utilities ---
static void emit_write_barrier(jl_codectx_t*, Value*, Value*);
#include "cgutils.cpp"
static void jl_rethrow_with_add(const char *fmt, ...)
{
if (jl_typeis(jl_exception_in_transit, jl_errorexception_type)) {
char *str = jl_string_data(jl_fieldref(jl_exception_in_transit,0));
char buf[1024];
va_list args;
va_start(args, fmt);
int nc = vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
nc += snprintf(buf+nc, sizeof(buf)-nc, ": %s", str);
jl_value_t *msg = jl_pchar_to_string(buf, nc);
JL_GC_PUSH1(&msg);
jl_throw(jl_new_struct(jl_errorexception_type, msg));
}
jl_rethrow();
}
// --- allocating local variables ---
static bool isbits_spec(jl_value_t *jt, bool allow_unsized = true)
{
return jl_isbits(jt) && jl_is_leaf_type(jt) && (allow_unsized ||
((jl_is_bitstype(jt) && jl_datatype_size(jt) > 0) ||
(jl_is_datatype(jt) && jl_datatype_nfields(jt)>0)));
}
static bool store_unboxed_p(jl_value_t *jt)
{
return (isbits_spec(jt,false) &&
// don't unbox intrinsics, since inference depends on their having
// stable addresses for table lookup.
jt != (jl_value_t*)jl_intrinsic_type);
}
static bool store_unboxed_p(int s, jl_codectx_t *ctx)
{
jl_varinfo_t &vi = ctx->slots[s];
// only store a variable unboxed if type inference has run, which
// checks that the variable is not referenced undefined.
return (ctx->linfo->inferred && !vi.usedUndef &&
// don't unbox vararg tuples
s != ctx->vaSlot && store_unboxed_p(vi.value.typ));
}
static jl_sym_t *slot_symbol(int s, jl_codectx_t *ctx)
{
return (jl_sym_t*)jl_cellref(ctx->linfo->slotnames, s);
}
static Value *alloc_local(int s, jl_codectx_t *ctx)
{
jl_varinfo_t &vi = ctx->slots[s];
jl_value_t *jt = vi.value.typ;
assert(store_unboxed_p(s,ctx));
Type *vtype = julia_type_to_llvm(jt);
assert(vtype != T_pjlvalue);
if (type_is_ghost(vtype)) {
vi.value = ghostValue(jt);
return NULL;
}
// CreateAlloca is OK here because alloc_local is only called during prologue setup
Value *lv = builder.CreateAlloca(vtype, 0, jl_symbol_name(slot_symbol(s,ctx)));
vi.value = mark_julia_slot(lv, jt);
// slot is not immutable if there are multiple assignments
vi.value.isimmutable &= (vi.isSA && s >= ctx->linfo->nargs);
assert(vi.value.isboxed == false);
return lv;
}
static void maybe_alloc_arrayvar(int s, jl_codectx_t *ctx)
{
jl_value_t *jt = ctx->slots[s].value.typ;
if (arraytype_constshape(jt)) {
// TODO: this optimization does not yet work with 1-d arrays, since the
// length and data pointer can change at any time via push!
// we could make it work by reloading the metadata when the array is
// passed to an external function (ideally only impure functions)
jl_arrayvar_t av;
int ndims = jl_unbox_long(jl_tparam1(jt));
Type *elt = julia_type_to_llvm(jl_tparam0(jt));
if (type_is_ghost(elt))
return;
// CreateAlloca is OK here because maybe_alloc_arrayvar is only called in the prologue setup
av.dataptr = builder.CreateAlloca(PointerType::get(elt,0));
av.len = builder.CreateAlloca(T_size);
for(int i=0; i < ndims-1; i++)
av.sizes.push_back(builder.CreateAlloca(T_size));
av.ty = jt;
(*ctx->arrayvars)[s] = av;
}
}
// Snooping on which functions are being compiled, and how long it takes
JL_STREAM *dump_compiles_stream = NULL;
uint64_t last_time = 0;
extern "C" JL_DLLEXPORT
void jl_dump_compiles(void *s)
{
dump_compiles_stream = (JL_STREAM*)s;
}
// --- entry point ---
//static int n_emit=0;
static std::unique_ptr<Module> emit_function(jl_lambda_info_t *lam, jl_llvm_functions_t *declarations);
void jl_add_linfo_in_flight(StringRef name, jl_lambda_info_t *linfo, const DataLayout &DL);
// this is the implementation component of jl_compile_linfo
// which compiles li and adds the result to the jitlayers
static void to_function(jl_lambda_info_t *li)
{
// setup global state
JL_LOCK(&codegen_lock);
JL_SIGATOMIC_BEGIN();
assert(!li->inInference);
li->inCompile = 1;
BasicBlock *old = nested_compile ? builder.GetInsertBlock() : NULL;
DebugLoc olddl = builder.getCurrentDebugLocation();
bool last_n_c = nested_compile;
if (!nested_compile && dump_compiles_stream != NULL)
last_time = jl_hrtime();
nested_compile = true;
jl_gc_inhibit_finalizers(nested_compile);
std::unique_ptr<Module> m;
Function *f = NULL, *specf = NULL;
// actually do the work of emitting the function
JL_TRY {
m = emit_function(li, &li->functionObjectsDecls);
f = (Function*)li->functionObjectsDecls.functionObject;
specf = (Function*)li->functionObjectsDecls.specFunctionObject;
//n_emit++;
}
JL_CATCH {
// something failed! this is very bad, since other WIP may be pointing to this function
// but there's not much we can do now. try to clear much of the WIP anyways.
li->functionObjectsDecls.functionObject = NULL;
li->functionObjectsDecls.specFunctionObject = NULL;
nested_compile = last_n_c;
if (old != NULL) {
builder.SetInsertPoint(old);
builder.SetCurrentDebugLocation(olddl);
}
li->inCompile = 0;
JL_SIGATOMIC_END();
JL_UNLOCK(&codegen_lock);
jl_rethrow_with_add("error compiling %s", jl_symbol_name(li->def ? li->def->name : anonymous_sym));
}
// record that this function name came from this linfo,
// so we can build a reverse mapping for debug-info.
bool toplevel = li->def == NULL;
if (!toplevel) {
const DataLayout &DL =
#ifdef LLVM35
m->getDataLayout();
#else
*jl_data_layout;
#endif
// but don't remember toplevel thunks because
// they may not be rooted in the gc for the life of the program,
// and the runtime doesn't notify us when the code becomes unreachable :(
jl_add_linfo_in_flight((specf ? specf : f)->getName(), li, DL);
}
// success. add the result to the execution engine now
jl_finalize_module(std::move(m), !toplevel);
if (!toplevel) {
li->functionID = jl_assign_functionID(f, 0);
if (specf)
li->specFunctionID = jl_assign_functionID(specf, 1);
}
// mark the pointer calling convention
li->jlcall_api = (f->getFunctionType() == jl_func_sig ? 0 : 1);
// done compiling: restore global state
if (old != NULL) {
builder.SetInsertPoint(old);
builder.SetCurrentDebugLocation(olddl);
}
li->inCompile = 0;
nested_compile = last_n_c;
jl_gc_inhibit_finalizers(nested_compile);
JL_UNLOCK(&codegen_lock);
JL_SIGATOMIC_END();
if (dump_compiles_stream != NULL) {
uint64_t this_time = jl_hrtime();
jl_printf(dump_compiles_stream, "%" PRIu64 "\t\"", this_time - last_time);
jl_static_show(dump_compiles_stream, (jl_value_t*)li);
jl_printf(dump_compiles_stream, "\"\n");
last_time = this_time;
}
}
#ifndef LLVM37
static Value *getModuleFlag(Module *m, StringRef Key)
{
SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
m->getModuleFlagsMetadata(ModuleFlags);
SmallVector<Module::ModuleFlagEntry, 8>::iterator it = ModuleFlags.begin();
for (;it != ModuleFlags.end(); ++it) {
if (Key == it->Key->getString())
return it->Val;
}
return NULL;
}
#else
#define getModuleFlag(m,str) m->getModuleFlag(str)
#endif
static void jl_setup_module(Module *m)
{
// Some linkers (*cough* OS X) don't understand DWARF v4, so we use v2 in
// imaging mode. The structure of v4 is slightly nicer for debugging JIT
// code.
if (!getModuleFlag(m,"Dwarf Version")) {
int dwarf_version = 4;
#ifdef _OS_DARWIN_
if (imaging_mode)
dwarf_version = 2;
#endif
m->addModuleFlag(llvm::Module::Warning, "Dwarf Version", dwarf_version);
}
#ifdef LLVM34
if (!getModuleFlag(m,"Debug Info Version"))
m->addModuleFlag(llvm::Module::Error, "Debug Info Version",
llvm::DEBUG_METADATA_VERSION);
#endif
#ifdef LLVM37
#ifdef USE_ORCJIT
m->setDataLayout(jl_ExecutionEngine->getDataLayout());
#elif defined(LLVM38)
m->setDataLayout(jl_ExecutionEngine->getDataLayout().getStringRepresentation());
#else
m->setDataLayout(jl_ExecutionEngine->getDataLayout()->getStringRepresentation());
#endif
m->setTargetTriple(jl_TargetMachine->getTargetTriple().str());
#elif defined(LLVM36)
m->setDataLayout(jl_ExecutionEngine->getDataLayout());
#endif
}
// this takes ownership of a module after code emission is complete
// and will add it to the execution engine when required (by jl_finalize_function)
static void finalize_gc_frame(Module *m);
static void jl_finalize_module(std::unique_ptr<Module> uniquem, bool shadow)
{
Module *m = uniquem.release(); // unique_ptr won't be able track what we do with this (the invariant is recovered by jl_finalize_function)
finalize_gc_frame(m);
#if !defined(USE_ORCJIT)
PM->run(*m);
#endif
#ifdef USE_MCJIT
// record the function names that are part of this Module
// so it can be added to the JIT when needed
for (Module::iterator I = m->begin(), E = m->end(); I != E; ++I) {
Function *F = &*I;
if (!F->isDeclaration())
module_for_fname[F->getName()] = m;
}
#endif
#if defined(USE_ORCJIT) || defined(USE_MCJIT)
// in the newer JITs, the shadow module is separate from the execution module
if (shadow)
#endif
jl_add_to_shadow(m);
}
// this ensures that llvmf has been emitted to the execution engine,
// returning the function pointer to it
extern void jl_callback_triggered_linfos(void);
static uint64_t getAddressForFunction(llvm::Function *llvmf)
{
#ifdef JL_DEBUG_BUILD
llvm::raw_fd_ostream out(1,false);
#endif
#ifdef USE_MCJIT
jl_finalize_function(llvmf, NULL);
uint64_t ret = jl_ExecutionEngine->getFunctionAddress(llvmf->getName());
// delay executing trace callbacks until here to make sure there's no
// recursive compilation.
jl_callback_triggered_linfos();
return ret;
#else
return (uint64_t)jl_ExecutionEngine->getPointerToFunction(
cast<Function>(shadow_output->getNamedValue(llvmf->getName())));
#endif
}
extern "C" JL_DLLEXPORT
uint64_t jl_get_llvm_fptr(llvm::Function *llvmf)
{
uint64_t addr = getAddressForFunction(llvmf);
#ifdef USE_ORCJIT
if (!addr)
addr = jl_ExecutionEngine->findUnmangledSymbol(llvmf->getName()).getAddress();
#endif
return addr;
}
// this assumes that jl_compile_linfo has already been called
// and forces compilation of the lambda info
extern "C" void jl_generate_fptr(jl_lambda_info_t *li)
{
JL_LOCK(&codegen_lock);
// objective: assign li->fptr
assert(li->functionObjectsDecls.functionObject);
assert(!li->inCompile);
if (li->fptr == NULL) {