-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
codegen.cpp
4756 lines (4488 loc) · 176 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
/*
* We include <mathimf.h> here, because somewhere below <math.h> is included also.
* As a result, Intel C++ Composer generates an error. To prevent this error, we
* include <mathimf.h> as soon as possible. <mathimf.h> defines several macros
* (like _INC_MATH, __MATH_H_INCLUDED, __COMPLEX_H_INCLUDED) that prevent
* including <math.h> (or rather its content).
*/
#if defined(_OS_WINDOWS_)
#include <malloc.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#if defined(_COMPILER_INTEL_)
#include <mathimf.h>
#else
#include <math.h>
#endif
#endif
#include "platform.h"
#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/ExecutionEngine/JITMemoryManager.h"
#include "llvm/PassManager.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Bitcode/ReaderWriter.h"
#ifdef _OS_DARWIN_
#include "llvm/Object/MachO.h"
#endif
#ifdef _OS_WINDOWS_
#include "llvm/Object/COFF.h"
#endif
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 6
#define LLVM36 1
#endif
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5
#define LLVM35 1
#include "llvm/IR/Verifier.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/AsmParser/Parser.h"
#include "llvm/Target/TargetMachine.h"
#else
#include "llvm/Analysis/Verifier.h"
#include "llvm/Assembly/Parser.h"
#endif
#include "llvm/DebugInfo/DIContext.h"
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 4
#define LLVM34 1
#define USE_MCJIT 1
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/ExecutionEngine/ObjectImage.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/Object/ObjectFile.h"
#else
#include "llvm/ExecutionEngine/JIT.h"
#endif
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 3
#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"
#define LLVM33 1
#else
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Intrinsics.h"
#include "llvm/Attributes.h"
#endif
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 2
#ifndef LLVM35
#include "llvm/DebugInfo.h"
#include "llvm/DIBuilder.h"
#endif
#ifndef LLVM33
#include "llvm/IRBuilder.h"
#endif
#define LLVM32 1
#else
#include "llvm/Analysis/DebugInfo.h"
#include "llvm/Analysis/DIBuilder.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/IRBuilder.h"
#endif
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Instrumentation.h"
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 1
#include "llvm/Transforms/Vectorize.h"
#endif
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Config/llvm-config.h"
#ifdef JL_DEBUG_BUILD
#include "llvm/Support/CommandLine.h"
#endif
#include "llvm/Transforms/Utils/Cloning.h"
// For disasm
#include "llvm/Support/MachO.h"
#include "llvm/Support/COFF.h"
#include "llvm/MC/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCContext.h"
#ifndef LLVM35
#include "llvm/ADT/OwningPtr.h"
#endif
#include "llvm/ADT/Triple.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"
#ifndef LLVM35
#include "llvm/Support/system_error.h"
#endif
#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;
extern "C" {
#include "builtin_proto.h"
void *__stack_chk_guard = NULL;
#if defined(_OS_WINDOWS_) && !defined(_COMPILER_MINGW_)
void __stack_chk_fail()
#else
void __attribute__(()) __stack_chk_fail()
#endif
{
/* put your panic function or similar in here */
fprintf(stderr, "warning: stack corruption detected\n");
//assert(0 && "stack corruption detected");
//abort();
}
}
#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 LLVM35
static DataLayoutPass *jl_data_layout;
#elif defined(LLVM32)
static DataLayout *jl_data_layout;
#else
static TargetData *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 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
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_tuplelen; // The len in a jl_tuple_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 );
}
// constants
static Value *V_null;
// global vars
static GlobalVariable *jltrue_var;
static GlobalVariable *jlfalse_var;
static GlobalVariable *jlnull_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 *jlboundserr_var;
static GlobalVariable *jlstderr_var;
static GlobalVariable *jlRTLD_DEFAULT_var;
#ifdef _OS_WINDOWS_
static GlobalVariable *jlexe_var;
static GlobalVariable *jldll_var;
#endif
// 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 *jlcheckassign_func;
static Function *jldeclareconst_func;
static Function *jltopeval_func;
static Function *jlcopyast_func;
static Function *jltuple_func;
static Function *jlntuple_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 *jlalloc2w_func;
static Function *jlalloc3w_func;
static Function *jl_alloc_tuple_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 *box8_func;
static Function *box16_func;
static Function *box32_func;
static Function *box64_func;
static Function *jlputs_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;
// --- 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
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), 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();
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
jl_gen_llvm_gv_array();
#ifdef USE_MCJIT
WriteBitcodeToFile(shadow_module, OS);
#else
WriteBitcodeToFile(jl_Module, OS);
#endif
}
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
formatted_raw_ostream FOS(OS);
jl_gen_llvm_gv_array();
// 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);
#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;
PM.add(new TargetLibraryInfo(Triple(jl_TargetMachine->getTargetTriple())));
#ifdef LLVM35
PM.add(new DataLayoutPass(*jl_ExecutionEngine->getDataLayout()));
#else
PM.add(new DataLayout(*jl_ExecutionEngine->getDataLayout()));
#endif
if (TM->addPassesToEmitFile(PM, FOS, TargetMachine::CGFT_ObjectFile, false)) {
jl_error("Could not generate obj file for this target");
}
#ifdef USE_MCJIT
PM.run(*shadow_module);
#else
PM.run(*jl_Module);
#endif
}
// 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::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_tuple_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;
std::vector<Instruction*> gc_frame_pops;
std::vector<CallInst*> to_inline;
} jl_codectx_t;
static Value *emit_expr(jl_value_t *expr, jl_codectx_t *ctx, bool boxed=true,
bool valuepos=true);
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);
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);
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 ---
#define XSTR(x) #x
#define MSTR(x) XSTR(x)
extern "C" {
const char *jl_cpu_string = MSTR(JULIA_TARGET_ARCH);
int globalUnique = 0;
}
extern "C" DLLEXPORT
jl_value_t *jl_get_cpu_name(void)
{
StringRef HostCPUName = llvm::sys::getHostCPUName();
return jl_pchar_to_string(HostCPUName.data(), HostCPUName.size());
}
#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, bool cstyle);
//static int n_compile=0;
static Function *to_function(jl_lambda_info_t *li, bool cstyle)
{
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, cstyle);
//JL_PRINTF(JL_STDOUT, "emit %s\n", li->name->name);
//n_emit++;
}
JL_CATCH {
li->functionObject = NULL;
li->cFunctionObject = 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
//ios_printf(ios_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;
}
extern "C" jl_function_t *jl_get_specialization(jl_function_t *f, jl_tuple_t *types);
static void jl_setup_module(Module *m, bool add)
{
m->addModuleFlag(llvm::Module::Warning, "Dwarf Version",3);
#ifdef LLVM34
m->addModuleFlag(llvm::Module::Error, "Debug Info Version",
llvm::DEBUG_METADATA_VERSION);
#endif
if (add) {
#ifdef LLVM36
jl_ExecutionEngine->addModule(std::unique_ptr<Module>(m));
#else
jl_ExecutionEngine->addModule(m);
#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 = MapValue((Function*)li->functionObject,mover.VMap,RF_None,NULL,&mover);
if (li->cFunctionObject != NULL)
li->cFunctionObject = MapValue((Function*)li->cFunctionObject,mover.VMap,RF_None,NULL,&mover);
}
#endif
Function *llvmf = (Function*)li->functionObject;
#ifdef USE_MCJIT
li->fptr = (jl_fptr_t)jl_ExecutionEngine->getFunctionAddress(llvmf->getName());
#else
li->fptr = (jl_fptr_t)jl_ExecutionEngine->getPointerToFunction(llvmf);
#endif
assert(li->fptr != NULL);
if (li->cFunctionObject != NULL) {
#ifdef USE_MCJIT
(void)jl_ExecutionEngine->getFunctionAddress(((Function*)li->cFunctionObject)->getName());
#else
(void)jl_ExecutionEngine->getPointerToFunction((Function*)li->cFunctionObject);
#endif
}
JL_SIGATOMIC_END();
if (!imaging_mode) {
llvmf->deleteBody();
if (li->cFunctionObject != NULL)
((Function*)li->cFunctionObject)->deleteBody();
}
}
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, false);
li->inCompile = 0;
}
}
void jl_cstyle_compile(jl_function_t *f)
{
jl_lambda_info_t *li = f->linfo;
if (li->cFunctionObject == NULL) {
// objective: assign li->cFunctionObject
li->inCompile = 1;
(void)to_function(li, true);
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 *jl_cfunction_object(jl_function_t *f, jl_value_t *rt, jl_value_t *argt)
{
if (rt) {
JL_TYPECHK(jl_function_ptr, type, rt);
}
JL_TYPECHK(jl_function_ptr, tuple, argt);
JL_TYPECHK(jl_function_ptr, type, argt);
if (jl_is_gf(f) && (rt == NULL || jl_is_leaf_type(rt) || rt == (jl_value_t*)jl_bottom_type) &&
jl_is_leaf_type(argt)) {
jl_function_t *ff = jl_get_specialization(f, (jl_tuple_t*)argt);
if (ff != NULL && ff->env==(jl_value_t*)jl_null && ff->linfo != NULL) {
if (ff->linfo->cFunctionObject == NULL) {
jl_cstyle_compile(ff);
}
if (ff->linfo->cFunctionObject != NULL) {
jl_lambda_info_t *li = ff->linfo;
if (!jl_types_equal((jl_value_t*)li->specTypes, argt)) {
jl_errorf("cfunction: type signature of %s does not match",
li->name->name);
}
if (rt != NULL) {
jl_value_t *astrt = jl_ast_rettype(li, li->ast);
if (!jl_types_equal(astrt, rt) &&
!(astrt==(jl_value_t*)jl_nothing->type && rt==(jl_value_t*)jl_bottom_type)) {
if (astrt == (jl_value_t*)jl_bottom_type) {
jl_errorf("cfunction: %s does not return", li->name->name);
}
else {
jl_errorf("cfunction: return type of %s does not match",
li->name->name);
}
}
}
return (Function*)ff->linfo->cFunctionObject;
}
}
}
jl_error("function is not yet c-callable");
return NULL;
}
// 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)
{
Function *llvmf = jl_cfunction_object(f, rt, argt);
assert(llvmf);
#ifdef USE_MCJIT
return (void*)jl_ExecutionEngine->getFunctionAddress(llvmf->getName());
#else
return jl_ExecutionEngine->getPointerToFunction(llvmf);
#endif
}
// 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)
{
Function *llvmf = jl_cfunction_object(f, rt, 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 ---
#include "debuginfo.cpp"
#include "disasm.cpp"
const jl_value_t *jl_dump_llvmf(void *f, bool dumpasm)
{
std::string code;
llvm::raw_string_ostream stream(code);
llvm::formatted_raw_ostream fstream(stream);
Function *llvmf = (Function*)f;
if (dumpasm == false) {
llvmf->print(stream);
}
else {
#ifdef USE_MCJIT
size_t fptr = (size_t)jl_ExecutionEngine->getFunctionAddress(llvmf->getName());
#else
size_t fptr = (size_t)jl_ExecutionEngine->getPointerToFunction(llvmf);
#endif
assert(fptr != 0);
#ifndef USE_MCJIT
std::map<size_t, FuncInfo, revcomp> &fmap = jl_jit_events->getMap();
std::map<size_t, FuncInfo, revcomp>::iterator fit = fmap.find(fptr);
if (fit == fmap.end()) {
JL_PRINTF(JL_STDERR, "Warning: Unable to find function pointer\n");
return jl_cstr_to_string(const_cast<char*>(""));
}
jl_dump_function_asm((void*)fptr, fit->second.lengthAdr, fit->second.lines, fstream);
#else // MCJIT version
std::map<size_t, ObjectInfo, revcomp> objmap = jl_jit_events->getObjectMap();
std::map<size_t, ObjectInfo, revcomp>::iterator fit = objmap.find(fptr);
if (fit == objmap.end()) {
JL_PRINTF(JL_STDERR, "Warning: Unable to find ObjectFile for function\n");
return jl_cstr_to_string(const_cast<char*>(""));
}
object::SymbolRef::Type symtype;
uint64_t symsize;
uint64_t symaddr;
#ifdef LLVM35
for (const object::SymbolRef &sym_iter : fit->second.object->symbols()) {
sym_iter.getType(symtype);
sym_iter.getAddress(symaddr);
if (symtype != object::SymbolRef::ST_Function || symaddr != fptr)
continue;
sym_iter.getSize(symsize);
jl_dump_function_asm((void*)fptr, symsize, fit->second.object, fstream);
}
#else
error_code itererr;
object::symbol_iterator sym_iter = fit->second.object->begin_symbols();
object::symbol_iterator sym_end = fit->second.object->end_symbols();
for (; sym_iter != sym_end; sym_iter.increment(itererr)) {
sym_iter->getType(symtype);
sym_iter->getAddress(symaddr);
if (symtype != object::SymbolRef::ST_Function || symaddr != fptr)
continue;
sym_iter->getSize(symsize);
jl_dump_function_asm((void*)fptr, symsize, fit->second.object, fstream);
}
#endif // LLVM35
#endif
fstream.flush();
}
return jl_cstr_to_string(const_cast<char*>(stream.str().c_str()));
}
extern "C" DLLEXPORT
void *jl_get_llvmf(jl_function_t *f, jl_tuple_t *types, bool getwrapper)
{
jl_function_t *sf = f;
if (types != NULL) {
if (!jl_is_function(f) || !jl_is_gf(f))
return NULL;
sf = jl_get_specialization(f, types);
}
if (sf == NULL || sf->linfo == NULL) {
sf = jl_method_lookup_by_type(jl_gf_mtable(f), types, 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->cFunctionObject == NULL) {
jl_cstyle_compile(sf);
}
}
if (sf->fptr == &jl_trampoline) {
if (!getwrapper && sf->linfo->cFunctionObject != NULL)
llvmf = (Function*)sf->linfo->cFunctionObject;
else
llvmf = (Function*)sf->linfo->functionObject;
}
else {
llvmf = to_function(sf->linfo, false);
}
return llvmf;
}
extern "C" DLLEXPORT
const jl_value_t *jl_dump_function(jl_function_t *f, jl_tuple_t *types, bool dumpasm, bool dumpwrapper)
{
void *llvmf = jl_get_llvmf(f,types,dumpwrapper);
if (llvmf == NULL)
return jl_cstr_to_string(const_cast<char*>(""));
return jl_dump_llvmf(llvmf,dumpasm);
}
// --- code gen for intrinsic functions ---
#include "intrinsics.cpp"
// --- constant determination ---
static bool in_vinfo(jl_sym_t *s, jl_array_t *vi)
{
size_t i, l = jl_array_len(vi);
for(i=0; i < l; i++) {
if (s == (jl_sym_t*)jl_cellref(jl_cellref(vi, i), 0))
return true;
}
return false;
}
// try to statically evaluate, NULL if not possible
extern "C"
jl_value_t *jl_static_eval(jl_value_t *ex, void *ctx_, jl_module_t *mod,
jl_value_t *sp, jl_expr_t *ast, int sparams, int allow_alloc)
{
jl_codectx_t *ctx = (jl_codectx_t*)ctx_;
if (jl_is_symbolnode(ex))
ex = (jl_value_t*)jl_symbolnode_sym(ex);
if (jl_is_symbol(ex)) {
jl_sym_t *sym = (jl_sym_t*)ex;
bool isglob;
if (ctx) {
isglob = is_global(sym, ctx);
}
else {
isglob = !in_vinfo(sym, jl_lam_vinfo(ast)) && !in_vinfo(sym, jl_lam_capt(ast));
}
if (isglob) {
size_t i;
if (sparams) {
for(i=0; i < jl_tuple_len(sp); i+=2) {
if (sym == (jl_sym_t*)jl_tupleref(sp, i)) {
// static parameter
return jl_tupleref(sp, i+1);
}
}
}
if (jl_is_const(mod, sym))
return jl_get_global(mod, sym);
}
return NULL;
}
if (jl_is_topnode(ex)) {
jl_binding_t *b = jl_get_binding(jl_base_relative_to(mod),
(jl_sym_t*)jl_fieldref(ex,0));
if (b == NULL) return NULL;
if (b->constp)
return b->value;
return NULL;
}
if (jl_is_quotenode(ex))
return jl_fieldref(ex,0);
if (jl_is_lambda_info(ex))
return NULL;
jl_module_t *m = NULL;
jl_sym_t *s = NULL;
if (jl_is_getfieldnode(ex)) {
m = (jl_module_t*)jl_static_eval(jl_fieldref(ex,0),ctx,mod,sp,ast,sparams,allow_alloc);
s = (jl_sym_t*)jl_fieldref(ex,1);
if (m && jl_is_module(m) && s && jl_is_symbol(s)) {
jl_binding_t *b = jl_get_binding(m, s);
if (b && b->constp)
return b->value;
}
return NULL;
}
if (jl_is_expr(ex)) {
jl_expr_t *e = (jl_expr_t*)ex;
if (e->head == call_sym || e->head == call1_sym) {
jl_value_t *f = jl_static_eval(jl_exprarg(e,0),ctx,mod,sp,ast,sparams,allow_alloc);
if (f && jl_is_function(f)) {
jl_fptr_t fptr = ((jl_function_t*)f)->fptr;
if (fptr == &jl_apply_generic) {
if (f == jl_get_global(jl_base_module, jl_symbol("dlsym")) ||
f == jl_get_global(jl_base_module, jl_symbol("dlopen"))) {
size_t i;
size_t n = jl_array_dim0(e->args);
jl_value_t **v;
JL_GC_PUSHARGS(v, n);
memset(v, 0, n*sizeof(jl_value_t*));
v[0] = f;
for (i = 1; i < n; i++) {
v[i] = jl_static_eval(jl_exprarg(e,i),ctx,mod,sp,ast,sparams,allow_alloc);
if (v[i] == NULL) {
JL_GC_POP();
return NULL;
}
}
jl_value_t *result = jl_apply_generic(f, v+1, (uint32_t)n-1);
JL_GC_POP();
return result;
}
}
else if (jl_array_dim0(e->args) == 3 && fptr == &jl_f_get_field) {
m = (jl_module_t*)jl_static_eval(jl_exprarg(e,1),ctx,mod,sp,ast,sparams,allow_alloc);
s = (jl_sym_t*)jl_static_eval(jl_exprarg(e,2),ctx,mod,sp,ast,sparams,allow_alloc);
if (m && jl_is_module(m) && s && jl_is_symbol(s)) {
jl_binding_t *b = jl_get_binding(m, s);
if (b && b->constp)
return b->value;
}