-
-
Notifications
You must be signed in to change notification settings - Fork 597
/
objc_glue.d
1642 lines (1350 loc) · 45.9 KB
/
objc_glue.d
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
/**
* Glue code for Objective-C interop.
*
* Copyright: Copyright (C) 2015-2021 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 http://www.digitalmars.com, Walter Bright)
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/objc_glue.d, _objc_glue.d)
* Documentation: https://dlang.org/phobos/dmd_objc_glue.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/objc_glue.d
*/
module dmd.objc_glue;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import dmd.aggregate;
import dmd.arraytypes;
import dmd.dclass;
import dmd.declaration;
import dmd.dmodule;
import dmd.dsymbol;
import dmd.expression;
import dmd.func;
import dmd.glue;
import dmd.identifier;
import dmd.mtype;
import dmd.objc;
import dmd.target;
import dmd.root.stringtable;
import dmd.root.array;
import dmd.backend.dt;
import dmd.backend.cc;
import dmd.backend.cdef;
import dmd.backend.el;
import dmd.backend.global;
import dmd.backend.oper;
import dmd.backend.outbuf;
import dmd.backend.ty;
import dmd.backend.type;
import dmd.backend.mach;
import dmd.backend.obj;
private __gshared ObjcGlue _objc;
ObjcGlue objc()
{
return _objc;
}
// Should be an interface
extern(C++) abstract class ObjcGlue
{
static struct ElemResult
{
elem* ec;
elem* ethis;
}
static void initialize()
{
if (target.objc.supported)
_objc = new Supported;
else
_objc = new Unsupported;
}
/// Resets the Objective-C glue layer.
abstract void reset();
abstract void setupMethodSelector(FuncDeclaration fd, elem** esel);
abstract ElemResult setupMethodCall(FuncDeclaration fd, TypeFunction tf,
bool directcall, elem* ec, elem* ehidden, elem* ethis);
abstract void setupEp(elem* esel, elem** ep, int leftToRight);
abstract void generateModuleInfo(Module module_);
/// Returns: the given expression converted to an `elem` structure
abstract elem* toElem(ObjcClassReferenceExp e) const;
/// Outputs the given Objective-C class to the object file.
abstract void toObjFile(ClassDeclaration classDeclaration) const;
/**
* Adds the selector parameter to the given list of parameters.
*
* For Objective-C methods the selector parameter is added. For
* non-Objective-C methods `parameters` is unchanged.
*
* Params:
* functionDeclaration = the function declaration to add the selector
* parameter from
* parameters = the list of parameters to add the selector parameter to
* parameterCount = the number of parameters
*
* Returns: the new number of parameters
*/
abstract size_t addSelectorParameterSymbol(
FuncDeclaration functionDeclaration,
Symbol** parameters, size_t parameterCount) const;
/**
* Returns the offset of the given variable declaration `var`.
*
* This is used in a `DotVarExp` to get the offset of the variable the
* expression is accessing.
*
* Instance variables in Objective-C are non-fragile. That means that the
* base class can change (add or remove instance variables) without the
* subclasses needing to recompile or relink. This is implemented instance
* variables having a dynamic offset. This is achieved by going through an
* indirection in the form of a symbol generated in the binary. The compiler
* outputs the static offset in the generated symbol. Then, at load time,
* the symbol is updated with the correct offset, if necessary.
*
* Params:
* var = the variable declaration to return the offset of
* type = the type of the `DotVarExp`
* offset = the existing offset
*
* Returns: a symbol containing the offset of the variable declaration
*/
abstract elem* getOffset(VarDeclaration var, Type type, elem* offset) const;
}
private:
extern(C++) final class Unsupported : ObjcGlue
{
override void reset()
{
// noop
}
override void setupMethodSelector(FuncDeclaration fd, elem** esel)
{
// noop
}
override ElemResult setupMethodCall(FuncDeclaration, TypeFunction, bool,
elem*, elem*, elem*)
{
assert(0, "Should never be called when Objective-C is not supported");
}
override void setupEp(elem* esel, elem** ep, int reverse)
{
// noop
}
override void generateModuleInfo(Module)
{
// noop
}
override elem* toElem(ObjcClassReferenceExp e) const
{
assert(0, "Should never be called when Objective-C is not supported");
}
override void toObjFile(ClassDeclaration classDeclaration) const
{
assert(0, "Should never be called when Objective-C is not supported");
}
override size_t addSelectorParameterSymbol(FuncDeclaration, Symbol**,
size_t count) const
{
return count;
}
override elem* getOffset(VarDeclaration var, Type type, elem* offset) const
{
return offset;
}
}
extern(C++) final class Supported : ObjcGlue
{
extern (D) this()
{
Segments.initialize();
Symbols.initialize();
}
override void reset()
{
Segments.reset();
Symbols.reset();
}
override void setupMethodSelector(FuncDeclaration fd, elem** esel)
{
if (fd && fd.objc.selector && !*esel)
{
*esel = el_var(Symbols.getMethVarRef(fd.objc.selector.toString()));
}
}
override ElemResult setupMethodCall(FuncDeclaration fd, TypeFunction tf,
bool directcall, elem* ec, elem* ehidden, elem* ethis)
{
import dmd.e2ir : addressElem;
if (directcall) // super call
{
ElemResult result;
// call through Objective-C runtime dispatch
result.ec = el_var(Symbols.getMsgSendSuper(ehidden !is null));
// need to change this pointer to a pointer to an two-word
// objc_super struct of the form { this ptr, class ptr }.
auto cd = fd.isThis.isClassDeclaration;
assert(cd, "call to objc_msgSendSuper with no class declaration");
// faking objc_super type as delegate
auto classRef = el_var(Symbols.getClassReference(cd));
auto super_ = el_pair(TYdelegate, ethis, classRef);
result.ethis = addressElem(super_, tf);
return result;
}
else
{
// make objc-style "virtual" call using dispatch function
assert(ethis);
Type tret = tf.next;
ElemResult result = {
ec: el_var(Symbols.getMsgSend(tret, ehidden !is null)),
ethis: ethis
};
return result;
}
}
override void setupEp(elem* esel, elem** ep, int leftToRight)
{
if (esel)
{
// using objc-style "virtual" call
// add hidden argument (second to 'this') for selector used by dispatch function
if (leftToRight)
*ep = el_param(esel, *ep);
else
*ep = el_param(*ep, esel);
}
}
override void generateModuleInfo(Module module_)
{
ClassDeclarations classes;
ClassDeclarations categories;
module_.members.foreachDsymbol(m => m.addObjcSymbols(&classes, &categories));
if (classes.length || categories.length || Symbols.hasSymbols)
Symbols.getModuleInfo(classes, categories);
}
override elem* toElem(ObjcClassReferenceExp e) const
{
return el_var(Symbols.getClassReference(e.classDeclaration));
}
override void toObjFile(ClassDeclaration classDeclaration) const
in
{
assert(classDeclaration !is null);
assert(classDeclaration.classKind == ClassKind.objc);
}
do
{
if (!classDeclaration.objc.isMeta)
ObjcClassDeclaration(classDeclaration, false).toObjFile();
}
override size_t addSelectorParameterSymbol(FuncDeclaration fd,
Symbol** params, size_t count) const
in
{
assert(fd);
}
do
{
if (!fd.objc.selector)
return count;
assert(fd.objc.selectorParameter);
auto selectorSymbol = fd.objc.selectorParameter.toSymbol();
memmove(params + 1, params, count * params[0].sizeof);
params[0] = selectorSymbol;
return count + 1;
}
override elem* getOffset(VarDeclaration var, Type type, elem* offset) const
{
auto typeClass = type.isTypeClass;
if (!typeClass || typeClass.sym.classKind != ClassKind.objc)
return offset;
return el_var(ObjcClassDeclaration(typeClass.sym, false).getIVarOffset(var));
}
}
struct Segments
{
enum Id
{
classlist,
classname,
classrefs,
const_,
objcData,
imageinfo,
ivar,
methname,
methtype,
selrefs,
protolist,
data
}
private
{
__gshared int[Id] segments;
__gshared Segments[Id] segmentData;
immutable(char*) sectionName;
immutable(char*) segmentName;
immutable int flags;
immutable int alignment;
this(typeof(this.tupleof) tuple)
{
this.tupleof = tuple;
}
static void initialize()
{
segmentData = [
Id.classlist: Segments("__objc_classlist", "__DATA", S_REGULAR | S_ATTR_NO_DEAD_STRIP, 3),
Id.classname: Segments("__objc_classname", "__TEXT", S_CSTRING_LITERALS, 0),
Id.classrefs: Segments("__objc_classrefs", "__DATA", S_REGULAR | S_ATTR_NO_DEAD_STRIP, 3),
Id.const_: Segments("__objc_const", "__DATA", S_REGULAR, 3),
Id.objcData: Segments("__objc_data", "__DATA", S_REGULAR, 3),
Id.imageinfo: Segments("__objc_imageinfo", "__DATA", S_REGULAR | S_ATTR_NO_DEAD_STRIP, 0),
Id.ivar: Segments("__objc_ivar", "__DATA", S_REGULAR, 3),
Id.methname: Segments("__objc_methname", "__TEXT", S_CSTRING_LITERALS, 0),
Id.methtype: Segments("__objc_methtype", "__TEXT", S_CSTRING_LITERALS, 0),
Id.selrefs: Segments("__objc_selrefs", "__DATA", S_LITERAL_POINTERS | S_ATTR_NO_DEAD_STRIP, 3),
Id.protolist: Segments("__objc_protolist", "__DATA", S_COALESCED | S_ATTR_NO_DEAD_STRIP, 3),
Id.data: Segments("__data", "__DATA", S_REGULAR, 3),
];
}
}
/// Resets the segments.
static void reset()
{
clearCache();
}
// Clears any caches.
private static void clearCache()
{
segments.clear;
}
static int opIndex(Id id)
{
if (auto segment = id in segments)
return *segment;
const seg = segmentData[id];
version (OSX)
{
return segments[id] = Obj.getsegment(
seg.sectionName,
seg.segmentName,
seg.alignment,
seg.flags
);
}
else
{
// This should never happen. If the platform is not OSX an error
// should have occurred sooner which should have prevented the
// code from getting here.
assert(0);
}
}
}
struct Symbols
{
static:
private __gshared
{
alias SymbolCache = StringTable!(Symbol*)*;
bool hasSymbols_ = false;
Symbol* objc_msgSend = null;
Symbol* objc_msgSend_stret = null;
Symbol* objc_msgSend_fpret = null;
Symbol* objc_msgSend_fp2ret = null;
Symbol* objc_msgSendSuper = null;
Symbol* objc_msgSendSuper_stret = null;
Symbol* imageInfo = null;
Symbol* moduleInfo = null;
Symbol* emptyCache = null;
Symbol* emptyVTable = null;
// Cache for `_OBJC_METACLASS_$_`/`_OBJC_CLASS_$_` symbols.
SymbolCache classNameTable = null;
// Cache for `L_OBJC_CLASSLIST_REFERENCES_` symbols.
SymbolCache classReferenceTable = null;
// Cache for `__OBJC_PROTOCOL_$_` symbols.
SymbolCache protocolTable = null;
SymbolCache methVarNameTable = null;
SymbolCache methVarRefTable = null;
SymbolCache methVarTypeTable = null;
// Cache for instance variable offsets
SymbolCache ivarOffsetTable = null;
}
void initialize()
{
initializeStringTables();
}
private void initializeStringTables()
{
alias This = typeof(this);
foreach (m ; __traits(allMembers, This))
{
static if (is(typeof(__traits(getMember, This, m)) == SymbolCache))
{
__traits(getMember, This, m) = new StringTable!(Symbol*)();
__traits(getMember, This, m)._init();
}
}
}
/// Resets the symbols.
void reset()
{
clearCache();
resetSymbolCache();
}
// Clears any caches.
private void clearCache()
{
alias This = typeof(this);
foreach (m ; __traits(allMembers, This))
{
static if (is(typeof(__traits(getMember, This, m)) == Symbol*))
__traits(getMember, This, m) = null;
}
}
// Resets the symbol caches.
private void resetSymbolCache()
{
alias This = typeof(this);
foreach (m ; __traits(allMembers, This))
{
static if (is(typeof(__traits(getMember, This, m)) == SymbolCache))
__traits(getMember, This, m).reset();
}
}
bool hasSymbols()
{
if (hasSymbols_)
return true;
alias This = typeof(this);
foreach (m ; __traits(allMembers, This))
{
static if (is(typeof(__traits(getMember, This, m)) == Symbol*))
{
if (__traits(getMember, This, m) !is null)
return true;
}
}
return false;
}
/**
* Convenience wrapper around `dmd.backend.global.symbol_name`.
*
* Allows to pass the name of the symbol as a D string.
*/
Symbol* symbolName(const(char)[] name, int sclass, type* t)
{
return symbol_name(name.ptr, cast(uint) name.length, sclass, t);
}
/**
* Gets a global symbol.
*
* Params:
* name = the name of the symbol
* t = the type of the symbol
*
* Returns: the symbol
*/
Symbol* getGlobal(const(char)[] name, type* t = type_fake(TYnptr))
{
return symbolName(name, SCglobal, t);
}
/**
* Gets a static symbol.
*
* Params:
* name = the name of the symbol
* t = the type of the symbol
*
* Returns: the symbol
*/
Symbol* getStatic(const(char)[] name, type* t = type_fake(TYnptr))
{
return symbolName(name, SCstatic, t);
}
Symbol* getCString(const(char)[] str, const(char)[] symbolName, Segments.Id segment)
{
hasSymbols_ = true;
// create data
auto dtb = DtBuilder(0);
dtb.nbytes(cast(uint) (str.length + 1), str.toStringz());
// find segment
auto seg = Segments[segment];
// create symbol
auto s = getStatic(symbolName, type_allocn(TYarray, tstypes[TYchar]));
s.Sdt = dtb.finish();
s.Sseg = seg;
return s;
}
Symbol* getMethVarName(const(char)[] name)
{
return cache(name, methVarNameTable, {
__gshared size_t classNameCount = 0;
char[42] buffer;
const symbolName = format(buffer, "L_OBJC_METH_VAR_NAME_%lu", classNameCount++);
return getCString(name, symbolName, Segments.Id.methname);
});
}
Symbol* getMethVarName(Identifier ident)
{
return getMethVarName(ident.toString());
}
Symbol* getMsgSend(Type returnType, bool hasHiddenArgument)
{
if (hasHiddenArgument)
return setMsgSendSymbol!("_objc_msgSend_stret")(TYhfunc);
// not sure if DMD can handle this
else if (returnType.ty == Tcomplex80)
return setMsgSendSymbol!("_objc_msgSend_fp2ret");
else if (returnType.ty == Tfloat80)
return setMsgSendSymbol!("_objc_msgSend_fpret");
else
return setMsgSendSymbol!("_objc_msgSend");
assert(0);
}
Symbol* getMsgSendSuper(bool hasHiddenArgument)
{
if (hasHiddenArgument)
return setMsgSendSymbol!("_objc_msgSendSuper_stret")(TYhfunc);
else
return setMsgSendSymbol!("_objc_msgSendSuper")(TYnfunc);
}
Symbol* getImageInfo()
{
if (imageInfo)
return imageInfo;
auto dtb = DtBuilder(0);
dtb.dword(0); // version
dtb.dword(64); // flags
imageInfo = symbol_name("L_OBJC_IMAGE_INFO", SCstatic, type_allocn(TYarray, tstypes[TYchar]));
imageInfo.Sdt = dtb.finish();
imageInfo.Sseg = Segments[Segments.Id.imageinfo];
outdata(imageInfo);
return imageInfo;
}
Symbol* getModuleInfo(/*const*/ ref ClassDeclarations classes,
/*const*/ ref ClassDeclarations categories)
{
assert(!moduleInfo); // only allow once per object file
auto dtb = DtBuilder(0);
foreach (c; classes)
dtb.xoff(getClassName(c), 0);
foreach (c; categories)
dtb.xoff(getClassName(c), 0);
Symbol* symbol = symbol_name("L_OBJC_LABEL_CLASS_$", SCstatic, type_allocn(TYarray, tstypes[TYchar]));
symbol.Sdt = dtb.finish();
symbol.Sseg = Segments[Segments.Id.classlist];
outdata(symbol);
getImageInfo(); // make sure we also generate image info
return moduleInfo;
}
/**
* Returns: the `_OBJC_METACLASS_$_`/`_OBJC_CLASS_$_` symbol for the given
* class declaration.
*/
Symbol* getClassName(ObjcClassDeclaration objcClass)
{
hasSymbols_ = true;
const prefix = objcClass.isMeta ? "_OBJC_METACLASS_$_" : "_OBJC_CLASS_$_";
auto name = prefix ~ objcClass.classDeclaration.objc.identifier.toString();
return cache(name, classNameTable, () => getGlobal(name));
}
/// ditto
Symbol* getClassName(ClassDeclaration classDeclaration, bool isMeta = false)
in
{
assert(classDeclaration !is null);
}
do
{
return getClassName(ObjcClassDeclaration(classDeclaration, isMeta));
}
/*
* Returns: the `L_OBJC_CLASSLIST_REFERENCES_$_` symbol for the given class
* declaration.
*/
Symbol* getClassReference(ClassDeclaration classDeclaration)
{
hasSymbols_ = true;
auto name = classDeclaration.objc.identifier.toString();
return cache(name, classReferenceTable, {
auto dtb = DtBuilder(0);
auto className = getClassName(classDeclaration);
dtb.xoff(className, 0, TYnptr);
auto segment = Segments[Segments.Id.classrefs];
__gshared size_t classReferenceCount = 0;
char[42] nameString;
auto result = format(nameString, "L_OBJC_CLASSLIST_REFERENCES_$_%lu", classReferenceCount++);
auto symbol = getStatic(result);
symbol.Sdt = dtb.finish();
symbol.Sseg = segment;
outdata(symbol);
return symbol;
});
}
Symbol* getMethVarRef(const(char)[] name)
{
return cache(name, methVarRefTable, {
// create data
auto dtb = DtBuilder(0);
auto selector = getMethVarName(name);
dtb.xoff(selector, 0, TYnptr);
// find segment
auto seg = Segments[Segments.Id.selrefs];
// create symbol
__gshared size_t selectorCount = 0;
char[42] nameString;
sprintf(nameString.ptr, "L_OBJC_SELECTOR_REFERENCES_%llu", cast(ulong) selectorCount);
auto symbol = symbol_name(nameString.ptr, SCstatic, type_fake(TYnptr));
symbol.Sdt = dtb.finish();
symbol.Sseg = seg;
outdata(symbol);
++selectorCount;
return symbol;
});
}
Symbol* getMethVarRef(const Identifier ident)
{
return getMethVarRef(ident.toString());
}
/**
* Returns the Objective-C type encoding for the given type.
*
* The available type encodings are documented by Apple, available at
* $(LINK2 https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html#//apple_ref/doc/uid/TP40008048-CH100, Type Encoding).
* The type encodings can also be obtained by running an Objective-C
* compiler and using the `@encode()` compiler directive.
*
* Params:
* type = the type to return the type encoding for
*
* Returns: a string containing the type encoding
*/
string getTypeEncoding(Type type)
in
{
assert(type !is null);
}
do
{
enum assertMessage = "imaginary types are not supported by Objective-C";
with (ENUMTY) switch (type.ty)
{
case Tvoid: return "v";
case Tbool: return "B";
case Tint8: return "c";
case Tuns8: return "C";
case Tchar: return "C";
case Tint16: return "s";
case Tuns16: return "S";
case Twchar: return "S";
case Tint32: return "i";
case Tuns32: return "I";
case Tdchar: return "I";
case Tint64: return "q";
case Tuns64: return "Q";
case Tfloat32: return "f";
case Tcomplex32: return "jf";
case Tfloat64: return "d";
case Tcomplex64: return "jd";
case Tfloat80: return "D";
case Tcomplex80: return "jD";
case Timaginary32: assert(false, assertMessage);
case Timaginary64: assert(false, assertMessage);
case Timaginary80: assert(false, assertMessage);
default: return "?"; // unknown
// TODO: add "*" char*, "#" Class, "@" id, ":" SEL
// TODO: add "^"<type> indirection and "^^" double indirection
}
}
/**
* Returns: the `L_OBJC_METH_VAR_TYPE_` symbol containing the given
* type encoding.
*/
Symbol* getMethVarType(const(char)[] typeEncoding)
{
return cache(typeEncoding, methVarTypeTable, {
__gshared size_t count = 0;
char[42] nameString;
const symbolName = format(nameString, "L_OBJC_METH_VAR_TYPE_%lu", count++);
auto symbol = getCString(typeEncoding, symbolName, Segments.Id.methtype);
outdata(symbol);
return symbol;
});
}
/// ditto
Symbol* getMethVarType(Type[] types ...)
{
string typeCode;
typeCode.reserve(types.length);
foreach (type; types)
typeCode ~= getTypeEncoding(type);
return getMethVarType(typeCode);
}
/// ditto
Symbol* getMethVarType(FuncDeclaration func)
{
Type[] types = [func.type.nextOf]; // return type first
if (func.parameters)
{
types.reserve(func.parameters.length);
foreach (e; *func.parameters)
types ~= e.type;
}
return getMethVarType(types);
}
/// Returns: the externally defined `__objc_empty_cache` symbol
Symbol* getEmptyCache()
{
return emptyCache = emptyCache ? emptyCache : getGlobal("__objc_empty_cache");
}
/// Returns: the externally defined `__objc_empty_vtable` symbol
Symbol* getEmptyVTable()
{
return emptyVTable = emptyVTable ? emptyVTable : getGlobal("__objc_empty_vtable");
}
/// Returns: the `L_OBJC_CLASS_NAME_` symbol for a class with the given name
Symbol* getClassNameRo(const(char)[] name)
{
return cache(name, classNameTable, {
__gshared size_t count = 0;
char[42] nameString;
const symbolName = format(nameString, "L_OBJC_CLASS_NAME_%lu", count++);
return getCString(name, symbolName, Segments.Id.classname);
});
}
/// ditto
Symbol* getClassNameRo(const Identifier ident)
{
return getClassNameRo(ident.toString());
}
Symbol* getIVarOffset(ClassDeclaration cd, VarDeclaration var, bool outputSymbol)
{
hasSymbols_ = true;
const className = cd.objc.identifier.toString;
const varName = var.ident.toString;
const name = "_OBJC_IVAR_$_" ~ className ~ '.' ~ varName;
auto stringValue = ivarOffsetTable.update(name);
auto symbol = stringValue.value;
if (!symbol)
{
symbol = getGlobal(name);
symbol.Sfl |= FLextern;
stringValue.value = symbol;
}
if (!outputSymbol)
return symbol;
auto dtb = DtBuilder(0);
dtb.size(var.offset);
symbol.Sdt = dtb.finish();
symbol.Sseg = Segments[Segments.Id.ivar];
symbol.Sfl &= ~FLextern;
outdata(symbol);
return symbol;
}
Symbol* getProtocolSymbol(InterfaceDeclaration id)
in
{
assert(!id.objc.isMeta);
}
do
{
const name = id.objc.identifier.toString();
return cache(name, protocolTable, () => ProtocolDeclaration(id).toObjFile());
}
private Symbol* setMsgSendSymbol(string name)(tym_t ty = TYnfunc)
{
alias This = typeof(this);
enum fieldName = name[1 .. $];
if (!__traits(getMember, This, fieldName))
__traits(getMember, This, fieldName) = getGlobal(name, type_fake(ty));
return __traits(getMember, This, fieldName);
}
/**
* Caches the symbol returned by `block` using the given name.
*
* If the symbol is already in the cache, the symbol will be returned
* immediately and `block` will not be called.
*
* Params:
* name = the name to cache the symbol under
* symbolCache = the cache storage to use for this symbol
* block = invoked when the symbol is not in the cache. The return value
* will be put into the cache
*
* Returns: the cached symbol
*/
private Symbol* cache(const(char)[] name, SymbolCache symbolCache,
scope Symbol* delegate() block)
{
hasSymbols_ = true;
auto stringValue = symbolCache.update(name);
if (stringValue.value)
return stringValue.value;
return stringValue.value = block();
}
}
private:
/**
* Functionality for outputting symbols for a specific Objective-C class
* declaration.
*/
struct ObjcClassDeclaration
{
/// Indicates what kind of class this is.
private enum Flags
{
/// Regular class.
regular = 0x00000,
/// Meta class.
meta = 0x00001,
/// Root class. A class without any base class.
root = 0x00002
}
/// The class declaration
ClassDeclaration classDeclaration;
/// `true` if this class is a metaclass.
bool isMeta;
this(ClassDeclaration classDeclaration, bool isMeta)
in
{
assert(classDeclaration !is null);
}
do
{
this.classDeclaration = classDeclaration;
this.isMeta = isMeta;
}
/**
* Outputs the class declaration to the object file.
*
* Returns: the exported symbol, that is, `_OBJC_METACLASS_$_` or
* `_OBJC_CLASS_$_`
*/
Symbol* toObjFile()
{
if (classDeclaration.objc.isExtern)
return null; // only a declaration for an externally-defined class
auto dtb = DtBuilder(0);
toDt(dtb);