forked from rochus-keller/Micron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMicMilInterpreter.cpp
2424 lines (2340 loc) · 86.7 KB
/
MicMilInterpreter.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 2024 Rochus Keller <mailto:me@rochus-keller.ch>
*
* This file is part of the Micron language project.
*
* The following is the license that applies to this copy of the
* file. For a license to use the file under conditions
* other than those described here, please email to me@rochus-keller.ch.
*
* 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 "MicMilInterpreter.h"
#include "MicMilOp.h"
#include "MicToken.h"
#include <QElapsedTimer>
#include <QVector>
#include <QtDebug>
using namespace Mic;
#define _USE_GETTIMEOFDAY
#ifdef _USE_GETTIMEOFDAY
#if defined(_WIN32) && !defined(__GNUC__)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
// Source: https://stackoverflow.com/questions/10905892/equivalent-of-gettimeday-for-windows/26085827
// MSVC defines this in winsock2.h!?
typedef struct timeval {
long tv_sec;
long tv_usec;
} timeval;
int gettimeofday(struct timeval * tp, struct timezone * tzp)
{
// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
// This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)
// until 00:00:00 January 1, 1970
static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime( &system_time );
SystemTimeToFileTime( &system_time, &file_time );
time = ((uint64_t)file_time.dwLowDateTime ) ;
time += ((uint64_t)file_time.dwHighDateTime) << 32;
tp->tv_sec = (long) ((time - EPOCH) / 10000000L);
tp->tv_usec = (long) (system_time.wMilliseconds * 1000);
return 0;
}
#else
#include <sys/time.h>
#endif
#endif
struct ModuleData;
struct ProcData
{
MilProcedure* proc;
ModuleData* module;
ProcData(MilProcedure* p, ModuleData* m):proc(p),module(m) {}
};
// NOTE: replaced original design based on MemSlots(QVector) by MemSlot[] and integrated
// all embedded arrays and structs into the same MemSlot[] so that constructs like
// struct Permute { Benchmark base; int count; } (from Permute.c) can be represented.
struct MemSlot
{
union {
qint64 i;
quint64 u;
double f;
MemSlot* p;
ProcData* pp;
};
enum Type { Invalid, I, U, F,
Record, Array, // pointer to sequence of MemSlot, owned
Pointer, // pointer to MemSlot (sequence, variable, parameter, field, element), not owned
Procedure, // pointer to procedure/module, not owned
Header // the header slot of a record or array; the pointer points to the next slot; u is size
};
#ifdef _DEBUG
Type t;
#else
quint8 t;
#endif
bool hw; // half width for i, u or f
bool embedded;
MemSlot():u(0),t(Invalid),hw(false),embedded(false) {}
MemSlot(quint64 u, bool h = false):u(u),t(U),hw(h),embedded(false) { if(hw) u &= 0xffffffff; }
MemSlot(qint64 i, bool h = false):i(i),t(I),hw(h),embedded(false) { if(hw) i = (qint32)i; }
MemSlot(int i, bool h = true):i(i),t(I),hw(h),embedded(false) {}
MemSlot(double d,bool h):f(d),t(F),hw(h),embedded(false) {}
MemSlot(MemSlot* s):p(s),t(Pointer), hw(false),embedded(false) {}
MemSlot(ProcData* p):pp(p),t(Procedure),hw(false),embedded(false) {}
MemSlot(const MemSlot& rhs):t(Invalid),u(0),embedded(false) { *this = rhs; }
~MemSlot();
void clear();
MemSlot& operator=(const MemSlot& rhs);
void move( MemSlot& rhs );
void copyOf(const MemSlot* rhs, bool record);
void copyOf(const MemSlot* rhs, quint32 off, quint32 len, bool record);
static void dispose(MemSlot*);
};
typedef QVector<MemSlot> MemSlotList;
#ifdef _MIC_MEM_CHECK
static QHash<MemSlot*,bool> dynamicSeqs;
#endif
static MemSlot* createSequence(int size)
{
MemSlot* s = new MemSlot[size+1];
s->t = MemSlot::Header;
s->u = size;
s++; // point to the second element which is the actual first element of the sequence
#ifdef _MIC_MEM_CHECK
dynamicSeqs.insert(s,false);
#endif
return s;
}
void MemSlot::copyOf(const MemSlot* rhs, bool record)
{
clear();
t = record ? Record : Array;
p = 0;
if( rhs == 0 )
return;
const MemSlot* header = rhs - 1;
Q_ASSERT(header->t == MemSlot::Header);
p = createSequence(header->u);
for(int i = 0; i < header->u; i++ )
p[i] = rhs[i];
}
void MemSlot::copyOf(const MemSlot* rhs, quint32 off, quint32 len, bool record)
{
clear();
t = record ? Record : Array;
if( rhs == 0 )
return;
if( len == 0 )
{
const MemSlot* header = rhs - 1;
Q_ASSERT(off == 0 && header->t == MemSlot::Header);
len = header->u;
}
p = createSequence(len);
for(int i = 0; i < len; i++ )
p[i] = rhs[i+off];
}
MemSlot& MemSlot::operator=(const MemSlot& rhs)
{
if( rhs.t == Array || rhs.t == Record )
copyOf(rhs.p, rhs.t == Record);
else
{
clear();
u = rhs.u;
t = rhs.t;
hw = rhs.hw;
}
return *this;
}
void MemSlot::move( MemSlot& rhs )
{
clear();
u = rhs.u;
t = rhs.t;
hw = rhs.hw;
embedded = rhs.embedded;
if( rhs.t == Record || rhs.t == Array )
rhs.p = 0;
}
void MemSlot::clear()
{
if( t == Record || t == Array )
dispose(p);
t = Invalid;
u = 0;
hw = 0;
}
MemSlot::~MemSlot()
{
clear();
}
void MemSlot::dispose(MemSlot* s)
{
if( s == 0 )
return;
#ifdef _MIC_MEM_CHECK
if( !dynamicSeqs.contains(s) )
qCritical() << "not dynamically allocated";
else if( dynamicSeqs.value(s) )
qCritical() << "double delete";
else
dynamicSeqs[s] = true;
#endif
MemSlot* header = s - 1;
Q_ASSERT(header->t == MemSlot::Header);
delete[] header;
}
struct ModuleData
{
MilModule* module;
MemSlotList variables;
QMap<const char*,ProcData*> procs;
ModuleData():module(0){}
~ModuleData()
{
QMap<const char*,ProcData*>::const_iterator i;
for( i = procs.begin(); i != procs.end(); ++i )
delete i.value();
}
};
class MilInterpreter::Imp
{
public:
Imp():loader(0),out(stdout) {}
MilLoader* loader;
QHash<const char*, ModuleData*> modules; // moduleFullName -> data
struct FlattenedType
{
const MilType* type;
quint32 len : 31; // flattened multi-dim-arrays
quint32 flattened : 1;
QList<MilVariable*> fields;
FlattenedType():type(0),len(0),flattened(0) {}
};
QHash<const MilType*,FlattenedType> flattened;
typedef QList< QList<int> > LoopStack;
struct MilLabel
{
quint32 labelPc;
QList<quint32> gotoPcs;
MilLabel():labelPc(0){}
};
typedef QHash<const char*,MilLabel> Labels;
typedef QHash<QByteArray,MemSlot*> Strings;
Strings strings; // internalized strings
QByteArray intrinsicMod, outMod, inputMod;
typedef QHash<const char*, MilProcedure> Intrinsics;
Intrinsics intrinsics;
QTextStream out;
#ifdef _USE_GETTIMEOFDAY
struct timeval start; // 57732 us for Bounce 1500, i.e. 23 times worse than Lua 5.4.7 without jump table
#else
QElapsedTimer timer; // NOTE: QElapsedTimer and gettimeofday are virtually identical
#endif
~Imp()
{
Strings::iterator i;
for( i = strings.begin(); i != strings.end(); ++i )
{
MemSlot::dispose(i.value());
i.value() = 0;
}
}
void dump(const MemSlot& s)
{
//out << "[" << (void*) &s << "] ";
switch( s.t )
{
case MemSlot::I:
out << s.i;
break;
case MemSlot::U:
out << s.u;
break;
case MemSlot::F:
out << s.f;
break;
case MemSlot::Pointer:
if( s.p == 0 )
out << "nil";
else
{
// out << (void*)s.sp;
out << "->";
if( (s.p-1)->t == MemSlot::Header && (s.p->t != MemSlot::Record || s.p->t != MemSlot::Array ) )
{
out << "[";
for( int i = 0; i < (s.p - 1)->u; i++ )
{
if( i != 0 )
out << " ";
dump(s.p[i]);
}
out << "]";
break;
}else
dump(*s.p);
}
break;
case MemSlot::Record:
case MemSlot::Array:
out << "(";
for( int i = 0; i < (s.p - 1)->u; i++ )
{
if( i != 0 )
out << " ";
dump(s.p[i]);
}
out << ")";
break;
case MemSlot::Procedure:
if( s.pp == 0 )
out << "none";
else
out << s.pp->module->module->fullName << "!" << s.pp->proc->name;
break;
default:
out << "?";
}
}
void dump( const MemSlotList& l, const QString& title)
{
out << "*** " << title << endl;
for( int i = 0; i < l.size(); i++ )
{
out << i << ": ";
dump(l[i]);
out << endl;
}
}
void dump(const QList<MemSlot>& stack)
{
out << "*** stack:" << endl;
for( int i = 0; i < stack.size(); i++ )
{
out << (i - stack.size() + 1) << ": ";
dump(stack[i]);
out << endl;
}
}
MemSlot* internalize(const QByteArray& str)
{
MemSlot* s = strings.value(str);
if( s == 0 )
{
s = createSequence(str.size());
for( int i = 0; i < str.size(); i++ )
{
s[i].t = MemSlot::U;
s[i].u = (quint8)str[i];
}
strings[str] = s;
}
return s;
}
static inline MemSlot::Type fromSymbol(const MilQuali& type)
{
MilEmitter::Type tt = MilEmitter::fromSymbol(type.second);
switch(tt)
{
case MilEmitter::I1: case MilEmitter::I2:
case MilEmitter::I4: case MilEmitter::I8:
return MemSlot::I;
case MilEmitter::R4: case MilEmitter::R8:
return MemSlot::F;
case MilEmitter::U1: case MilEmitter::U2:
case MilEmitter::U4: case MilEmitter::U8:
return MemSlot::U;
case MilEmitter::IntPtr:
return MemSlot::Pointer;
}
return MemSlot::Invalid;
}
void initSlot(ModuleData* module, MemSlot& s, const MilQuali& type )
{
FlattenedType* t = getFlattenedType(module, type);
if( t == 0 )
{
// maybe intrinsic type
s.t = fromSymbol(type);
return;
}
switch( t->type->kind )
{
// TODO Alias
case MilEmitter::Struct:
s.clear();
s.t = MemSlot::Record;
s.p = createSequence(t->fields.size());
initFields(module, s.p, t->fields);
break;
case MilEmitter::Array:
s.clear();
s.t = MemSlot::Array;
s.p = createSequence(t->len);
initArray(module, s.p, t->type->base);
break;
case MilEmitter::Pointer:
s.t = MemSlot::Pointer;
break;
case MilEmitter::ProcType:
s.t = MemSlot::Procedure;
break;
}
}
void initArray(ModuleData* module, MemSlot* ss, const MilQuali& etype )
{
MemSlot* header = ss-1;
Q_ASSERT( header->t == MemSlot::Header );
MilQuali q = etype;
FlattenedType* t = getFlattenedType(module,q);
while( t && t->type->kind == MilEmitter::Array )
{
// skip embedded arrays since multi-dim were flattened already and
// we just initialize the flattened one with the ultimate element type
q = t->type->base;
t = getFlattenedType(module,q);
}
//if( t == 0 || (t->type->kind != MilEmitter::Struct && t->type->kind != MilEmitter::Union) )
// return; // scalar or no struct/union type, no initialisation required
for( int i = 0; i < header->u; i++ )
initSlot(module,ss[i],q);
}
void initVars(ModuleData* module, MemSlot* ss, const QList<MilVariable>& types )
{
for(int i = 0; i < types.size(); i++ )
// slot can either be a flattened array or struct or union, or a scalar
initSlot(module, ss[i], types[i].type);
}
void initFields( ModuleData* module, MemSlot* ss, const QList<MilVariable*>& types )
{
for(int i = 0; i < types.size(); i++ )
{
FlattenedType* t = getFlattenedType(module,types[i]->type);
//if( t == 0 || t->type->kind != MilEmitter::Array )
// skip embedded structs/unions since they were flattened already
// continue;
initSlot(module, ss[i], types[i]->type);
}
}
ModuleData* loadModule(const QByteArray& fullName)
{
ModuleData* md = modules.value(fullName.constData());
if( md )
return md;
if( fullName.constData() == intrinsicMod.constData() )
{
md = new ModuleData();
modules.insert(fullName.constData(), md);
return md;
}
MilModule* module = loader->getModule(fullName);
if( module == 0 )
return 0;
md = new ModuleData();
md->module = module;
md->variables.resize(module->vars.size());
initVars(md, md->variables.data(),module->vars);
modules.insert(fullName.constData(), md);
for( int i = 0; i < module->imports.size(); i++ )
{
ModuleData* imp = loadModule(module->imports[i]);
if( imp == 0 )
return 0;
}
MilProcedure* init = 0;
for( int i = 0; i < module->procs.size(); i++ )
{
if( module->procs[i].kind == MilProcedure::ModuleInit )
{
init = &module->procs[i];
break;
}
}
if( init )
{
MemSlotList args;
MemSlot ret;
execute(md, init, args, ret);
}
return md;
}
void assureValid(ModuleData* module, const MilProcedure* proc, int start, int pc, int op1, int op2 = 0, int op3 = 0)
{
if( pc >= proc->body.size() )
{
QString what = s_opName[op1];
if( op2 )
what += QString(" | %1").arg(s_opName[op2]);
if( op3 )
what += QString(" | %1").arg(s_opName[op3]);
throw QString("%1!%2 statement %3 at pc %4 premature end when looking for %5")
.arg(module->module->fullName.constData())
.arg(proc->name.constData()).arg(s_opName[proc->body[start].op]).arg(start).arg(what);
}
if( proc->body[pc].op == op1 ||
(op2 && proc->body[pc].op == op2) ||
(op3 && proc->body[pc].op == op3))
return;
QString what = s_opName[op1];
if( op2 )
what += QString(" | %1").arg(s_opName[op2]);
if( op3 )
what += QString(" | %1").arg(s_opName[op3]);
throw QString("%1!%2 statement %3 at pc %4 missing %5 at pc %6")
.arg(module->module->fullName.constData())
.arg(proc->name.constData()).arg(s_opName[proc->body[start].op]).arg(start)
.arg(what).arg(pc);
}
void execError(ModuleData* module, const MilProcedure* proc, int pc, const QString& msg = QString())
{
throw QString("%1!%2 error at statement '%3' at pc %4 %5")
.arg(module->module->fullName.constData())
.arg(proc->name.constData()).arg(s_opName[proc->body[pc].op]).arg(pc).arg(msg);
}
void execError(ModuleData* module, const MilProcedure* proc, const QString& msg = QString())
{
throw QString("%1!%2 error: %3")
.arg(module->module->fullName.constData())
.arg(proc->name.constData()).arg(msg);
}
MilType* getType(ModuleData* module, const MilQuali& q)
{
// this is only for custom types defined with Emitter::addType or begin/endType, not for intrinsic types
MilModule* m = q.first.isEmpty() ? module->module : loader->getModule(q.first);
if( m == 0 )
return 0;
QPair<MilModule::What,quint32> what = m->symbols.value(q.second.constData());
if( what.first == MilModule::Type )
return &m->types[what.second];
// else
return 0;
}
FlattenedType* getFlattenedType(ModuleData* module, const MilQuali& q)
{
MilType* type = getType(module,q);
if( type == 0 )
return 0;
FlattenedType& ft = flattened[type];
if( ft.type == 0 )
{
if( type->kind == MilEmitter::Struct )
{
for( int i = 0; i < type->fields.size(); i++ )
{
FlattenedType* fieldType = getFlattenedType(module, type->fields[i].type);
// fieldType is null e.g. in case of int32
type->fields[i].offset = ft.fields.size();
if( fieldType && !fieldType->fields.isEmpty() )
{
// field is itself a struct or union, use the flattened fields
ft.fields << fieldType->fields;
ft.flattened = true;
}else
ft.fields << &type->fields[i]; // scalars, arrays, and fieldless structs or unions
}
}else if( type->kind == MilEmitter::Union )
{
for( int i = 0; i < type->fields.size(); i++ )
{
FlattenedType* fieldType = getFlattenedType(module, type->fields[i].type);
type->fields[i].offset = 0;
if( fieldType && !fieldType->fields.isEmpty() )
{
// field is itself a struct or union, use the flattened fields
if( ft.fields.size() < fieldType->fields.size() )
ft.fields = fieldType->fields; // use the largest field set
ft.flattened = true;
}else if( ft.fields.isEmpty() )
ft.fields << &type->fields[i]; // scalars, arrays, and fieldless structs or unions
}
}else if( type->kind == MilEmitter::Array )
{
FlattenedType* elemType = getFlattenedType(module, type->base);
ft.len = type->len ? type->len : 1;
if( elemType && elemType->type->kind == MilEmitter::Array )
{
ft.len *= elemType->len;
ft.flattened = true;
}
}
ft.type = type;
}
return &ft;
}
ProcData* getProc(ModuleData* module, const MilQuali& q)
{
ModuleData* m = q.first.isEmpty() ? module : loadModule(q.first);
if( m == 0 )
return 0; // error?
ProcData* res = m->procs.value(q.second.constData());
if( res )
return res;
MilProcedure* proc = 0;
if( m->module == 0 )
{
// intrinsic module
Intrinsics::iterator i = intrinsics.find(q.second.constData());
if( i == intrinsics.end() )
return 0;
proc = &i.value();
}else
{
QPair<MilModule::What,quint32> what = m->module->symbols.value(q.second.constData());
if( what.first != MilModule::Proc )
return 0; // error?
proc = &m->module->procs[what.second];
}
res = new ProcData(proc, m);
m->procs.insert(q.second.constData(), res);
return res;
}
void processBlock(ModuleData* module, MilProcedure* proc, quint32& pc, Labels& labels, LoopStack& loopStack)
{
QList<MilOperation>& ops = proc->body;
const int start = pc;
switch(ops[pc].op)
{
case IL_while:
{
// end -> while+1, then -> end+1
pc++;
while( pc < ops.size() && ops[pc].op != IL_do )
processBlock(module, proc,pc, labels, loopStack);
assureValid(module,proc,start,pc,IL_do);
const int then = pc;
pc++;
while( pc < ops.size() && ops[pc].op != IL_end )
processBlock(module, proc, pc, labels, loopStack); // look for nested statements
assureValid(module,proc,start,pc,IL_end);
ops[pc].index = start+1; // end jumps to while+1
pc++;
ops[then].index = pc; // then jumps to end+1
}
break;
case IL_switch:
{
// switch -> case -> case -> else -> end
pc++;
while( pc < ops.size() && ops[pc].op != IL_case &&
ops[pc].op != IL_else && ops[pc].op != IL_end )
processBlock(module, proc,pc, labels, loopStack);
assureValid(module,proc,start,pc,IL_case, IL_else, IL_end);
int prev = start;
QList<quint32> thenList;
while( ops[pc].op == IL_case )
{
ops[prev].index = pc;
prev = pc;
pc++;
assureValid(module,proc,start,pc,IL_then);
thenList.append(pc);
pc++;
while( pc < ops.size() && ops[pc].op != IL_case &&
ops[pc].op != IL_else && ops[pc].op != IL_end )
processBlock(module, proc, pc, labels, loopStack); // look for nested statements
assureValid(module,proc,start,pc,IL_case, IL_else, IL_end);
}
if( ops[pc].op == IL_else )
{
ops[prev].index = pc;
prev = pc;
thenList.append(pc);
pc++;
while( pc < ops.size() && ops[pc].op != IL_end )
processBlock(module, proc, pc, labels, loopStack);
}
assureValid(module,proc,start,pc,IL_end);
foreach( quint32 off, thenList )
ops[off].index = pc; // all then and else point to end
pc++;
}
break;
case IL_if:
{
// if -> then -> else -> end
pc++;
while( pc < ops.size() && ops[pc].op != IL_then )
processBlock(module, proc,pc, labels, loopStack);
assureValid(module,proc,start,pc, IL_then);
int then = pc;
pc++;
while( pc < ops.size() && ops[pc].op != IL_else && ops[pc].op != IL_end)
processBlock(module, proc, pc, labels, loopStack); // then statements
assureValid(module,proc,start,pc, IL_else, IL_end);
if( ops[pc].op == IL_else )
{
ops[then].index = pc+1; // then -> else+1
const int else_ = pc;
pc++;
while( pc < ops.size() && ops[pc].op != IL_end )
processBlock(module, proc, pc, labels, loopStack); // else statements
ops[else_].index = pc; // else -> end
}else
ops[then].index = pc; // then -> end
assureValid(module,proc,start,pc,IL_end);
pc++;
}
break;
case IL_repeat:
{
// end -> repeat+1
pc++;
while( pc < ops.size() && ops[pc].op != IL_until )
processBlock(module, proc, pc, labels, loopStack);
assureValid(module,proc,start,pc, IL_until);
pc++;
while( pc < ops.size() && ops[pc].op != IL_end )
processBlock(module, proc,pc, labels, loopStack);
assureValid(module,proc,start,pc, IL_end);
ops[pc].index = start+1;
pc++;
}
break;
case IL_loop:
{
// end -> loop
loopStack.push_back(QList<int>());
pc++;
while( pc < ops.size() && ops[pc].op != IL_end )
processBlock(module, proc, pc, labels, loopStack);
assureValid(module,proc,start,pc, IL_end);
ops[pc].index = start+1;
pc++;
foreach( int exit_, loopStack.back() )
ops[exit_].index = pc;
loopStack.pop_back();
}
break;
case IL_exit:
if( loopStack.isEmpty() )
execError(module, proc, pc, "operation not expected here");
loopStack.back().append(pc);
pc++;
break;
case IL_label:
labels[ops[pc].arg.toByteArray().constData()].labelPc = pc;
pc++;
break;
case IL_goto:
case IL_ifgoto:
labels[ops[pc].arg.toByteArray().constData()].gotoPcs.append(pc);
pc++;
break;
case IL_ldfld:
case IL_ldflda:
case IL_stfld:
{
MilTrident td = ops[pc].arg.value<MilTrident>();
FlattenedType* ty = getFlattenedType(module, td.first);
if( ty == 0 )
execError(module, proc, pc, QString("unknown type '%1'").
arg(MilEmitter::toString(td.first).constData()));
const int idx = ty->type->indexOf(td.second);
if( idx < 0 )
break; // error?
ops[pc].index = ty->type->fields[idx].offset;
}
pc++;
break;
case IL_ldvar:
case IL_ldvara:
case IL_stvar:
{
MilQuali q = ops[pc].arg.value<MilQuali>();
MilModule* m = q.first.isEmpty() ? module->module : loader->getModule(q.first);
if( m == 0 )
break; // error?
const int idx = m->indexOfVar(q.second);
if( idx < 0 )
break; // error?
// since the module is not a struct we don't flatten structs and the offset is the index in the field list
ops[pc].index = idx;
}
pc++;
break;
default:
pc++;
break;
}
}
void calcOffsets(ModuleData* module, MilProcedure* proc, quint32& pc)
{
Labels labels; // name -> label pos, goto poss
LoopStack loopStack;
while( pc < proc->body.size() )
{
processBlock(module, proc, pc, labels, loopStack);
}
Labels::const_iterator i;
for( i = labels.begin(); i != labels.end(); ++i )
{
for(int j = 0; j < i.value().gotoPcs.size(); j++ )
proc->body[i.value().gotoPcs[j]].index = i.value().labelPc;
}
}
void inline convertTo( QList<MemSlot>& stack, MemSlot::Type to, quint8 size )
{
MemSlot s = stack.takeLast();
switch(s.t)
{
case MemSlot::F:
if( to != s.t )
s.i = s.f;
break;
case MemSlot::I:
case MemSlot::U:
if( to == MemSlot::F )
s.f = s.i;
else if( to == MemSlot::I && size )
{
s.hw = size && size != 8;
switch(size)
{
case 1:
{
qint8 tmp = s.i;
s.i = tmp;
break;
}
case 2:
{
qint16 tmp = s.i;
s.i = tmp;
break;
}
case 4:
{
qint32 tmp = s.i;
s.i = tmp;
break;
}
}
}else if( to == MemSlot::U && size )
{
s.hw = size && size != 8;
switch(size)
{
case 1:
{
quint8 tmp = s.u;
s.u = tmp;
break;
}
case 2:
{
quint16 tmp = s.u;
s.u = tmp;
break;
}
case 4:
{
quint32 tmp = s.u;
s.u = tmp;
break;
}
}
}
break;
case MemSlot::Pointer:
if( to == MemSlot::F )
s.f = s.i;
break;
default:
s.u = 0;
if( size && size < 8 )
s.hw = true;
break;
}
s.t = to;
stack.push_back(s);
}
void convert(MemSlot& out, const QVariant& data )
{
out.clear();
if( data.canConvert<MilRecordLiteral>() )
{
// TODO: flatten embedded elements
MilRecordLiteral m = data.value<MilRecordLiteral>();
out.p = createSequence(m.size());
out.t = MemSlot::Record;
for( int i = 0; i < m.size(); i++ )
convert(out.p[i], m[i].second);
return;
}
switch( data.type() )
{
case QVariant::List:
{
// TODO: flatten multi-dim arrays
QVariantList l = data.toList();
out.p = createSequence(l.size());
out.t = MemSlot::Array;
for( int i = 0; i < l.size(); i++ )
convert(out.p[i], l[i]);
}
break;
case QVariant::ByteArray:
out.p = internalize(data.toByteArray());
out.t = MemSlot::Pointer;
break;
case QVariant::String:
out.p = internalize(data.toString().toLatin1());
out.t = MemSlot::Pointer;
break;
case QVariant::LongLong:
case QVariant::Int:
case QVariant::Bool:
out.i = data.toLongLong();
out.t = MemSlot::I; // TODO: hw
break;
case QVariant::ULongLong:
case QVariant::UInt:
out.u = data.toULongLong();
out.t = MemSlot::U; // TODO: hw
break;
case QVariant::Double:
out.f = data.toDouble();
out.t = MemSlot::F;
break;
default:
Q_ASSERT(false);
}
}
inline void makeCall(QList<MemSlot>& stack, ProcData* proc)
{
// TODO: support varargs
MemSlotList args(proc->proc->params.size());
for( int i = proc->proc->params.size()-1; i >= 0; i-- )
{
if( stack.isEmpty() )
execError(proc->module,proc->proc,"not enough actual parameters");
args[i].move(stack.back());
stack.pop_back();
}
MemSlot ret;
execute(proc->module, proc->proc, args, ret);
if( !proc->proc->retType.second.isEmpty() )
{
stack.push_back(MemSlot());
stack.back().move(ret);
}
}
static inline QByteArray toStr(const MemSlot& s)
{
Q_ASSERT( (s.t == MemSlot::Pointer || s.t == MemSlot::Array) && s.p );
#if 0
MemSlot* header = s.sp - 1;
Q_ASSERT( header->t == MemSlot::Header );