forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcgutils.cpp
1818 lines (1689 loc) · 68.1 KB
/
cgutils.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
// utility procedures used in code generation
static Instruction *tbaa_decorate(MDNode *md, Instruction *load_or_store)
{
load_or_store->setMetadata( llvm::LLVMContext::MD_tbaa, md );
return load_or_store;
}
static llvm::Value *prepare_call(llvm::Value *Callee)
{
if (Function *F = dyn_cast<Function>(Callee)) {
Module *M = jl_builderModule;
GlobalValue *local = M->getNamedValue(Callee->getName());
if (!local) {
local = function_proto(F, M);
}
return local;
}
return Callee;
}
// --- string constants ---
static StringMap<GlobalVariable*> stringConstants;
static Value *stringConstPtr(const std::string &txt)
{
StringRef ctxt(txt.c_str(), strlen(txt.c_str()) + 1);
#ifdef LLVM36
StringMap<GlobalVariable*>::iterator pooledval =
stringConstants.insert(std::pair<StringRef, GlobalVariable*>(ctxt, NULL)).first;
#else
StringMap<GlobalVariable*>::MapEntryTy *pooledval =
&stringConstants.GetOrCreateValue(ctxt, (GlobalVariable*)NULL);
#endif
StringRef pooledtxt = pooledval->getKey();
if (imaging_mode) {
if (pooledval->second == NULL) {
static int strno = 0;
std::stringstream ssno;
ssno << "_j_str" << strno++;
GlobalVariable *gv = new GlobalVariable(*shadow_output,
ArrayType::get(T_int8, pooledtxt.size()),
true,
GlobalVariable::PrivateLinkage,
ConstantDataArray::get(jl_LLVMContext,
ArrayRef<unsigned char>(
(const unsigned char*)pooledtxt.data(),
pooledtxt.size())),
ssno.str());
#ifdef LLVM39
gv->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
#else
gv->setUnnamedAddr(true);
#endif
pooledval->second = gv;
jl_ExecutionEngine->addGlobalMapping(gv, (void*)(uintptr_t)pooledtxt.data());
}
GlobalVariable *v = prepare_global(pooledval->second);
Value *zero = ConstantInt::get(Type::getInt32Ty(jl_LLVMContext), 0);
Value *Args[] = { zero, zero };
#ifdef LLVM37
return builder.CreateInBoundsGEP(v->getValueType(), v, Args);
#else
return builder.CreateInBoundsGEP(v, Args);
#endif
}
else {
Value *v = ConstantExpr::getIntToPtr(
ConstantInt::get(T_size, (uintptr_t)pooledtxt.data()),
T_pint8);
return v;
}
}
// --- Debug info ---
#ifdef LLVM37
static DIType *julia_type_to_di(jl_value_t *jt, DIBuilder *dbuilder, bool isboxed = false)
#else
static DIType julia_type_to_di(jl_value_t *jt, DIBuilder *dbuilder, bool isboxed = false)
#endif
{
if (isboxed)
return jl_pvalue_dillvmt;
// always return the boxed representation for types with hidden content
if (jl_is_abstracttype(jt) || !jl_is_datatype(jt) || jl_is_array_type(jt) ||
jt == (jl_value_t*)jl_sym_type || jt == (jl_value_t*)jl_module_type ||
jt == (jl_value_t*)jl_simplevector_type || jt == (jl_value_t*)jl_datatype_type ||
jt == (jl_value_t*)jl_method_instance_type)
return jl_pvalue_dillvmt;
if (jl_is_typector(jt) || jl_is_typevar(jt))
return jl_pvalue_dillvmt;
assert(jl_is_datatype(jt));
jl_datatype_t *jdt = (jl_datatype_t*)jt;
if (jdt->ditype != NULL) {
#ifdef LLVM37
DIType* t = (DIType*)jdt->ditype;
#ifndef LLVM39
// On LLVM 3.7 and 3.8, DICompositeType with a unique name
// are ref'd by their unique name and needs to be explicitly
// retained in order to be used in the module.
if (auto *Composite = dyn_cast<DICompositeType>(t)) {
if (Composite->getRawIdentifier()) {
dbuilder->retainType(Composite);
}
}
#endif
return t;
#else
return DIType((llvm::MDNode*)jdt->ditype);
#endif
}
if (jl_is_bitstype(jt)) {
uint64_t SizeInBits = 8*jdt->size;
#ifdef LLVM37
llvm::DIType *t = dbuilder->createBasicType(
jl_symbol_name(jdt->name->name),
SizeInBits,
8 * jdt->layout->alignment,
llvm::dwarf::DW_ATE_unsigned);
jdt->ditype = t;
return t;
#else
DIType t = dbuilder->createBasicType(
jl_symbol_name(jdt->name->name),
SizeInBits,
8 * jdt->layout->alignment,
llvm::dwarf::DW_ATE_unsigned);
MDNode *M = t;
jdt->ditype = M;
return t;
#endif
}
#ifdef LLVM37
else if (!jl_is_leaf_type(jt)) {
jdt->ditype = jl_pvalue_dillvmt;
return jl_pvalue_dillvmt;
}
else if (jl_is_structtype(jt)) {
jl_datatype_t *jst = (jl_datatype_t*)jt;
size_t ntypes = jl_datatype_nfields(jst);
const char *tname = jl_symbol_name(jdt->name->name);
std::stringstream unique_name;
unique_name << tname << "_" << globalUnique++;
llvm::DICompositeType *ct = dbuilder->createStructType(
NULL, // Scope
tname, // Name
NULL, // File
0, // LineNumber
8 * jdt->size, // SizeInBits
8 * jdt->layout->alignment, // AlignInBits
DIFlagZero, // Flags
NULL, // DerivedFrom
DINodeArray(), // Elements
dwarf::DW_LANG_Julia, // RuntimeLanguage
nullptr, // VTableHolder
unique_name.str() // UniqueIdentifier
);
jdt->ditype = ct;
std::vector<llvm::Metadata*> Elements;
for(unsigned i = 0; i < ntypes; i++)
Elements.push_back(julia_type_to_di(jl_svecref(jst->types,i),dbuilder,false));
dbuilder->replaceArrays(ct, dbuilder->getOrCreateArray(ArrayRef<Metadata*>(Elements)));
return ct;
}
else {
jdt->ditype = dbuilder->createTypedef(jl_pvalue_dillvmt, jl_symbol_name(jdt->name->name), NULL, 0, NULL);
return (llvm::DIType*)jdt->ditype;
}
#endif
// TODO: Fixme
return jl_pvalue_dillvmt;
}
// --- emitting pointers directly into code ---
static Value *literal_static_pointer_val(const void *p, Type *t)
{
// this function will emit a static pointer into the generated code
// the generated code will only be valid during the current session,
// and thus, this should typically be avoided in new API's
#if defined(_P64)
return ConstantExpr::getIntToPtr(ConstantInt::get(T_int64, (uint64_t)p), t);
#else
return ConstantExpr::getIntToPtr(ConstantInt::get(T_int32, (uint32_t)p), t);
#endif
}
static Value *julia_gv(const char *cname, void *addr)
{
// emit a GlobalVariable for a jl_value_t named "cname"
GlobalVariable *gv = jl_get_global_for(cname, addr, jl_builderModule);
return tbaa_decorate(tbaa_const, builder.CreateLoad(gv));
}
static Value *julia_gv(const char *prefix, jl_sym_t *name, jl_module_t *mod, void *addr)
{
// emit a GlobalVariable for a jl_value_t, using the prefix, name, and module to
// to create a readable name of the form prefixModA.ModB.name
size_t len = strlen(jl_symbol_name(name))+strlen(prefix)+1;
jl_module_t *parent = mod, *prev = NULL;
while (parent != NULL && parent != prev) {
len += strlen(jl_symbol_name(parent->name))+1;
prev = parent;
parent = parent->parent;
}
char *fullname = (char*)alloca(len);
strcpy(fullname, prefix);
len -= strlen(jl_symbol_name(name))+1;
strcpy(fullname + len, jl_symbol_name(name));
parent = mod;
prev = NULL;
while (parent != NULL && parent != prev) {
size_t part = strlen(jl_symbol_name(parent->name))+1;
strcpy(fullname+len-part,jl_symbol_name(parent->name));
fullname[len-1] = '.';
len -= part;
prev = parent;
parent = parent->parent;
}
return julia_gv(fullname, addr);
}
static GlobalVariable *julia_const_gv(jl_value_t *val);
static Value *literal_pointer_val(jl_value_t *p)
{
// emit a pointer to any jl_value_t which will be valid across reloading code
// also, try to give it a nice name for gdb, for easy identification
if (p == NULL)
return ConstantPointerNull::get((PointerType*)T_pjlvalue);
if (!imaging_mode)
return literal_static_pointer_val(p, T_pjlvalue);
if (auto gv = julia_const_gv(p)) {
return tbaa_decorate(tbaa_const, builder.CreateLoad(prepare_global(gv)));
}
if (jl_is_datatype(p)) {
jl_datatype_t *addr = (jl_datatype_t*)p;
// DataTypes are prefixed with a +
return julia_gv("+", addr->name->name, addr->name->module, p);
}
if (jl_is_method(p)) {
jl_method_t *m = (jl_method_t*)p;
// functions are prefixed with a -
return julia_gv("-", m->name, m->module, p);
}
if (jl_is_method_instance(p)) {
jl_method_instance_t *linfo = (jl_method_instance_t*)p;
// Type-inferred functions are also prefixed with a -
if (linfo->def)
return julia_gv("-", linfo->def->name, linfo->def->module, p);
}
if (jl_is_symbol(p)) {
jl_sym_t *addr = (jl_sym_t*)p;
// Symbols are prefixed with jl_sym#
return julia_gv("jl_sym#", addr, NULL, p);
}
// something else gets just a generic name
return julia_gv("jl_global#", p);
}
static Value *literal_pointer_val(jl_binding_t *p)
{
// emit a pointer to any jl_value_t which will be valid across reloading code
if (p == NULL)
return ConstantPointerNull::get((PointerType*)T_pjlvalue);
if (!imaging_mode)
return literal_static_pointer_val(p, T_pjlvalue);
// bindings are prefixed with jl_bnd#
return julia_gv("jl_bnd#", p->name, p->owner, p);
}
// bitcast a value, but preserve its address space when dealing with pointer types
static Value *emit_bitcast(Value *v, Type *jl_value)
{
if (isa<PointerType>(jl_value) &&
v->getType()->getPointerAddressSpace() != jl_value->getPointerAddressSpace()) {
// Cast to the proper address space
Type *jl_value_addr =
PointerType::get(cast<PointerType>(jl_value)->getElementType(),
v->getType()->getPointerAddressSpace());
return builder.CreateBitCast(v, jl_value_addr);
}
else {
return builder.CreateBitCast(v, jl_value);
}
}
static Value *julia_binding_gv(Value *bv)
{
return builder.
CreateGEP(bv,ConstantInt::get(T_size,
offsetof(jl_binding_t,value)/sizeof(size_t)));
}
static Value *julia_binding_gv(jl_binding_t *b)
{
// emit a literal_pointer_val to the value field of a jl_binding_t
// binding->value are prefixed with *
Value *bv = imaging_mode ?
emit_bitcast(julia_gv("*", b->name, b->owner, b), T_ppjlvalue) :
literal_static_pointer_val(b,T_ppjlvalue);
return julia_binding_gv(bv);
}
// --- mapping between julia and llvm types ---
static Type *julia_struct_to_llvm(jl_value_t *jt, bool *isboxed);
extern "C" {
JL_DLLEXPORT Type *julia_type_to_llvm(jl_value_t *jt, bool *isboxed)
{
// this function converts a Julia Type into the equivalent LLVM type
if (isboxed) *isboxed = false;
if (jt == (jl_value_t*)jl_bool_type) return T_int8;
if (jt == (jl_value_t*)jl_bottom_type) return T_void;
if (!jl_is_leaf_type(jt)) {
if (isboxed) *isboxed = true;
return T_pjlvalue;
}
if (jl_is_cpointer_type(jt)) {
Type *lt = julia_type_to_llvm(jl_tparam0(jt));
if (lt == NULL)
return NULL;
if (lt == T_void)
return T_pint8;
return PointerType::get(lt, 0);
}
if (jl_is_bitstype(jt)) {
if (jt == (jl_value_t*)jl_long_type)
return T_size;
int nb = jl_datatype_size(jt);
if (jl_is_floattype(jt)) {
#ifndef DISABLE_FLOAT16
if (nb == 2)
return T_float16;
else
#endif
if (nb == 4)
return T_float32;
else if (nb == 8)
return T_float64;
else if (nb == 16)
return T_float128;
}
return Type::getIntNTy(jl_LLVMContext, nb*8);
}
if (jl_isbits(jt)) {
if (((jl_datatype_t*)jt)->size == 0) {
return T_void;
}
return julia_struct_to_llvm(jt, isboxed);
}
if (isboxed) *isboxed = true;
return T_pjlvalue;
}
}
static Type *julia_struct_to_llvm(jl_value_t *jt, bool *isboxed)
{
// this function converts a Julia Type into the equivalent LLVM struct
// use this where C-compatible (unboxed) structs are desired
// use julia_type_to_llvm directly when you want to preserve Julia's type semantics
bool isTuple = jl_is_tuple_type(jt);
if (isboxed) *isboxed = false;
if ((isTuple || jl_is_structtype(jt)) && !jl_is_array_type(jt)) {
if (!jl_is_leaf_type(jt))
return NULL;
jl_datatype_t *jst = (jl_datatype_t*)jt;
if (jst->struct_decl == NULL) {
size_t ntypes = jl_datatype_nfields(jst);
if (ntypes == 0 || jst->size == 0)
return T_void;
StructType *structdecl;
if (!isTuple) {
structdecl = StructType::create(jl_LLVMContext, jl_symbol_name(jst->name->name));
jst->struct_decl = structdecl;
}
std::vector<Type*> latypes(0);
size_t i;
bool isarray = true;
bool isvector = true;
jl_value_t* jlasttype = NULL;
Type *lasttype = NULL;
for(i = 0; i < ntypes; i++) {
jl_value_t *ty = jl_svecref(jst->types, i);
if (jlasttype!=NULL && ty!=jlasttype)
isvector = false;
jlasttype = ty;
Type *lty;
if (jl_field_isptr(jst, i))
lty = T_pjlvalue;
else
lty = ty==(jl_value_t*)jl_bool_type ? T_int8 : julia_type_to_llvm(ty);
if (lasttype != NULL && lasttype != lty)
isarray = false;
lasttype = lty;
if (type_is_ghost(lty))
lty = NoopType;
latypes.push_back(lty);
}
if (!isTuple) {
if (jl_is_vecelement_type(jt))
// VecElement type is unwrapped in LLVM
jst->struct_decl = latypes[0];
else
structdecl->setBody(latypes);
}
else {
if (isarray && lasttype != T_int1 && !type_is_ghost(lasttype)) {
if (isvector && jl_special_vector_alignment(ntypes, jlasttype)!=0)
jst->struct_decl = VectorType::get(lasttype, ntypes);
else
jst->struct_decl = ArrayType::get(lasttype, ntypes);
}
else {
jst->struct_decl = StructType::get(jl_LLVMContext,ArrayRef<Type*>(&latypes[0],ntypes));
}
}
#ifndef NDEBUG
// If LLVM and Julia disagree about alignment, much trouble ensues, so check it!
const DataLayout &DL =
#ifdef LLVM36
jl_ExecutionEngine->getDataLayout();
#else
*jl_ExecutionEngine->getDataLayout();
#endif
unsigned llvm_alignment = DL.getABITypeAlignment((Type*)jst->struct_decl);
unsigned julia_alignment = jst->layout->alignment;
assert(llvm_alignment == julia_alignment);
#endif
}
return (Type*)jst->struct_decl;
}
return julia_type_to_llvm(jt, isboxed);
}
static bool is_datatype_all_pointers(jl_datatype_t *dt)
{
size_t i, l = jl_datatype_nfields(dt);
for(i=0; i < l; i++) {
if (!jl_field_isptr(dt, i)) {
return false;
}
}
return true;
}
static bool is_tupletype_homogeneous(jl_svec_t *t)
{
size_t i, l = jl_svec_len(t);
if (l > 0) {
jl_value_t *t0 = jl_svecref(t, 0);
if (!jl_is_leaf_type(t0))
return false;
for(i=1; i < l; i++) {
if (!jl_types_equal(t0, jl_svecref(t,i)))
return false;
}
}
return true;
}
static bool deserves_sret(jl_value_t *dt, Type *T)
{
assert(jl_is_datatype(dt));
return (size_t)jl_datatype_size(dt) > sizeof(void*) && !T->isFloatingPointTy() && !T->isVectorTy();
}
// --- generating various field accessors ---
static Value *emit_nthptr_addr(Value *v, ssize_t n)
{
return builder.CreateGEP(emit_bitcast(v, T_ppjlvalue),
ConstantInt::get(T_size, n));
}
static Value *emit_nthptr_addr(Value *v, Value *idx)
{
return builder.CreateGEP(emit_bitcast(v, T_ppjlvalue), idx);
}
static Value *emit_nthptr(Value *v, ssize_t n, MDNode *tbaa)
{
// p = (jl_value_t**)v; p[n]
Value *vptr = emit_nthptr_addr(v, n);
return tbaa_decorate(tbaa,builder.CreateLoad(vptr, false));
}
static Value *emit_nthptr_recast(Value *v, Value *idx, MDNode *tbaa, Type *ptype)
{
// p = (jl_value_t**)v; *(ptype)&p[n]
Value *vptr = emit_nthptr_addr(v, idx);
return tbaa_decorate(tbaa,builder.CreateLoad(emit_bitcast(vptr,ptype), false));
}
static Value *emit_nthptr_recast(Value *v, ssize_t n, MDNode *tbaa, Type *ptype)
{
// p = (jl_value_t**)v; *(ptype)&p[n]
Value *vptr = emit_nthptr_addr(v, n);
return tbaa_decorate(tbaa,builder.CreateLoad(emit_bitcast(vptr,ptype), false));
}
static Value *emit_typeptr_addr(Value *p)
{
ssize_t offset = (sizeof(jl_taggedvalue_t) -
offsetof(jl_taggedvalue_t, type)) / sizeof(jl_value_t*);
return emit_nthptr_addr(p, -offset);
}
static Value *boxed(const jl_cgval_t &v, jl_codectx_t *ctx, bool gcooted=true);
static Value *boxed(const jl_cgval_t &v, jl_codectx_t *ctx, jl_value_t* type) = delete; // C++11 (temporary to prevent rebase error)
static Value *emit_typeof(Value *tt)
{
// given p, a jl_value_t*, compute its type tag
assert(tt->getType() == T_pjlvalue);
tt = tbaa_decorate(tbaa_tag, builder.CreateLoad(emit_typeptr_addr(tt), false));
tt = builder.CreateIntToPtr(builder.CreateAnd(
builder.CreatePtrToInt(tt, T_size),
ConstantInt::get(T_size,~(uintptr_t)15)),
T_pjlvalue);
return tt;
}
static jl_cgval_t emit_typeof(const jl_cgval_t &p, jl_codectx_t *ctx)
{
// given p, compute its type
if (!p.constant && p.isboxed && !jl_is_leaf_type(p.typ)) {
return mark_julia_type(emit_typeof(p.V), true, jl_datatype_type, ctx, /*needsroot*/false);
}
jl_value_t *aty = p.typ;
if (jl_is_type_type(aty)) // convert Int::Type{Int} ==> typeof(Int) ==> DataType
// but convert 1::Type{1} ==> typeof(1) ==> Int
aty = (jl_value_t*)jl_typeof(jl_tparam0(aty));
return mark_julia_const(aty);
}
static Value *emit_typeof_boxed(const jl_cgval_t &p, jl_codectx_t *ctx)
{
return boxed(emit_typeof(p, ctx), ctx);
}
static Value *emit_datatype_types(Value *dt)
{
return tbaa_decorate(tbaa_const, builder.
CreateLoad(emit_bitcast(builder.
CreateGEP(emit_bitcast(dt, T_pint8),
ConstantInt::get(T_size, offsetof(jl_datatype_t, types))),
T_ppjlvalue)));
}
static Value *emit_datatype_nfields(Value *dt)
{
Value *nf = tbaa_decorate(tbaa_const, builder.CreateLoad(
tbaa_decorate(tbaa_const, builder.CreateLoad(
emit_bitcast(
builder.CreateGEP(
emit_bitcast(dt, T_pint8),
ConstantInt::get(T_size, offsetof(jl_datatype_t, types))),
T_pint32->getPointerTo())))));
#ifdef _P64
nf = builder.CreateSExt(nf, T_int64);
#endif
return nf;
}
static Value *emit_datatype_size(Value *dt)
{
Value *size = tbaa_decorate(tbaa_const, builder.
CreateLoad(emit_bitcast(builder.
CreateGEP(emit_bitcast(dt, T_pint8),
ConstantInt::get(T_size, offsetof(jl_datatype_t, size))),
T_pint32)));
return size;
}
static Value *emit_datatype_mutabl(Value *dt)
{
Value *mutabl = tbaa_decorate(tbaa_const, builder.
CreateLoad(builder.CreateGEP(emit_bitcast(dt, T_pint8),
ConstantInt::get(T_size, offsetof(jl_datatype_t, mutabl)))));
return builder.CreateTrunc(mutabl, T_int1);
}
static Value *emit_datatype_abstract(Value *dt)
{
Value *abstract = tbaa_decorate(tbaa_const, builder.
CreateLoad(builder.CreateGEP(emit_bitcast(dt, T_pint8),
ConstantInt::get(T_size, offsetof(jl_datatype_t, abstract)))));
return builder.CreateTrunc(abstract, T_int1);
}
static Value *emit_datatype_isbitstype(Value *dt)
{
Value *immut = builder.CreateXor(emit_datatype_mutabl(dt), ConstantInt::get(T_int1, -1));
Value *nofields = builder.CreateICmpEQ(emit_datatype_nfields(dt), ConstantInt::get(T_size, 0));
Value *isbitstype = builder.CreateAnd(immut, builder.CreateAnd(nofields,
builder.CreateXor(builder.CreateAnd(emit_datatype_abstract(dt),
builder.CreateICmpSGT(emit_datatype_size(dt), ConstantInt::get(T_int32, 0))),
ConstantInt::get(T_int1, -1))));
return isbitstype;
}
static Value *emit_datatype_name(Value *dt)
{
return emit_nthptr(dt, (ssize_t)(offsetof(jl_datatype_t,name)/sizeof(char*)),
tbaa_const);
}
// --- generating various error checks ---
// Do not use conditional throw for cases that type inference can know
// the error is always thrown. This may cause non dominated use
// of SSA value error in the verifier.
static void just_emit_error(const std::string &txt, jl_codectx_t *ctx)
{
builder.CreateCall(prepare_call(jlerror_func), stringConstPtr(txt));
}
static void emit_error(const std::string &txt, jl_codectx_t *ctx)
{
just_emit_error(txt, ctx);
builder.CreateUnreachable();
BasicBlock *cont = BasicBlock::Create(jl_LLVMContext,"after_error",ctx->f);
builder.SetInsertPoint(cont);
}
// DO NOT PASS IN A CONST CONDITION!
static void error_unless(Value *cond, const std::string &msg, jl_codectx_t *ctx)
{
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext,"fail",ctx->f);
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext,"pass");
builder.CreateCondBr(cond, passBB, failBB);
builder.SetInsertPoint(failBB);
just_emit_error(msg, ctx);
builder.CreateUnreachable();
ctx->f->getBasicBlockList().push_back(passBB);
builder.SetInsertPoint(passBB);
}
static void raise_exception(Value *exc, jl_codectx_t *ctx,
BasicBlock *contBB=nullptr)
{
#ifdef LLVM37
builder.CreateCall(prepare_call(jlthrow_func), { exc });
#else
builder.CreateCall(prepare_call(jlthrow_func), exc);
#endif
builder.CreateUnreachable();
if (!contBB) {
contBB = BasicBlock::Create(jl_LLVMContext, "after_throw", ctx->f);
}
else {
ctx->f->getBasicBlockList().push_back(contBB);
}
builder.SetInsertPoint(contBB);
}
// DO NOT PASS IN A CONST CONDITION!
static void raise_exception_unless(Value *cond, Value *exc, jl_codectx_t *ctx)
{
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext,"fail",ctx->f);
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext,"pass");
builder.CreateCondBr(cond, passBB, failBB);
builder.SetInsertPoint(failBB);
raise_exception(exc, ctx, passBB);
}
// DO NOT PASS IN A CONST CONDITION!
static void raise_exception_if(Value *cond, Value *exc, jl_codectx_t *ctx)
{
raise_exception_unless(builder.CreateXor(cond, ConstantInt::get(T_int1,-1)),
exc, ctx);
}
static void null_pointer_check(Value *v, jl_codectx_t *ctx)
{
raise_exception_unless(builder.CreateICmpNE(v,Constant::getNullValue(v->getType())),
literal_pointer_val(jl_undefref_exception), ctx);
}
static void emit_type_error(const jl_cgval_t &x, jl_value_t *type, const std::string &msg,
jl_codectx_t *ctx)
{
Value *fname_val = stringConstPtr(ctx->funcName);
Value *msg_val = stringConstPtr(msg);
#ifdef LLVM37
builder.CreateCall(prepare_call(jltypeerror_func),
{ fname_val, msg_val,
literal_pointer_val(type), boxed(x, ctx, false)}); // x is rooted by jl_type_error_rt
#else
builder.CreateCall4(prepare_call(jltypeerror_func),
fname_val, msg_val,
literal_pointer_val(type), boxed(x, ctx, false)); // x is rooted by jl_type_error_rt
#endif
}
static void emit_typecheck(const jl_cgval_t &x, jl_value_t *type, const std::string &msg,
jl_codectx_t *ctx)
{
Value *istype;
// if (jl_subtype(x.typ, type, 0)) {
// // This case should already be handled by the caller
// return;
// }
if (jl_type_intersection(x.typ, type) == (jl_value_t*)jl_bottom_type) {
emit_type_error(x, type, msg, ctx);
builder.CreateUnreachable();
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext, "fail", ctx->f);
builder.SetInsertPoint(failBB);
return;
}
else if (jl_is_type_type(type) || !jl_is_leaf_type(type)) {
Value *vx = boxed(x, ctx);
istype = builder.
CreateICmpNE(
#ifdef LLVM37
builder.CreateCall(prepare_call(jlsubtype_func), { vx, literal_pointer_val(type),
ConstantInt::get(T_int32,1) }),
#else
builder.CreateCall3(prepare_call(jlsubtype_func), vx, literal_pointer_val(type),
ConstantInt::get(T_int32,1)),
#endif
ConstantInt::get(T_int32,0));
}
else {
istype = builder.CreateICmpEQ(emit_typeof_boxed(x,ctx), literal_pointer_val(type));
}
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext,"fail",ctx->f);
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext,"pass");
builder.CreateCondBr(istype, passBB, failBB);
builder.SetInsertPoint(failBB);
emit_type_error(x, type, msg, ctx);
builder.CreateUnreachable();
ctx->f->getBasicBlockList().push_back(passBB);
builder.SetInsertPoint(passBB);
}
#define CHECK_BOUNDS 1
static Value *emit_bounds_check(const jl_cgval_t &ainfo, jl_value_t *ty, Value *i, Value *len, jl_codectx_t *ctx)
{
Value *im1 = builder.CreateSub(i, ConstantInt::get(T_size, 1));
#if CHECK_BOUNDS==1
if ((!ctx->is_inbounds &&
jl_options.check_bounds != JL_OPTIONS_CHECK_BOUNDS_OFF) ||
jl_options.check_bounds == JL_OPTIONS_CHECK_BOUNDS_ON) {
Value *ok = builder.CreateICmpULT(im1, len);
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext,"fail",ctx->f);
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext,"pass");
builder.CreateCondBr(ok, passBB, failBB);
builder.SetInsertPoint(failBB);
if (!ty) { // jl_value_t** tuple (e.g. the vararg)
#ifdef LLVM37
builder.CreateCall(prepare_call(jlvboundserror_func), { ainfo.V, len, i });
#else
builder.CreateCall3(prepare_call(jlvboundserror_func), ainfo.V, len, i);
#endif
}
else if (ainfo.isboxed) { // jl_datatype_t or boxed jl_value_t
#ifdef LLVM37
builder.CreateCall(prepare_call(jlboundserror_func), { boxed(ainfo, ctx), i });
#else
builder.CreateCall2(prepare_call(jlboundserror_func), boxed(ainfo, ctx), i);
#endif
}
else { // unboxed jl_value_t*
Value *a = ainfo.V;
if (ainfo.isghost) {
a = Constant::getNullValue(T_pint8);
}
else if (!ainfo.ispointer()) {
// CreateAlloca is OK here since we are on an error branch
Value *tempSpace = builder.CreateAlloca(a->getType());
builder.CreateStore(a, tempSpace);
a = tempSpace;
}
#ifdef LLVM37
builder.CreateCall(prepare_call(jluboundserror_func), {
builder.CreatePointerCast(a, T_pint8),
literal_pointer_val(ty),
i });
#else
builder.CreateCall3(prepare_call(jluboundserror_func),
builder.CreatePointerCast(a, T_pint8),
literal_pointer_val(ty),
i);
#endif
}
builder.CreateUnreachable();
ctx->f->getBasicBlockList().push_back(passBB);
builder.SetInsertPoint(passBB);
}
#endif
return im1;
}
// --- loading and storing ---
// If given alignment is 0 and LLVM's assumed alignment for a load/store via ptr
// might be stricter than the Julia alignment for jltype, return the alignment of jltype.
// Otherwise return the given alignment.
//
// Parameter ptr should be the pointer argument for the LoadInst or StoreInst.
// It is currently unused, but might be used in the future for a more precise answer.
static unsigned julia_alignment(Value* /*ptr*/, jl_value_t *jltype, unsigned alignment)
{
if (!alignment && ((jl_datatype_t*)jltype)->layout->alignment > MAX_ALIGN) {
// Type's natural alignment exceeds strictest alignment promised in heap, so return the heap alignment.
return MAX_ALIGN;
}
return alignment;
}
static LoadInst *build_load(Value *ptr, jl_value_t *jltype)
{
return builder.CreateAlignedLoad(ptr, julia_alignment(ptr, jltype, 0));
}
static Value *emit_unbox(Type *to, const jl_cgval_t &x, jl_value_t *jt, Value* dest = NULL, bool volatile_store = false);
static jl_cgval_t typed_load(Value *ptr, Value *idx_0based, jl_value_t *jltype,
jl_codectx_t *ctx, MDNode *tbaa, unsigned alignment = 0)
{
bool isboxed;
Type *elty = julia_type_to_llvm(jltype, &isboxed);
assert(elty != NULL);
if (type_is_ghost(elty))
return ghostValue(jltype);
Value *data;
// TODO: preserving_pointercast?
if (ptr->getType()->getContainedType(0) != elty)
data = builder.CreatePointerCast(ptr, PointerType::get(elty, 0));
else
data = ptr;
if (idx_0based)
data = builder.CreateGEP(data, idx_0based);
Value *elt;
// TODO: can only lazy load if we can create a gc root for ptr for the lifetime of elt
//if (elty->isAggregateType() && tbaa == tbaa_immut && !alignment) { // can lazy load on demand, no copy needed
// elt = data;
//}
//else {
Instruction *load = builder.CreateAlignedLoad(data, isboxed ? alignment : julia_alignment(data, jltype, alignment), false);
if (tbaa) {
elt = tbaa_decorate(tbaa, load);
}
else {
elt = load;
}
if (isboxed) {
null_pointer_check(elt, ctx);
}
//}
return mark_julia_type(elt, isboxed, jltype, ctx);
}
static void typed_store(Value *ptr, Value *idx_0based, const jl_cgval_t &rhs,
jl_value_t *jltype, jl_codectx_t *ctx, MDNode *tbaa,
Value *parent, // for the write barrier, NULL if no barrier needed
unsigned alignment = 0, bool root_box = true) // if the value to store needs a box, should we root it ?
{
bool isboxed;
Type *elty = julia_type_to_llvm(jltype, &isboxed);
assert(elty != NULL);
if (type_is_ghost(elty))
return;
Value *r;
if (!isboxed) {
r = emit_unbox(elty, rhs, jltype);
}
else {
r = boxed(rhs, ctx, root_box);
if (parent != NULL) emit_write_barrier(ctx, parent, r);
}
Value *data;
if (ptr->getType()->getContainedType(0) != elty)
data = emit_bitcast(ptr, PointerType::get(elty, 0));
else
data = ptr;
Instruction *store = builder.CreateAlignedStore(r, builder.CreateGEP(data, idx_0based), isboxed ? alignment : julia_alignment(r, jltype, alignment));
if (tbaa)
tbaa_decorate(tbaa, store);
}
// --- convert boolean value to julia ---
static Value *julia_bool(Value *cond)
{
return builder.CreateSelect(cond, literal_pointer_val(jl_true),
literal_pointer_val(jl_false));
}
// --- get the inferred type of an AST node ---
static inline jl_module_t *topmod(jl_codectx_t *ctx)
{
return jl_base_relative_to(ctx->module);
}
static jl_value_t *expr_type(jl_value_t *e, jl_codectx_t *ctx)
{
if (jl_is_ssavalue(e)) {
if (jl_is_long(ctx->source->ssavaluetypes))
return (jl_value_t*)jl_any_type;
int idx = ((jl_ssavalue_t*)e)->id;
assert(jl_is_array(ctx->source->ssavaluetypes));
jl_array_t *ssavalue_types = (jl_array_t*)ctx->source->ssavaluetypes;
return jl_array_ptr_ref(ssavalue_types, idx);
}
if (jl_typeis(e, jl_slotnumber_type)) {
jl_array_t *slot_types = (jl_array_t*)ctx->source->slottypes;
if (!jl_is_array(slot_types))
return (jl_value_t*)jl_any_type;
return jl_array_ptr_ref(slot_types, jl_slot_number(e)-1);
}
if (jl_typeis(e, jl_typedslot_type)) {
jl_value_t *typ = jl_typedslot_get_type(e);
if (jl_is_typevar(typ))
typ = ((jl_tvar_t*)typ)->ub;
return typ;
}
if (jl_is_expr(e)) {
if (((jl_expr_t*)e)->head == static_parameter_sym) {
size_t idx = jl_unbox_long(jl_exprarg(e,0))-1;
if (idx >= jl_svec_len(ctx->linfo->sparam_vals))
return (jl_value_t*)jl_any_type;
e = jl_svecref(ctx->linfo->sparam_vals, idx);
if (jl_is_typevar(e))
return (jl_value_t*)jl_any_type;
goto type_of_constant;
}
jl_value_t *typ = ((jl_expr_t*)e)->etype;
if (jl_is_typevar(typ))
typ = ((jl_tvar_t*)typ)->ub;
return typ;
}
if (jl_is_quotenode(e)) {
e = jl_fieldref(e,0);
goto type_of_constant;
}
if (jl_is_globalref(e)) {
jl_sym_t *s = (jl_sym_t*)jl_globalref_name(e);
jl_binding_t *b = jl_get_binding(jl_globalref_mod(e), s);
if (b && b->constp) {
e = b->value;
goto type_of_constant;
}
return (jl_value_t*)jl_any_type;
}
if (jl_is_symbol(e)) {
jl_binding_t *b = jl_get_binding(ctx->module, (jl_sym_t*)e);
if (!b || !b->value)
return (jl_value_t*)jl_any_type;
if (b->constp)
e = b->value;
else
return (jl_value_t*)jl_any_type;
}
type_of_constant:
if (jl_is_datatype(e) || jl_is_uniontype(e) || jl_is_typector(e))
return (jl_value_t*)jl_wrap_Type(e);
return (jl_value_t*)jl_typeof(e);
}
// --- accessing the representations of built-in data types ---
static Value *data_pointer(const jl_cgval_t &x, jl_codectx_t *ctx, Type *astype = T_ppjlvalue)
{
Value *data = x.constant ? boxed(x, ctx) : x.V;
if (data->getType() != astype)
data = emit_bitcast(data, astype);
return data;
}
static bool emit_getfield_unknownidx(jl_cgval_t *ret, const jl_cgval_t &strct, Value *idx, jl_datatype_t *stt, jl_codectx_t *ctx)
{
size_t nfields = jl_datatype_nfields(stt);
if (strct.ispointer()) { // boxed or stack
if (is_datatype_all_pointers(stt)) {
idx = emit_bounds_check(strct, (jl_value_t*)stt, idx, ConstantInt::get(T_size, nfields), ctx);
Value *fld = tbaa_decorate(strct.tbaa, builder.CreateLoad(
builder.CreateGEP(data_pointer(strct, ctx), idx)));
if ((unsigned)stt->ninitialized != nfields)
null_pointer_check(fld, ctx);
*ret = mark_julia_type(fld, true, jl_any_type, ctx, strct.gcroot || !strct.isimmutable);
return true;
}
else if (is_tupletype_homogeneous(stt->types)) {
assert(nfields > 0); // nf == 0 trapped by all_pointers case
jl_value_t *jt = jl_field_type(stt, 0);
idx = emit_bounds_check(strct, (jl_value_t*)stt, idx, ConstantInt::get(T_size, nfields), ctx);
Value *ptr = data_pointer(strct, ctx);
if (!stt->mutabl) {
// just compute the pointer and let user load it when necessary
Type *fty = julia_type_to_llvm(jt);