-
Notifications
You must be signed in to change notification settings - Fork 30
/
ObxCilGen.cpp
5201 lines (4870 loc) · 196 KB
/
ObxCilGen.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
/*
* Copyright 2021 Rochus Keller <mailto:[email protected]>
*
* This file is part of the Oberon+ parser/compiler library.
*
* The following is the license that applies to this copy of the
* library. For a license to use the library under conditions
* other than those described here, please email to [email protected].
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License (GPL) versions 2.0 or 3.0 as published by the Free Software
* Foundation and appearing in the file LICENSE.GPL included in
* the packaging of this file. Please review the following information
* to ensure GNU General Public Licensing requirements will be met:
* http://www.fsf.org/licensing/licenses/info/GPLv2.html and
* http://www.gnu.org/copyleft/gpl.html.
*/
#include "ObxCilGen.h"
#include "ObxAst.h"
#include "ObErrors.h"
#include "ObxProject.h"
#include "ObxIlEmitter.h"
#include "ObxPelibGen.h"
#include "ObxValidator.h"
#include <MonoTools/MonoMdbGen.h>
#include <QtDebug>
#include <QFile>
#include <QDir>
#include <QCryptographicHash>
#include <limits>
using namespace Obx;
using namespace Ob;
#ifndef OBX_AST_DECLARE_SET_METATYPE_IN_HEADER
Q_DECLARE_METATYPE( Obx::Literal::SET )
#endif
#define _MY_GENERICS_ // using my own generics implementation instead of the dotnet generics;
// there is an architectural value type initialization issue with dotnet generics!
// NOTE that disabling this define most likely leads to errors, since no longer maintained
// #define _CLI_USE_PTR_TO_MEMBER_ // access struct members by native int + offset instead of memberref (no advantage so far)
// #define _CLI_DYN_STRUCT_VARIABLES_ // unsafe structs in module variables are dynamically allocated on heap
// TODO: this doesnt seem to resolve the issue; still random crashes in SDL test;
// the issue vanishes if either a) we use Mono 5, or b) the SDL function using the
// address of the struct is called in a method (not on top level of the .cctor), regardless
// whether the struct is a module or local variable, or c) we compile with ILASM instead
// of Pelib ; this might be the urgent reason to switch to Mono5 also on Linux and
// just accept the 30% speed-down; but it's likely a pelib issue
#define _CLI_VARARG_SUBST_PROCS_ // generated local substitution methods with the required signature instead of relying on
// CLI pinvoke vararg implementation (which apparently doesn't work on all platforms/architectures).
// #define _CLI_PASS_RAW_FUNCTION_POINTER // TODO
// NOTE: even though CoreCLR replaced mscorlib by System.Private.CoreLib the generated code still runs with "dotnet Main.exe",
// but the directory with the OBX assemblies requires a Main.runtimeconfig.json file as generated below
// "dotnet.exe run" apparently creates an non-managed exe which loads coreclr.dll and the app assembly dll; mono5 (in contrast to 3)
// is able to disasm and even run the app assembly dll created by dotnet.exe CoreCLR 3.1.
struct ObxCilGenCollector : public AstVisitor
{
QList<Procedure*> allProcs;
QList<Record*> allRecords;
QSet<Module*> allImports;
QList<ProcType*> allProcTypes;
Module* thisMod;
void collect(Type* t)
{
switch( t->getTag() )
{
case Thing::T_Array:
collect(cast<Array*>(t)->d_type.data());
break;
case Thing::T_Record:
{
Record* r = cast<Record*>(t);
allRecords.append( r );
foreach( const Ref<Field>& f, r->d_fields )
{
collect(f->d_type.data());
}
if( r->d_base )
collect(r->d_base.data());
}
break;
case Thing::T_Pointer:
collect(cast<Pointer*>(t)->d_to.data());
break;
case Thing::T_ProcType:
{
ProcType* pt = cast<ProcType*>(t);
if( !( pt->d_formals.isEmpty() && pt->d_return.isNull() ) ) // proc types with no params are mapped to OBX.Command
allProcTypes.append(pt);
foreach( const Ref<Parameter>& p, pt->d_formals )
collect(p->d_type.data());
if( pt->d_return )
collect(pt->d_return.data());
}
break;
case Thing::T_QualiType:
if( Record* r = t->toRecord() )
{
Named* n = r->findDecl();
if( n ) // actually n cannot be 0
allImports.insert(n->getModule());
}
#if 0
// no, we only create delegates for proc types declared here
else
{
t = t->derefed();
if( t && t->getTag() == Thing::T_ProcType )
collect(t); // even if the proc type was declared in another module, we create a local delegate here
}
#endif
break;
}
}
void collect( Named* n )
{
switch( n->getTag() )
{
case Thing::T_Procedure:
{
Procedure* p = cast<Procedure*>(n);
if( p->d_receiver.isNull() )
allProcs.append(cast<Procedure*>(n));
p->accept(this);
}
break;
case Thing::T_NamedType:
collect(n->d_type.data());
break;
case Thing::T_Const:
{
Const* c = cast<Const*>(n);
if( c->d_vtype == Const::ProcLit )
collect(n->d_type.data());
}
break;
case Thing::T_Variable:
case Thing::T_Parameter:
case Thing::T_LocalVar:
collect(n->d_type.data());
break;
}
}
void visit( Module* me )
{
thisMod = me;
foreach( const Ref<Named>& n, me->d_order )
collect(n.data());
}
void visit( Procedure* me)
{
foreach( const Ref<Named>& n, me->d_order )
collect(n.data());
}
};
struct CilGenTempPool
{
enum { MAX_TEMP = 250 };
std::bitset<MAX_TEMP> d_slots;
QList<QByteArray> d_types;
quint16 d_start;
CilGenTempPool():d_start(0){}
void reset(quint16 start)
{
d_slots.reset();
d_start = start;
d_types.clear();
}
int buy(const QByteArray& type)
{
int i = 0;
while( i < d_types.size() && i < MAX_TEMP )
{
if( d_types[i] == type && !d_slots.test(i) )
{
d_slots.set(i);
return i + d_start;
}
i++;
}
if( i < MAX_TEMP )
{
d_types.append(type);
Q_ASSERT( !d_slots.test(i) );
d_slots.set(i);
return i + d_start;
}
Q_ASSERT( false );
return -1;
}
void sell( int i )
{
Q_ASSERT( i >= d_start );
d_slots.set(i-d_start,false);
}
void sellAll()
{
d_slots.reset();
}
};
struct ObxCilGenImp : public AstVisitor
{
Errors* err;
Module* thisMod;
IlEmitter* emitter;
QString buffer;
quint32 anonymousDeclNr; // starts with one, zero is an invalid slot
qint16 level;
bool ownsErr;
bool forceAssemblyPrefix;
bool forceFormalIndex;
bool debug;
bool arrayAsElementType;
bool structAsPointer;
bool checkPtrSize;
RowCol last;
CilGenTempPool temps;
QHash<QByteArray, QPair<Array*,int> > copiers; // type string -> array, max dim count
QHash<QByteArray,ProcType*> delegates; // signature hash -> signature
#ifdef _CLI_VARARG_SUBST_PROCS_
QHash<Module*,QHash<Procedure*,QHash<QByteArray, QList<Type*> > > > substitutes; // replace vararg by overloads
#endif
QList<QPair<int,int> > pinnedTemps; // pinned temp var -> write back var or -1
QList<int> exitJump;
Procedure* scope;
int suppressLine;
ObxCilGenImp():ownsErr(false),err(0),thisMod(0),anonymousDeclNr(1),level(0),
scope(0),forceAssemblyPrefix(false),forceFormalIndex(false),
suppressLine(0),debug(false),checkPtrSize(false),
arrayAsElementType(false),structAsPointer(false)
{
}
static QByteArray inline escape( const QByteArray& name )
{
return "'" + name + "'";
}
QByteArray dottedName( Named* n )
{
// concatenate names up to but not including module
QByteArray name = n->d_name;
Named* scope = n->d_scope;
if( scope )
{
const int tag = scope->getTag();
if( tag != Thing::T_Module )
{
if( tag == Thing::T_Procedure )
{
Procedure* proc = cast<Procedure*>(scope);
if( proc->d_receiverRec )
{
// if the scope is a bound proc follow its receiver, but first use the proc name.
// this is necessary because procs bound to different recs can have the same name and
// even have the same name as ordinary procs, so there is a risk of duplicate names when
// just following the normal scope
name = scope->d_name + "#" + name;
scope = proc->d_receiverRec->findDecl();
Q_ASSERT( scope );
}
}
return dottedName(scope) + "#" + name;
}
}
return name;
}
QByteArray nestedPath(Named* n)
{
return escape(dottedName(n));
}
QByteArray formatMetaActuals(Module* m)
{
#ifndef _MY_GENERICS_
if( m == thisMod && !m->d_metaParams.isEmpty() )
{
Q_ASSERT( m->d_metaActuals.isEmpty() );
QByteArray res = "<";
for( int i = 0; i < m->d_metaParams.size(); i++ )
{
if( i != 0 )
res += ",";
Q_ASSERT( m->d_metaParams[i]->d_slotValid );
res += "!" + QByteArray::number(m->d_metaParams[i]->d_slot);
}
res += ">";
return res;
}else if( !m->d_metaActuals.isEmpty() )
{
QByteArray res = "<";
for( int i = 0; i < m->d_metaActuals.size(); i++ )
{
if( i != 0 )
res += ",";
res += formatType(m->d_metaActuals[i].data());
}
res += ">";
return res;
}
#endif
return QByteArray();
}
QByteArray formatMetaActuals(Type* t)
{
// t==0 -> module
Module* m = 0;
t = derefed(t);
if( t == 0 )
m = thisMod;
else
m = t->declaredIn();
return formatMetaActuals(m);
}
inline QByteArray getName( Named* n )
{
Q_ASSERT(n);
#ifdef _MY_GENERICS_
return n->getName();
#else
if( n->getTag() == Thing::T_Module )
return cast<Module*>(n)->d_fullName.join('.');
else
return n->d_name;
#endif
}
QByteArray moduleRef( Named* modName )
{
if( modName == 0 )
return "???";
Q_ASSERT( modName->getTag() == Thing::T_Module );
const QByteArray mod = escape(cast<Module*>(modName)->d_name);
if( !forceAssemblyPrefix && modName == thisMod )
return mod;
else
{
const QByteArray ass = escape(getName(modName));
return "[" + ass + "]" + mod;
}
}
QByteArray classRef( Named* className )
{
Q_ASSERT( className && className->getTag() == Thing::T_NamedType );
Module* m = className->getModule();
if( m == 0 && className->d_type && className->d_type->derefed()->getBaseType() == Type::ANYREC )
return "[OBX.Runtime]OBX.Anyrec";
else
return moduleRef(m) + "/" + nestedPath(className); // dotted because also records nested in procs are lifted to module level
}
QByteArray classRef( Record* r )
{
Named* n = r->findDecl();
if( n && n->getTag() == Thing::T_NamedType )
return classRef(n);
else
{
#ifdef _DEBUG
Q_ASSERT( r->d_slotValid );
#endif
if( n == 0 )
n = r->findDecl(true);
Module* m = n ? n->getModule() : 0;
if( m == 0 )
m = thisMod;
return moduleRef(m) + "/'#" + QByteArray::number(r->d_slot) + "'";
}
}
QByteArray memberRef( Named* member, const QList<Type*>& varargs = QList<Type*>())
{
QByteArray res;
Record* record = 0;
ProcType* pt = 0;
switch( member->getTag() )
{
case Thing::T_Field:
{
Field* f = cast<Field*>(member);
record = f->d_owner;
}
break;
case Thing::T_Variable:
break;
case Thing::T_Procedure:
{
Procedure* p = cast<Procedure*>(member);
if( p->d_receiverRec )
record = p->d_receiverRec;
pt = p->getProcType();
#ifdef _CLI_VARARG_SUBST_PROCS_
if( !varargs.isEmpty() && pt->d_varargs )
{
// substitute vararg function with local non-vararg function
const QByteArray sig = formatFormals(pt,false,varargs,false);
substitutes[member->getModule()][p][sig] = varargs;
return formatType(pt->d_return.data(),pt->d_unsafe) + " " +
moduleRef(thisMod) + "::" + escape( p->getModule()->getName() + "#" + p->d_name ) + sig;
}
#endif
}
break;
case Thing::T_Const:
{
Const* c = cast<Const*>(member);
Procedure* p = c->findProc();
Q_ASSERT(false);
return memberRef(p,varargs);
}
break;
default:
Q_ASSERT(false);
}
const QByteArray ma = formatMetaActuals(record);
forceFormalIndex = !ma.isEmpty();
if( pt )
{
if( !varargs.isEmpty() )
res = "vararg ";
res += formatType(pt->d_return.data(),pt->d_unsafe);
}else
res = formatType(member->d_type.data(),member->d_unsafe);
res += " ";
if( !ma.isEmpty() )
res += "class "; // only if not my generics
if( record == 0 ) // if module level
res += moduleRef(member->getModule());
else
res += classRef(record);
res += ma;
res += "::";
if( record == 0 ) // if module level
res += nestedPath(member); // because of nested procedures which are lifted to module level
else
res += escape(member->d_name);
if( pt )
res += formatFormals(pt,varargs.isEmpty(),varargs);
forceFormalIndex = false;
return res;
}
QByteArray inline delegateName( const QByteArray& sig )
{
QCryptographicHash hash(QCryptographicHash::Md5);
hash.addData(sig);
return hash.result().toHex(); // issues because of '/': toBase64(QByteArray::OmitTrailingEquals);
}
QByteArray delegateRef( ProcType* pt )
{
if( pt == 0 )
return "?";
if( pt->d_formals.isEmpty() && pt->d_return.isNull() )
return "[OBX.Runtime]OBX.Command";
forceAssemblyPrefix = true;
#ifndef _MY_GENERICS_
const bool old = forceFormalIndex;
forceFormalIndex = true;
const QByteArray sig = procTypeSignature(pt);
forceFormalIndex = old;
#else
const QByteArray sig = procTypeSignature(pt);
#endif
const QByteArray name = "Ð" + delegateName(sig); // using Ð (U+00D0) instead of @ for C# compatibility
if( pt->declaredIn() == thisMod )
delegates.insert(name,pt);
Module* m = pt->declaredIn();
if( m == 0 )
m = thisMod;
const QByteArray res = moduleRef(m) + "/'" + name + "'" + formatMetaActuals(pt);
forceAssemblyPrefix = false;
return res;
}
QByteArray formatArrayCopierRef(Array* a)
{
Q_ASSERT(a);
const QByteArray sig = formatType(a);
QPair<Array*,int>& d = copiers[sig];
if( d.first == 0 )
d.first = a;
QByteArray res = "void " + moduleRef(thisMod) + "::'#copy'(";
res += sig;
res += ", ";
res += sig;
res += ")";
return res;
}
void emitArrayCopier( Array* a, const RowCol& loc )
{
// this is no longer for array of char
Q_ASSERT(a);
Type* et = derefed(a->d_type.data());
Q_ASSERT(et);
emitter->beginMethod("'#copy'", true, IlEmitter::Static );
const QByteArray type = formatType(a);
emitter->addArgument(type,"lhs");
emitter->addArgument(type,"rhs");
beginBody();
line(loc); // the same line for the whole method
const int len = temps.buy("int32");
Q_ASSERT( len >= 0 );
emitter->ldarg_(0);
emitter->ldlen_();
emitter->ldarg_(1);
emitter->ldlen_();
// stack: len lhs, len rhs
const int lhsIsLen = emitter->newLabel();
const int storeLen = emitter->newLabel();
emitter->ble_(lhsIsLen);
emitter->ldarg_(1);
emitter->ldlen_();
emitter->br_(storeLen);
emitter->label_(lhsIsLen);
emitter->ldarg_(0);
emitter->ldlen_();
emitter->label_(storeLen);
emitter->stloc_(len); // len = qMin(lenLhs,lenRhs)
const int idx = temps.buy("int32");
Q_ASSERT( idx >= 0 );
emitter->ldc_i4(0);
emitter->stloc_(idx);
const int checkLenLbl = emitter->newLabel();
const int addLbl = emitter->newLabel();
emitter->label_(checkLenLbl);
emitter->ldloc_(idx);
emitter->ldloc_(len);
const int afterLoopLbl = emitter->newLabel();
emitter->bge_(afterLoopLbl);
if( et->getTag() == Thing::T_Array )
{
emitter->ldarg_(0);
emitter->ldloc_(idx);
// stack: array, int
emitter->ldelem_(formatType(et));
emitter->ldarg_(1);
emitter->ldloc_(idx);
// stack: array, array, int
emitter->ldelem_(formatType(et));
// stack: lhs array, rhs array
emitCopyArray(et,et,loc);
// emitter->call_(formatArrayCopierRef(cast<Array*>(et)),2);
emitter->br_(addLbl);
}else
{
switch( et->getTag() )
{
case Thing::T_Record:
{
emitter->ldarg_(0);
emitter->ldloc_(idx);
// stack: array, int
emitter->ldelem_(formatType(et));
emitter->ldarg_(1);
emitter->ldloc_(idx);
// stack: record, array, int
emitter->ldelem_(formatType(et));
// stack: lhs record, rhs record
Record* r2 = cast<Record*>(et);
QByteArray type = formatType(r2);
if( r2->d_byValue )
type += "&";
emitter->callvirt_("void " + classRef(r2) + formatMetaActuals(r2) +
"::'#copy'(" + type + ")", 1 );
}
break;
case Thing::T_Array:
Q_ASSERT(false); // et always points to the base type of the (multidim) array, which cannot be an array
break;
case Thing::T_BaseType:
case Thing::T_Enumeration:
case Thing::T_Pointer:
case Thing::T_ProcType:
{
emitter->ldarg_(0);
emitter->ldloc_(idx);
// stack: lhs array, int
emitter->ldarg_(1);
emitter->ldloc_(idx);
// stack: lhs array, int, rhs array, int
emitter->ldelem_(formatType(et));
// stack: lhs array, int, value
emitter->stelem_(formatType(et));
}
break;
}
}
emitter->label_(addLbl);
emitter->ldloc_(idx);
emitter->ldc_i4(1);
emitter->add_();
emitter->stloc_(idx);
emitter->br_(checkLenLbl);
emitter->label_(afterLoopLbl);
temps.sell(idx);
temps.sell(len);
emitter->ret_();
emitLocalVars();
emitter->endMethod();
}
//#define _USE_VALUE_RECORDS_
// no value records currently because the initialization works completely different; needs extra work
void allocRecordDecl(Record* r)
{
if( r->d_slotValid )
return; // can happen e.g. with VAR foo, bar: RECORD ch: CHAR; i: INTEGER END;
Named* n = r->findDecl();
if( n == 0 || n->getTag() != Thing::T_NamedType )
{
r->d_slot = anonymousDeclNr++;
r->d_slotValid = true;
}
}
void emitRecordDecl(Record* r)
{
if( r->d_slotAllocated )
return;
r->d_slotAllocated = true;
Named* n = r->findDecl();
QByteArray className, superClassName;
bool isPublic = false;
if( n == 0 || n->getTag() != Thing::T_NamedType )
{
Q_ASSERT(r->d_slotValid);
className = "'#" + QByteArray::number(r->d_slot) + "'";
}else
{
isPublic = n->d_scope == thisMod && n->d_visibility == Named::ReadWrite;
#ifdef _USE_VALUE_RECORDS_
r->d_byValue = !isPublic && r->d_baseRec == 0 && r->d_subRecs.isEmpty();
#else
r->d_byValue = false;
#endif
className = nestedPath(n); // because of records declared in procedures are lifted to module level
if( !r->d_base.isNull() )
superClassName = formatType(r->d_base.data());
else if(!r->d_unsafe) // unsafe rec has no basetype
superClassName = "[OBX.Runtime]OBX.Anyrec";
}
emitter->beginClass(className, isPublic, r->d_unsafe ? IlEmitter::Value : IlEmitter::Object,
superClassName, r->d_unsafe ? r->getByteSize() : -1 );
foreach( const Ref<Field>& f, r->d_fields )
f->accept(this);
foreach( const Ref<Procedure>& p, r->d_methods )
p->accept(this);
// NOTE: I verified that in case of unsafe structs there is really no marshalling; the struct address in
// the dll is the same as in the Mono engine.
QList<Field*> fields = r->getOrderedFields();
// default constructor
if( !r->d_unsafe ) // unsafe records use initobj; no constructor is called for unsafe records
{
emitter->beginMethod(".ctor",true);
beginBody();
line(r->d_loc).ldarg_(0);
QByteArray what;
if( r->d_baseRec )
{
Q_ASSERT( !r->d_unsafe );
what = "void class " + classRef(r->d_baseRec) + formatMetaActuals(r->d_baseRec) + "::.ctor()";
}else if( r->d_byValue )
what = "void [mscorlib]System.ValueType::.ctor()";
else
what = "void [OBX.Runtime]OBX.Anyrec::.ctor()";
line(r->d_loc).call_(what,1,false,true);
// initialize fields of current record
// NOTE safe records cannot have fields of unsafe structured types by value; thus no destructor required
for( int i = 0; i < fields.size(); i++ )
{
// oberon system expects all vars to be initialized
line(fields[i]->d_loc).ldarg_(0);
if( emitInitializer(fields[i]->d_type.data(), false, fields[i]->d_loc ) )
emitStackToVar( fields[i], fields[i]->d_loc );
else
line(fields[i]->d_loc).pop_();
}
line(r->d_loc).ret_();
emitLocalVars();
emitter->endMethod();
// end default constructor
}
// copy
if( !r->d_unsafe )
{
emitter->beginMethod("'#copy'",true, IlEmitter::Virtual);
QByteArray type = formatType(r);
if( r->d_byValue )
type += "&";
emitter->addArgument(type, "rhs");
beginBody();
if( r->d_baseRec )
{
line(r->d_loc).ldarg_(0);
line(r->d_loc).ldarg_(1);
QByteArray what = "void class " + classRef(r->d_baseRec) + formatMetaActuals(r->d_baseRec) + "::'#copy'(";
type = formatType(r->d_baseRec);
if( r->d_byValue )
type += "&";
what += type + ")";
line(r->d_loc).call_(what,1,false,true);
}
for( int i = 0; i < fields.size(); i++ )
{
Type* ft = derefed(fields[i]->d_type.data());
switch( ft->getTag() )
{
case Thing::T_Record:
{
line(r->d_loc).ldarg_(0);
line(r->d_loc).ldfld_(memberRef(fields[i]));
line(r->d_loc).ldarg_(1);
line(r->d_loc).ldfld_(memberRef(fields[i]));
Record* r2 = cast<Record*>(ft);
QByteArray what = "void " + classRef(r2) + formatMetaActuals(r2) + "::'#copy'(";
type = formatType(r2);
if( r2->d_byValue )
type += "&";
what += type + ")";
line(r->d_loc).callvirt_(what,1);
}
break;
case Thing::T_Array:
{
line(r->d_loc).ldarg_(0);
line(r->d_loc).ldfld_(memberRef(fields[i]));
line(r->d_loc).ldarg_(1);
line(r->d_loc).ldfld_(memberRef(fields[i]));
// stack: lhs array, rhs array
emitCopyArray(ft,ft,r->d_loc);
//line(r->d_loc).call_(formatArrayCopierRef(cast<Array*>(ft)),2);
}
break;
case Thing::T_BaseType:
case Thing::T_Enumeration:
case Thing::T_Pointer:
case Thing::T_ProcType:
line(r->d_loc).ldarg_(0);
line(r->d_loc).ldarg_(1);
line(r->d_loc).ldfld_(memberRef(fields[i]));
line(r->d_loc).stfld_(memberRef(fields[i]));
break;
}
}
line(r->d_loc).ret_();
emitLocalVars();
emitter->endMethod();
// end copy
}
emitter->endClass();
}
void emitDelegDecl(ProcType* sig, const QByteArray& name)
{
// NOTE: if the name deviates from the one used for referencing the delegate mono3 crashes with this message:
// TypeRef ResolutionScope not yet handled (3) for .48b15Qezth5ae11+xOqLVw in image GenericTest6.dll
// * Assertion at class.c:5695, condition `!mono_loader_get_last_error ()' not met
emitter->beginClass(escape(name),true,IlEmitter::Delegate,"[mscorlib]System.MulticastDelegate");
// formatMetaParams(thisMod)
emitter->beginMethod(".ctor",true,IlEmitter::Instance,true);
emitter->addArgument("object","MethodsClass");
emitter->addArgument("native int", "MethodPtr");
emitter->endMethod();
emitter->beginMethod("Invoke",true,IlEmitter::Instance,true);
if( !sig->d_return.isNull() || sig->d_unsafe )
{
QByteArray ret = formatType(sig->d_return.data(),sig->d_unsafe);
if( sig->d_unsafe )
ret += " modopt([mscorlib]System.Runtime.CompilerServices.CallConvCdecl)";
emitter->setReturnType(ret);
}
for( int i = 0; i < sig->d_formals.size(); i++ )
{
QByteArray type = formatType(sig->d_formals[i]->d_type.data(),sig->d_unsafe);
if( requiresRefOp(sig->d_formals[i].data()) )
type += "&";
emitter->addArgument(type,escape(sig->d_formals[i]->d_name));
}
emitter->endMethod();
emitter->endClass();
}
QByteArray formatMetaParams(Module* m)
{
#ifdef _MY_GENERICS_
return QByteArray();
#else
if( m->d_metaParams.isEmpty() )
return QByteArray();
QByteArray res = "<";
for( int i = 0; i < m->d_metaParams.size(); i++ )
{
if( i != 0 )
res += ", ";
res += escape(m->d_metaParams[i]->d_name);
}
res += ">";
return res;
#endif
}
void visit( Module* me )
{
ObxCilGenCollector co;
me->accept(&co);
foreach( Import* imp, me->d_imports )
{
if(imp->d_mod->d_synthetic || imp->d_mod->d_isDef ) // TODO: def
continue; // ignore SYSTEM
co.allImports.insert(imp->d_mod.data());
if( !imp->d_mod.isNull() && !imp->d_mod->d_metaActuals.isEmpty() )
{
for( int i = 0; i < imp->d_mod->d_metaActuals.size(); i++ )
{
Q_ASSERT(i < imp->d_mod->d_metaParams.size());
if( imp->d_mod->d_metaParams[i]->getTag() == Thing::T_NamedType )
{
Type* at = imp->d_mod->d_metaActuals[i].d_type.data();
//Q_ASSERT( !at->d_slotValid );
at->d_slot = i;
at->d_slotValid = true;
at->d_metaActual = true;
}
}
}
}
QByteArrayList imports;
imports.append( escape("mscorlib") );
imports.append( escape("OBX.Runtime") );
foreach( Module* m, co.allImports )
{
if( m && m != me )
imports.append( escape(getName(m)) );
}
// NOTE: module name is always set in '' and thus doesn't have to be escaped
emitter->beginModule(escape(me->getName()), escape(me->d_name), imports, thisMod->d_file);
for( int i = 0; i < co.allProcTypes.size(); i++ )
delegateRef(co.allProcTypes[i]);
foreach( Record* r, co.allRecords )
allocRecordDecl(r);
foreach( Record* r, co.allRecords )
emitRecordDecl(r);
foreach( const Ref<Named>& n, me->d_order )
{
if( n->getTag() == Thing::T_Variable )
n->accept(this);
}
#ifndef _MY_GENERICS_
if( !me->d_metaParams.isEmpty() && me->d_metaActuals.isEmpty() )
{
foreach( const Ref<GenericName>& n, me->d_metaParams )
{
Q_ASSERT( n->d_slotValid );
out << ws() << ".field assembly static !" << n->d_slot << " '##" << n->d_slot << "'" << endl;
}
}
#endif
foreach( Procedure* p, co.allProcs )
p->accept(this);
if( !me->d_externC )
{
// instead of .cctor we now have an ordinary begïn method which is explicitly called via import
// dependency chain; this was necessary because during .cctor apparently not all relevant parts of
// Mono are ready, e.g. Thread.Join doesn't work an blocks all running threads instead.
// "begïn" (note the ï, U+00EF) is a compatible ident with C# (in contrast to e.g. begin#)
emitter->addField(escape("beginCalled#"),"bool",false,true);
emitter->beginMethod(".cctor", false, IlEmitter::Static );
line(me->d_end).ldc_i4(0);
line(me->d_end).stsfld_("bool " + moduleRef(thisMod)+"::'beginCalled#'");
line(me->d_end).ret_(false);
emitter->endMethod();
emitter->beginMethod(escape("begïn"), false, IlEmitter::Static ); // MODULE BEGIN
beginBody();
line(me->d_end).ldsfld_("bool " + moduleRef(thisMod)+"::'beginCalled#'");
const int callPending = emitter->newLabel();
line(me->d_end).brfalse_(callPending);
line(me->d_end).ret_(callPending);
line(me->d_end).label_(callPending);
line(me->d_end).ldc_i4(1);
line(me->d_end).stsfld_("bool " + moduleRef(thisMod)+"::'beginCalled#'");
foreach( Import* imp, me->d_imports )
{
if(imp->d_mod->d_synthetic )
continue; // ignore SYSTEM
const QByteArray mod = moduleRef(imp->d_mod.data());
line(me->d_end).call_("void " + mod + "::'begïn'()");
}
#ifndef _MY_GENERICS_
if( !me->d_metaParams.isEmpty() && me->d_metaActuals.isEmpty() )
{
foreach( const Ref<GenericName>& n, me->d_metaParams ) // generate default values
{
// NOTE: this doesn't initialize OBX value types; e.g. in GenericTest3 l1.value is initialized to null instead
// of an empty array 20 of char; to get around a default constructor for all possible types, especially
// fixed size arrays, would be needed.
emitOpcode2("ldsflda ", 1, me->d_begin );
Q_ASSERT(n->d_slotValid);
out << "!" << QByteArray::number(n->d_slot) << " class " << moduleRef(me) << formatMetaActuals(me)
<< "::'##" << n->d_slot << "'" << endl;
emitOpcode("initobj !"+escape(n->d_name),-1, me->d_begin);
}
}
#endif
suppressLine++;
foreach( const Ref<Named>& n, me->d_order )
{
if( n->getTag() == Thing::T_Variable )
emitInitializer(n.data());
}
suppressLine--;
emitCheckPtrSize(me->d_begin); // after declarations
foreach( const Ref<Statement>& s, me->d_body )
{
temps.sellAll();
s->accept(this);
}
line(me->d_end).ret_(false);
emitLocalVars();
emitter->endMethod();
}else
{
emitter->beginMethod(escape("begïn"), false, IlEmitter::Static ); // MODULE BEGIN
if( checkPtrSize )
{
beginBody();
emitCheckPtrSize(me->d_begin);
}