-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
codegen.cpp
5538 lines (5194 loc) · 206 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
#include "platform.h"
#include "options.h"
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
#include "llvm-version.h"
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/JITEventListener.h>
#include <llvm/IR/IntrinsicInst.h>
#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/TargetLibraryInfo.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>
#ifdef 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
#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>
#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(_OS_WINDOWS_) && !defined(NOMINMAX)
#define NOMINMAX
#endif
#include "julia.h"
#include "julia_internal.h"
#include <setjmp.h>
#include <string>
#include <sstream>
#include <fstream>
#include <map>
#include <vector>
#include <set>
#include <cstdio>
#include <cassert>
using namespace llvm;
#if LLVM37
using namespace llvm::legacy;
#endif
extern "C" {
#include "builtin_proto.h"
#ifdef HAVE_SSP
extern uintptr_t __stack_chk_guard;
extern void __stack_chk_fail();
#else
DLLEXPORT uintptr_t __stack_chk_guard = (uintptr_t)0xBAD57ACCBAD67ACC; // 0xBADSTACKBADSTACK
DLLEXPORT void __stack_chk_fail()
{
/* put your panic function or similar in here */
fprintf(stderr, "fatal error: stack corruption detected\n");
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
DLLEXPORT LLVMContext &jl_LLVMContext = getGlobalContext();
static IRBuilder<> builder(getGlobalContext());
static bool nested_compile=false;
DLLEXPORT ExecutionEngine *jl_ExecutionEngine;
static TargetMachine *jl_TargetMachine;
#ifdef USE_MCJIT
static Module *shadow_module;
static RTDyldMemoryManager *jl_mcjmm;
#define jl_Module (builder.GetInsertBlock()->getParent()->getParent())
#else
static Module *jl_Module;
#endif
static MDBuilder *mbuilder;
static std::map<int, std::string> argNumberStrings;
static FunctionPassManager *FPM;
#ifdef LLVM37
// No DataLayout pass needed anymore.
#elif LLVM35
static DataLayoutPass *jl_data_layout;
#else
static DataLayout *jl_data_layout;
#endif
// for image reloading
static bool imaging_mode = false;
// types
static Type *jl_value_llvmt;
static Type *jl_pvalue_llvmt;
static Type *jl_ppvalue_llvmt;
static Type* jl_parray_llvmt;
static FunctionType *jl_func_sig;
static Type *jl_pfptr_llvmt;
static Type *T_int1;
static Type *T_int8;
static Type *T_pint8;
static Type *T_uint8;
static Type *T_int16;
static Type *T_pint16;
static Type *T_uint16;
static Type *T_int32;
static Type *T_pint32;
static Type *T_uint32;
static Type *T_int64;
static Type *T_pint64;
static Type *T_uint64;
static Type *T_char;
static Type *T_size;
static Type *T_psize;
static Type *T_float32;
static Type *T_pfloat32;
static Type *T_float64;
static Type *T_pfloat64;
static Type *T_void;
// type-based alias analysis nodes. Indentation of comments indicates hierarchy.
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_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
namespace llvm {
extern Pass *createLowerSimdLoopPass();
extern bool annotateSimdLoop( BasicBlock* latch );
}
// Basic DITypes
#ifdef LLVM37
static MDCompositeType *jl_value_dillvmt;
static MDDerivedType *jl_pvalue_dillvmt;
static MDDerivedType *jl_ppvalue_dillvmt;
static MDSubroutineType *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;
// global vars
static GlobalVariable *jltrue_var;
static GlobalVariable *jlfalse_var;
static GlobalVariable *jlemptysvec_var;
static GlobalVariable *jlemptytuple_var;
#if defined(_CPU_X86_)
#define JL_NEED_FLOATTEMP_VAR 1
#endif
#if JL_NEED_FLOATTEMP_VAR
static GlobalVariable *jlfloattemp_var;
#endif
#ifdef JL_GC_MARKSWEEP
static GlobalVariable *jlpgcstack_var;
#endif
static GlobalVariable *jlexc_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_
// important functions
static Function *jlnew_func;
static Function *jlthrow_func;
static Function *jlthrow_line_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 *jltopeval_func;
static Function *jlcopyast_func;
static Function *jltuple_func;
static Function *jlnsvec_func;
static Function *jlapplygeneric_func;
static Function *jlgetfield_func;
static Function *jlbox_func;
static Function *jlclosure_func;
static Function *jlmethod_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 *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;
#ifdef JL_GC_MARKSWEEP
static Function *wbfunc;
static Function *queuerootfun;
#endif
static Function *expect_func;
static Function *jldlsym_func;
static Function *jlnewbits_func;
//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 *show_execution_point_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;
extern "C" DLLEXPORT void gc_wb_slow(jl_value_t* parent, jl_value_t* ptr)
{
gc_wb(parent, ptr);
}
// --- code generation ---
// per-local-variable information
struct jl_varinfo_t {
Value *memvalue; // an address, if the var is alloca'd
Value *SAvalue; // register, if the var is SSA
Value *passedAs; // if an argument, the original passed value
#ifdef LLVM37
MDLocalVariable *dinfo;
#else
DIVariable dinfo;
#endif
int closureidx; // index in closure env, or -1
bool isAssigned;
bool isCaptured;
bool isSA;
bool isVolatile;
bool isArgument;
bool isGhost; // Has size 0 and is thus never actually allocated
bool hasGCRoot;
bool escapes;
bool usedUndef;
bool used;
jl_value_t *declType;
jl_value_t *initExpr; // initializing expression for SSA variables
jl_varinfo_t() : memvalue(NULL), SAvalue(NULL), passedAs(NULL),
#ifdef LLVM37
dinfo(NULL),
#else
dinfo(DIVariable()),
#endif
closureidx(-1), isAssigned(true), isCaptured(false), isSA(false),
isVolatile(false), isArgument(false), isGhost(false), hasGCRoot(false),
escapes(true), usedUndef(false), used(false),
declType((jl_value_t*)jl_any_type), initExpr(NULL)
{
}
};
// --- helpers for reloading IR image
static void jl_gen_llvm_gv_array(llvm::Module *mod, SmallVector<GlobalVariable*, 8> &globalvars);
extern "C"
void jl_dump_bitcode(char *fname)
{
#ifdef LLVM36
std::error_code err;
StringRef fname_ref = StringRef(fname);
raw_fd_ostream OS(fname_ref, err, sys::fs::F_None);
#elif LLVM35
std::string err;
raw_fd_ostream OS(fname, err, sys::fs::F_None);
#else
std::string err;
raw_fd_ostream OS(fname, err);
#endif
SmallVector<GlobalVariable*, 8> globalvars;
#ifdef USE_MCJIT
jl_gen_llvm_gv_array(shadow_module, globalvars);
WriteBitcodeToFile(shadow_module, OS);
#else
jl_gen_llvm_gv_array(jl_Module, globalvars);
WriteBitcodeToFile(jl_Module, OS);
#endif
for (SmallVectorImpl<GlobalVariable>::iterator *I = globalvars.begin(), *E = globalvars.end(); I != E; ++I) {
(*I)->eraseFromParent();
}
}
extern "C"
void jl_dump_objfile(char *fname, int jit_model)
{
#ifdef LLVM36
std::error_code err;
StringRef fname_ref = StringRef(fname);
raw_fd_ostream OS(fname_ref, err, sys::fs::F_None);
#elif LLVM35
std::string err;
raw_fd_ostream OS(fname, err, sys::fs::F_None);
#else
std::string err;
raw_fd_ostream OS(fname, err);
#endif
// We don't want to use MCJIT's target machine because
// it uses the large code model and we may potentially
// want less optimizations there.
Triple TheTriple = Triple(jl_TargetMachine->getTargetTriple());
#if defined(_OS_WINDOWS_) && defined(USE_MCJIT)
TheTriple.setObjectFormat(Triple::COFF);
#elif defined(_OS_DARWIN_) && defined(FORCE_ELF)
TheTriple.setObjectFormat(Triple::MachO);
#endif
#ifdef LLVM35
std::unique_ptr<TargetMachine>
#else
OwningPtr<TargetMachine>
#endif
TM(jl_TargetMachine->getTarget().createTargetMachine(
TheTriple.getTriple(),
jl_TargetMachine->getTargetCPU(),
jl_TargetMachine->getTargetFeatureString(),
jl_TargetMachine->Options,
#if defined(_OS_LINUX_) || defined(_OS_FREEBSD_)
Reloc::PIC_,
#else
jit_model ? Reloc::PIC_ : Reloc::Default,
#endif
jit_model ? CodeModel::JITDefault : CodeModel::Default,
CodeGenOpt::Aggressive // -O3
));
PassManager PM;
#ifndef LLVM37
PM.add(new TargetLibraryInfo(Triple(jl_TargetMachine->getTargetTriple())));
#else
PM.add(new TargetLibraryInfoWrapperPass(Triple(jl_TargetMachine->getTargetTriple())));
#endif
#ifdef LLVM37
// No DataLayout pass needed anymore.
#elif LLVM36
PM.add(new DataLayoutPass());
#elif LLVM35
PM.add(new DataLayoutPass(*jl_ExecutionEngine->getDataLayout()));
#else
PM.add(new DataLayout(*jl_ExecutionEngine->getDataLayout()));
#endif
#ifdef LLVM37 // 3.7 simplified formatted output; just use the raw stream alone
raw_fd_ostream& FOS(OS);
#else
formatted_raw_ostream FOS(OS);
#endif
if (TM->addPassesToEmitFile(PM, FOS, TargetMachine::CGFT_ObjectFile, false)) {
jl_error("Could not generate obj file for this target");
}
SmallVector<GlobalVariable*, 8> globalvars;
#ifdef USE_MCJIT
jl_gen_llvm_gv_array(shadow_module, globalvars);
PM.run(*shadow_module);
#else
jl_gen_llvm_gv_array(jl_Module, globalvars);
PM.run(*jl_Module);
#endif
for (SmallVectorImpl<GlobalVariable>::iterator *I = globalvars.begin(), *E = globalvars.end(); I != E; ++I) {
(*I)->eraseFromParent();
}
}
// 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.
// NOTE: you must be careful not to access vars[s] before you are sure "s" is
// a local, since otherwise this will add it to the map.
std::map<jl_sym_t*, jl_varinfo_t> vars;
std::vector<Value*> gensym_SAvalues;
std::vector<bool> gensym_assigned;
std::map<jl_sym_t*, jl_arrayvar_t> *arrayvars;
std::map<int, BasicBlock*> *labels;
std::map<int, Value*> *handlers;
jl_module_t *module;
jl_expr_t *ast;
jl_svec_t *sp;
jl_lambda_info_t *linfo;
Value *envArg;
Value *argArray;
Value *argCount;
Instruction *argTemp;
int argDepth;
int maxDepth;
int argSpaceOffs;
std::string funcName;
jl_sym_t *vaName; // name of vararg argument
bool vaStack; // varargs stack-allocated
int nReqArgs;
int lineno;
std::vector<bool> boundsCheck;
#ifdef JL_GC_MARKSWEEP
Instruction *gcframe;
Instruction *argSpaceInits;
StoreInst *storeFrameSize;
#endif
BasicBlock::iterator first_gcframe_inst;
BasicBlock::iterator last_gcframe_inst;
llvm::DIBuilder *dbuilder;
bool debug_enabled;
std::vector<Instruction*> gc_frame_pops;
std::vector<CallInst*> to_inline;
} jl_codectx_t;
typedef struct {
size_t len;
struct {
int64_t isref;
Function *f;
} data[];
} cFunctionList_t;
static Value *emit_expr(jl_value_t *expr, jl_codectx_t *ctx, bool boxed=true,
bool valuepos=true, jl_sym_t **valuevar=NULL);
static Value *emit_unboxed(jl_value_t *e, jl_codectx_t *ctx);
static int is_global(jl_sym_t *s, jl_codectx_t *ctx);
static Value *make_gcroot(Value *v, jl_codectx_t *ctx, jl_sym_t *var = NULL);
static Value *emit_boxed_rooted(jl_value_t *e, jl_codectx_t *ctx);
static Value *global_binding_pointer(jl_module_t *m, jl_sym_t *s,
jl_binding_t **pbnd, bool assign);
static Value *emit_checked_var(Value *bp, jl_sym_t *name, jl_codectx_t *ctx, bool isvol=false);
static bool might_need_root(jl_value_t *ex);
static Value *emit_condition(jl_value_t *cond, const std::string &msg, jl_codectx_t *ctx);
// NoopType
static Type *NoopType;
// --- utilities ---
extern "C" {
int globalUnique = 0;
}
extern "C" DLLEXPORT
jl_value_t *jl_get_cpu_name(void)
{
#if LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR < 5
std::string HostCPUName = llvm::sys::getHostCPUName();
#else
StringRef HostCPUName = llvm::sys::getHostCPUName();
#endif
return jl_pchar_to_string(HostCPUName.data(), HostCPUName.size());
}
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();
}
// --- entry point ---
//static int n_emit=0;
static Function *emit_function(jl_lambda_info_t *lam);
//static int n_compile=0;
static Function *to_function(jl_lambda_info_t *li)
{
JL_SIGATOMIC_BEGIN();
assert(!li->inInference);
BasicBlock *old = nested_compile ? builder.GetInsertBlock() : NULL;
DebugLoc olddl = builder.getCurrentDebugLocation();
bool last_n_c = nested_compile;
nested_compile = true;
Function *f = NULL;
JL_TRY {
f = emit_function(li);
//jl_printf(JL_STDOUT, "emit %s\n", li->name->name);
//n_emit++;
}
JL_CATCH {
li->functionObject = NULL;
li->specFunctionObject = NULL;
li->cFunctionList = NULL;
nested_compile = last_n_c;
if (old != NULL) {
builder.SetInsertPoint(old);
builder.SetCurrentDebugLocation(olddl);
}
JL_SIGATOMIC_END();
jl_rethrow_with_add("error compiling %s", li->name->name);
}
assert(f != NULL);
nested_compile = last_n_c;
#ifdef JL_DEBUG_BUILD
#ifdef LLVM35
llvm::raw_fd_ostream out(1,false);
#endif
if (
#ifdef LLVM35
verifyFunction(*f,&out)
#else
verifyFunction(*f,PrintMessageAction)
#endif
) {
f->dump();
abort();
}
#endif
FPM->run(*f);
//n_compile++;
// print out the function's LLVM code
//jl_printf(JL_STDERR, "%s:%d\n",
// ((jl_sym_t*)li->file)->name, li->line);
//if (verifyFunction(*f,PrintMessageAction)) {
// f->dump();
// abort();
//}
if (old != NULL) {
builder.SetInsertPoint(old);
builder.SetCurrentDebugLocation(olddl);
}
JL_SIGATOMIC_END();
return f;
}
static void jl_setup_module(Module *m, bool add)
{
m->addModuleFlag(llvm::Module::Warning, "Dwarf Version",2);
#ifdef LLVM34
m->addModuleFlag(llvm::Module::Error, "Debug Info Version",
llvm::DEBUG_METADATA_VERSION);
#endif
#ifdef LLVM37
if (jl_ExecutionEngine) {
m->setDataLayout(jl_ExecutionEngine->getDataLayout()->getStringRepresentation());
m->setTargetTriple(jl_TargetMachine->getTargetTriple());
}
#elif LLVM36
if (jl_ExecutionEngine)
m->setDataLayout(jl_ExecutionEngine->getDataLayout());
#endif
if (add) {
assert(jl_ExecutionEngine);
#ifdef LLVM36
jl_ExecutionEngine->addModule(std::unique_ptr<Module>(m));
#else
jl_ExecutionEngine->addModule(m);
#endif
#if defined(_CPU_X86_64_) && defined(_OS_WINDOWS_) && defined(USE_MCJIT)
ArrayType *atype = ArrayType::get(T_uint32,3); // want 4-byte alignment of 12-bytes of data
(new GlobalVariable(*m, atype,
false, GlobalVariable::InternalLinkage,
ConstantAggregateZero::get(atype), "__UnwindData"))->setSection(".text");
(new GlobalVariable(*m, atype,
false, GlobalVariable::InternalLinkage,
ConstantAggregateZero::get(atype), "__catchjmp"))->setSection(".text");
#endif
}
}
extern "C" void jl_generate_fptr(jl_function_t *f)
{
// objective: assign li->fptr
jl_lambda_info_t *li = f->linfo;
assert(li->functionObject);
if (li->fptr == &jl_trampoline) {
JL_SIGATOMIC_BEGIN();
#ifdef USE_MCJIT
if (imaging_mode) {
// Copy the function out of the shadow module
Module *m = new Module("julia", jl_LLVMContext);
jl_setup_module(m,true);
FunctionMover mover(m,shadow_module);
li->functionObject = mover.CloneFunction((Function*)li->functionObject);
if (li->specFunctionObject != NULL)
li->specFunctionObject = mover.CloneFunction((Function*)li->specFunctionObject);
if (li->cFunctionList != NULL) {
size_t i;
cFunctionList_t *list = (cFunctionList_t*)li->cFunctionList;
for (i = 0; i < list->len; i++) {
list->data[i].f = mover.CloneFunction(list->data[i].f);
}
}
}
#endif
Function *llvmf = (Function*)li->functionObject;
#ifdef USE_MCJIT
li->fptr = (jl_fptr_t)(intptr_t)jl_ExecutionEngine->getFunctionAddress(llvmf->getName());
#else
li->fptr = (jl_fptr_t)jl_ExecutionEngine->getPointerToFunction(llvmf);
#endif
assert(li->fptr != NULL);
#ifndef KEEP_BODIES
if (!imaging_mode)
llvmf->deleteBody();
#endif
if (li->cFunctionList != NULL) {
size_t i;
cFunctionList_t *list = (cFunctionList_t*)li->cFunctionList;
for (i = 0; i < list->len; i++) {
#ifdef USE_MCJIT
(void)jl_ExecutionEngine->getFunctionAddress(list->data[i].f->getName());
#else
(void)jl_ExecutionEngine->getPointerToFunction(list->data[i].f);
#endif
#ifndef KEEP_BODIES
if (!imaging_mode) {
list->data[i].f->deleteBody();
}
#endif
}
}
if (li->specFunctionObject != NULL) {
#ifdef USE_MCJIT
(void)jl_ExecutionEngine->getFunctionAddress(((Function*)li->specFunctionObject)->getName());
#else
(void)jl_ExecutionEngine->getPointerToFunction((Function*)li->specFunctionObject);
#endif
if (!imaging_mode)
((Function*)li->specFunctionObject)->deleteBody();
}
JL_SIGATOMIC_END();
}
f->fptr = li->fptr;
}
extern "C" void jl_compile(jl_function_t *f)
{
jl_lambda_info_t *li = f->linfo;
if (li->functionObject == NULL) {
// objective: assign li->functionObject
li->inCompile = 1;
(void)to_function(li);
li->inCompile = 0;
}
}
// Get the LLVM Function* for the C-callable entry point for a certain function
// and argument types. If rt is NULL then whatever return type is present is
// accepted.
static Function *gen_cfun_wrapper(jl_function_t *ff, jl_value_t *jlrettype, jl_tupletype_t *argt, int64_t isref);
static Function *jl_cfunction_object(jl_function_t *f, jl_value_t *rt, jl_tupletype_t *argt)
{
if (rt) {
JL_TYPECHK(cfunction, type, rt);
}
JL_TYPECHK(cfunction, type, (jl_value_t*)argt);
JL_TYPECHK(cfunction, function, (jl_value_t*)f);
if (!jl_is_gf(f))
jl_error("only generic functions are currently c-callable");
size_t i, nargs = jl_nparams(argt);
if (nargs >= 64)
jl_error("only functions with less than 64 arguments are c-callable");
uint64_t isref = 0; // bit vector of which argument types are a subtype of Type{Ref{T}}
jl_value_t *sigt = NULL; // type signature with Ref{} annotations removed
JL_GC_PUSH1(&sigt);
sigt = (jl_value_t*)jl_alloc_svec(nargs);
for (i = 0; i < nargs; i++) {
jl_value_t *ati = jl_tparam(argt, i);
if (jl_is_abstract_ref_type(ati)) {
ati = jl_tparam0(ati);
if (jl_is_typevar(ati))
jl_error("cfunction: argument type Ref should have an element type, not Ref{T}");
isref |= (2<<i);
}
else if (ati != (jl_value_t*)jl_any_type && !jl_is_leaf_type(ati)) {
jl_error("cfunction: type signature must only contain leaf types");
}
jl_svecset(sigt, i, ati);
}
sigt = (jl_value_t*)jl_apply_tuple_type((jl_svec_t*)sigt);
if (rt != NULL) {
if (jl_is_abstract_ref_type(rt)) {
rt = jl_tparam0(rt);
if (jl_is_typevar(rt))
jl_error("cfunction: return type Ref should have an element type, not Ref{T}");
if (rt == (jl_value_t*)jl_any_type)
jl_error("cfunction: return type Ref{Any} is invalid. Use Any or Ptr{Any} instead.");
isref |= 1;
}
else if (!jl_is_leaf_type(rt)) {
isref |= 1;
}
}
jl_function_t *ff = jl_get_specialization(f, (jl_tupletype_t*)sigt);
if (ff != NULL && ff->env==(jl_value_t*)jl_emptysvec && ff->linfo != NULL) {
jl_lambda_info_t *li = ff->linfo;
if (!jl_types_equal((jl_value_t*)li->specTypes, sigt)) {
jl_errorf("cfunction: type signature of %s does not match specification",
li->name->name);
}
jl_value_t *astrt = jl_ast_rettype(li, li->ast);
if (rt != NULL) {
if (astrt == (jl_value_t*)jl_bottom_type) {
if (rt != (jl_value_t*)jl_void_type) {
// a function that doesn't return can be passed to C as void
jl_errorf("cfunction: %s does not return", li->name->name);
}
}
else if (!jl_subtype(astrt, rt, 0)) {
jl_errorf("cfunction: return type of %s does not match",
li->name->name);
}
}
JL_GC_POP(); // kill list: sigt
return gen_cfun_wrapper(ff, astrt, argt, isref);
}
jl_error("cfunction: no method exactly matched the required type signature (function not yet c-callable)");
}
// get the address of a C-callable entry point for a function
extern "C" DLLEXPORT
void *jl_function_ptr(jl_function_t *f, jl_value_t *rt, jl_value_t *argt)
{
JL_GC_PUSH1(&argt);
if (jl_is_tuple(argt)) {
// TODO: maybe deprecation warning, better checking
argt = (jl_value_t*)jl_apply_tuple_type_v((jl_value_t**)jl_data_ptr(argt), jl_nfields(argt));
}
assert(jl_is_tuple_type(argt));
Function *llvmf = jl_cfunction_object(f, rt, (jl_tupletype_t*)argt);
assert(llvmf);
JL_GC_POP();
#ifdef USE_MCJIT
return (void*)(intptr_t)jl_ExecutionEngine->getFunctionAddress(llvmf->getName());
#else
return jl_ExecutionEngine->getPointerToFunction(llvmf);
#endif
}
extern "C" DLLEXPORT
void *jl_function_ptr_by_llvm_name(char* name) {
#ifdef __has_feature
#if __has_feature(memory_sanitizer)
__msan_unpoison_string(name);
#endif
#endif
return (void*)(intptr_t)jl_ExecutionEngine->FindFunctionNamed(name);
}
// export a C-callable entry point for a function, with a given name
extern "C" DLLEXPORT
void jl_extern_c(jl_function_t *f, jl_value_t *rt, jl_value_t *argt, char *name)
{
assert(jl_is_tuple_type(argt));
Function *llvmf = jl_cfunction_object(f, rt, (jl_tupletype_t*)argt);
if (llvmf) {
#ifndef LLVM35
new GlobalAlias(llvmf->getType(), GlobalValue::ExternalLinkage, name, llvmf, llvmf->getParent());
#else
GlobalAlias::create(llvmf->getType()->getElementType(), llvmf->getType()->getAddressSpace(),
GlobalValue::ExternalLinkage, name, llvmf, llvmf->getParent());
#endif
}
}
// --- native code info, and dump function to IR and ASM ---
extern void RegisterJuliaJITEventListener();
extern int jl_get_llvmf_info(uint64_t fptr, uint64_t *symsize, uint64_t *slide,
#ifdef USE_MCJIT
const object::ObjectFile **object
#else
std::vector<JITEvent_EmittedFunctionDetails::LineStart> *lines
#endif
);
// Get pointer to llvm::Function instance, compiling if necessary
extern "C" DLLEXPORT
void *jl_get_llvmf(jl_function_t *f, jl_tupletype_t *tt, bool getwrapper)
{
jl_function_t *sf = f;
if (tt != NULL) {
if (!jl_is_function(f) || !jl_is_gf(f)) {
return NULL;
}
sf = jl_get_specialization(f, tt);
}
if (sf == NULL || sf->linfo == NULL) {
sf = jl_method_lookup_by_type(jl_gf_mtable(f), tt, 0, 0);
if (sf == jl_bottom_func) {
return NULL;
}
jl_printf(JL_STDERR,
"Warning: Returned code may not match what actually runs.\n");
}
Function *llvmf;
if (getwrapper || sf->linfo->specTypes == NULL) {
if (sf->linfo->functionObject == NULL) {
jl_compile(sf);
}
}
else {
if (sf->linfo->specFunctionObject == NULL) {
jl_compile(sf);
}
}
if (sf->fptr == &jl_trampoline) {
if (!getwrapper && sf->linfo->specFunctionObject != NULL)
llvmf = (Function*)sf->linfo->specFunctionObject;
else
llvmf = (Function*)sf->linfo->functionObject;
}
else {
llvmf = to_function(sf->linfo);
}
return llvmf;
}
extern "C" DLLEXPORT
const jl_value_t *jl_dump_function_ir(void *f, bool strip_ir_metadata)
{
std::string code;
llvm::raw_string_ostream stream(code);
Function *llvmf = dyn_cast<Function>((Function*)f);
if (!llvmf)
jl_error("jl_dump_function_ir: Expected Function*");
if (!strip_ir_metadata || llvmf->isDeclaration()) {
// print the function IR as-is
llvmf->print(stream);
}
else {
// make a copy of the function and strip metadata from the copy
llvm::ValueToValueMapTy VMap;
Function* f2 = llvm::CloneFunction(llvmf, VMap, false);
Function::BasicBlockListType::iterator f2_bb = f2->getBasicBlockList().begin();
// iterate over all basic blocks in the function
for (; f2_bb != f2->getBasicBlockList().end(); ++f2_bb) {
BasicBlock::InstListType::iterator f2_il = (*f2_bb).getInstList().begin();
// iterate over instructions in basic block
for (; f2_il != (*f2_bb).getInstList().end(); ) {
Instruction *inst = f2_il++;
// remove dbg.declare and dbg.value calls
if (isa<DbgDeclareInst>(inst) || isa<DbgValueInst>(inst)) {
inst->eraseFromParent();
continue;
}
SmallVector<std::pair<unsigned, MDNode*>, 4> MDForInst;
inst->getAllMetadata(MDForInst);
SmallVector<std::pair<unsigned, MDNode*>, 4>::iterator md_iter = MDForInst.begin();
// iterate over all metadata kinds and set to NULL to remove
for (; md_iter != MDForInst.end(); ++md_iter) {
inst->setMetadata((*md_iter).first, NULL);
}