-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.cc
More file actions
1286 lines (1234 loc) · 33.7 KB
/
codegen.cc
File metadata and controls
1286 lines (1234 loc) · 33.7 KB
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
#include "interpretor.h"
#include "vmachine.h"
class cgen {
int normal_read = 0;
int agg_phase = 0; //0 is not grouping, 1 is first read, 2 is aggregate retrieval
int select_count = 0;
int joinFileIdx = 0;
int prevJoinRead = 0;
int wherenot = 0;
bool headerdone = false;
vector<int> valposTypes;
vector<pair<int,int>> dualPhaseGroupVars;
vector<opcode>& v;
jumpPositions jumps;
varScoper vs;
querySpecs* q;
public:
void addop(int code);
void addop(int code, int p1);
void addop(int code, int p1, int p2);
void addop(int code, int p1, int p2, int p3);
void generateCode();
void genScanAndChain(astnode &n, int fileno);
void genAndChainSet(astnode &n);
void genSortAnds(astnode &n);
void genJoinPredicates(astnode &n);
void genJoinCompare(astnode &n);
void genJoinSets(astnode &n);
void genTraverseJoins(astnode &n);
void genScanJoinFiles(astnode &n);
void genScannedJoinExprs(astnode &n, int fileno);
void genNormalOrderedQuery(astnode &n);
void genNormalQuery(astnode &n);
void genGroupingQuery(astnode &n);
void genJoiningQuery(astnode &n);
void genAggSortList(astnode &n);
void genVars(astnode &n);
void genWhere(astnode &n);
void genDistinct(int goWhenNot);
void genGetGroup(astnode &n);
void genSelect(astnode &n);
void genExprAll(astnode &n);
void genExprAdd(astnode &n);
void genExprMult(astnode &n);
void genExprNeg(astnode &n);
void genExprCase(astnode &n);
void genCPredList(astnode &n, int end);
void genCWExprList(astnode &n, int end);
void genNormalSortList(astnode &n);
void genCPred(astnode &n, int end);
void genCWExpr(astnode &n, int end);
void genPredicates(astnode &n);
void genPredCompare(astnode &n);
void genValue(astnode &n);
void genFunction(astnode &n);
void genPrint();
void genHeader();
void genSelectAll();
void genSelections(astnode &n);
void genTypeConv(astnode &n);
void genIterateGroups(astnode &n);
void genUnsortedGroupRow(astnode &n, int nextgroup, int doneGroups);
void genSortedGroupRow(astnode &n, int nextgroup);
void genEndrun();
void finish();
cgen(querySpecs &qs): q{&qs}, v{qs.bytecode} {}
};
void cgen::addop(int code){ addop(code,0,0,0); }
void cgen::addop(int code, int p1){ addop(code,p1,0,0); }
void cgen::addop(int code, int p1, int p2){ addop(code,p1,p2,0); }
void cgen::addop(int code, int p1, int p2, int p3){
debugAddop
v.push_back({code, p1, p2, p3});
}
static const int funcTypes[] = { 0,0,1,0,0,2 };
//for debugging
static int ident = 0;
//#define e //turn off debug printer
#ifndef e
#define e(A) { \
string spc; \
for (int i=0; i< ident; i++) spc += " "; \
perr(st(spc, A )); \
ident++; } \
shared_ptr<void> _(nullptr, [&n](...){ \
ident--; \
string spc; \
for (int i=0; i< ident; i++) spc += " "; \
perr(st(spc,"done ",A)); });
#endif
#define pushvars() for (auto &i : q->vars) addop(PUSH);
void jumpPositions::updateBytecode(vector<opcode> &vec) {
for (auto &v : vec)
if (opDoesJump(v.code) && v.p1 < 0)
v.p1 = jumps[v.p1];
};
void cgen::generateCode(){
if (q->joining)
genJoiningQuery(q->tree);
else if (q->grouping)
genGroupingQuery(q->tree);
else if (q->sorting)
genNormalOrderedQuery(q->tree);
else
genNormalQuery(q->tree);
jumps.updateBytecode(v);
finish();
}
void cgen::finish(){
int i = 0;
for (auto c : v){
perr(st("ip: ",left,setw(4),i++,c.print()));
}
}
void codeGen(querySpecs &q){
cgen cg(q);
cg.generateCode();
}
//generate bytecode for expression nodes
void cgen::genExprAll(astnode &n){
if (n == nullptr) return;
switch (n->label){
case N_EXPRADD: genExprAdd (n); break;
case N_EXPRNEG: genExprNeg (n); break;
case N_EXPRMULT: genExprMult (n); break;
case N_EXPRCASE: genExprCase (n); break;
case N_PREDICATES: genPredicates (n); break;
case N_PREDCOMP: genPredCompare (n); break;
case N_VALUE: genValue (n); break;
case N_FUNCTION: genFunction (n); break;
case N_TYPECONV: genTypeConv (n); break;
}
}
void cgen::genEndrun(){
addop(ENDRUN);
}
//given q.tree as node param
void cgen::genJoiningQuery(astnode &n){
e("basic join");
pushvars();
joinFileIdx = 0;
if (q->grouping)
agg_phase = 1;
genScanJoinFiles(n->nfrom()->njoins());
genHeader();
joinFileIdx = 0;
genTraverseJoins(n->nfrom());
if (q->grouping){ // includes group sorting
agg_phase = 2;
genIterateGroups(n->nafterfrom()->ngroups());
} else if (q->sorting){
int reread = jumps.newPlaceholder();
int endreread = jumps.newPlaceholder();
addop(SORT);
addop(PREP_REREAD);
jumps.setPlace(reread, v.size());
addop(RDLINE_ORDERED, endreread);
vs.setscope(SELECT_FILTER, V_READ2_SCOPE);
genVars(n->npreselect());
genSelect(n->nselect());
genDistinct(reread);
genPrint();
addop((q->quantityLimit > 0 ? JMPCNT : JMP), reread);
jumps.setPlace(endreread, v.size());
}
genEndrun();
}
//given 'from' node
void cgen::genTraverseJoins(astnode &n){
if (n == nullptr) return;
//start with base file
addop(START_MESSAGE, messager::readingfirst);
int endfile1 = jumps.newPlaceholder();
normal_read = v.size();
prevJoinRead = normal_read;
addop(RDLINE, endfile1, 0);
genJoinSets(n->njoins());
jumps.setPlace(endfile1, v.size());
addop(STOP_MESSAGE);
}
//given 'join' node
void cgen::genJoinSets(astnode &n){
if (n == nullptr) {
if (q->grouping){ // includes group sorting
genWhere(q->tree->nafterfrom());
genGetGroup(q->tree->nafterfrom()->ngroups());
vs.setscope(SELECT_FILTER|ORDER_FILTER|HAVING_FILTER, V_READ1_SCOPE);
genVars(q->tree->npreselect());
genSelect(q->tree->nselect());
genAggSortList(q->tree->nafterfrom());
genPredicates(q->tree->nafterfrom()->nhaving()); //having phase 1
addop(JMP, prevJoinRead);
} else if (q->sorting){
genWhere(q->tree->nafterfrom());
genNormalSortList(q->tree->nafterfrom());
addop(SAVEPOS);
addop(JMP, prevJoinRead);
} else {
genWhere(q->tree->nafterfrom());
vs.setscope(SELECT_FILTER, V_READ1_SCOPE);
genVars(q->tree->npreselect());
genSelect(q->tree->nselect());
genDistinct(prevJoinRead);
genPrint();
addop((q->quantityLimit > 0 ? JMPCNT : JMP), prevJoinRead);
}
return;
}
// could genwhere per file
joinFileIdx++;
vs.setscope(JCOMP_FILTER, V_READ1_SCOPE);
genVars(q->tree->npreselect());
genJoinPredicates(n->njoinconds());
addop(JOINSET_INIT, (joinFileIdx-1)*2, n->tok3 == "left");
int goWhenDone = prevJoinRead;
prevJoinRead = v.size();
wherenot = prevJoinRead;
addop(JOINSET_TRAV, goWhenDone, (joinFileIdx-1)*2, joinFileIdx);
genJoinSets(n->nnextjoin());
}
void cgen::genHeader(){
if (headerdone)
return;
headerdone = true;
if (!globalSettings.termbox && q->outputcsv && q->outputcsvheader)
addop(PRINTCSV_HEADER);
}
void cgen::genPrint(){
if (q->outputjson)
addop(PRINTJSON, q->outputcsv ? 0 : 1);
if (q->outputhtml)
addop(PRINTHTML, q->outputcsv ? 0 : 1);
if (q->outputcsv){
if (globalSettings.termbox)
addop(PRINTBOX);
else
addop(PRINTCSV);
}
if (q->isSubquery == SQ_INLIST){
q->thisSq->btreeIdx = addBtree(q->thisSq->singleDatatype, q);
addop(PRINTBTREE, q->thisSq->btreeIdx);
}
}
void cgen::genAndChainSet(astnode &n){
int cz = n->chainSize();
int ci = n->chainIdx();
int fi = n->predFileNum();
auto& chain = q->getFileReader(fi)->andchains[ci];
auto nn = n.get();
for (int i=0; i<cz; ++i){
auto& prednode = nn->npredcomp();
if (prednode->relop() == KW_LIKE){
addop(LDLIT, q->dataholder.size());
q->dataholder.push_back(prepareLike(prednode));
} else if (prednode->scannedExpr() == 1){
genExprAll(prednode->npredexp2());
}else if (prednode->scannedExpr() == 2){
genExprAll(prednode->npredexp1());
}
chain.functionTypes.push_back(funcTypes[prednode->datatype]);
chain.relops.push_back(vmachine::relopIdx[prednode->relop()]);
chain.negations.push_back(prednode->negated());
nn = nn->nnextpreds().get();
}
chain.relops[0] = 4; // 4 is index of eq, instruction already konws real first relop
int orEquals = 0;
switch (n->npredcomp()->relop()){
case SP_EQ:
addop(JOINSET_EQ_AND, fi, ci);
break;
case SP_LESSEQ:
orEquals = 1;
case SP_LESS:
addop(PUSH_N, orEquals);
addop(JOINSET_LESS_AND, fi, ci);
break;
case SP_GREATEQ:
orEquals = 1;
case SP_GREAT:
addop(PUSH_N, orEquals);
addop(JOINSET_GRT_AND, fi, ci);
break;
default:
error("joins with '",n->tok1,"' operator in first of 'and' conditions not implemented");
}
}
//given 'predicates' node
void cgen::genJoinPredicates(astnode &n){
if (n == nullptr) return;
if (n->andChain()){
genAndChainSet(n);
return;
}
genJoinPredicates(n->nnextpreds());
genJoinCompare(n->npredcomp());
switch (n->logop()){
case KW_AND:
addop(AND_SET);
break;
case KW_OR:
addop(OR_SET);
break;
case KW_XOR:
addop(XOR_SET);
break;
}
}
//given predicate comparison node
void cgen::genJoinCompare(astnode &n){
if (n == nullptr) return;
if (n->relop() == SP_LPAREN){
genJoinPredicates(n->nmorepreds());
return;
}
//evaluate the one not scanned
if (n->scannedExpr() == 1){
genExprAll(n->npredexp2());
} else if (n->scannedExpr() == 2){
genExprAll(n->npredexp1());
}
if (n->datatype == T_STRING)
addop(NUL_TO_STR);
int orEquals = 0, vpidx = n->predValposIdx();
switch (n->relop()){
case SP_EQ:
addop(JOINSET_EQ, joinFileIdx, vpidx, funcTypes[valposTypes[vpidx]]);
break;
case SP_LESSEQ:
orEquals = 1;
case SP_LESS:
addop(PUSH_N, orEquals);
addop(JOINSET_LESS, joinFileIdx, vpidx, funcTypes[valposTypes[vpidx]]);
break;
case SP_GREATEQ:
orEquals = 1;
case SP_GREAT:
addop(PUSH_N, orEquals);
addop(JOINSET_GRT, joinFileIdx, vpidx, funcTypes[valposTypes[vpidx]]);
break;
default:
error("joins with '",n->tok1,"' operator not implemented");
}
}
void cgen::genScanJoinFiles(astnode &n){
e("scan joins");
auto& joinNode = findFirstNode(n, N_JOIN);
for (auto jnode = joinNode.get(); jnode; jnode = jnode->nnextjoin().get()){
auto& f = q->filemap[jnode->nfile()->filealias()];
int afterfile = jumps.newPlaceholder();
addop(START_MESSAGE, messager::scanningjoin);
normal_read = v.size();
addop(RDLINE, afterfile, f->fileno);
joinFileIdx++;
f->vpTypes = std::move(valposTypes);
valposTypes.clear();
vs.setscope(JSCAN_FILTER, V_SCAN_SCOPE);
genVars(q->tree->npreselect());
genScannedJoinExprs(jnode->njoinconds(), f->fileno);
if (valposTypes.size())
addop(SAVEVALPOS, f->fileno, f->joinValpos.size());
addop(JMP, normal_read);
jumps.setPlace(afterfile, v.size());
addop(START_MESSAGE, messager::indexing);
genSortAnds(joinNode->njoinconds());
for (u32 i=0; i<valposTypes.size(); i++)
addop(SORTVALPOS, f->fileno, i, funcTypes[valposTypes[i]]);
}
}
void cgen::genSortAnds(astnode &n){
if (n == nullptr) return;
e("sort ands");
if (n->andChain() == 1){
addop(SORT_ANDCHAIN, n->predFileNum(), n->chainIdx());
return;
} else {
genSortAnds(n->nnextpreds());
if (n->npredcomp()->relop() == SP_LPAREN)
genSortAnds(n->npredcomp()->nmorepreds());
}
}
void cgen::genScanAndChain(astnode &n, int fileno){
if (n == nullptr || n->andChain() == 0) return;
e("join ands");
auto nn = n.get();
for (int i=0; i<n->chainSize(); ++i){
auto& prednode = nn->npredcomp();
if (prednode->scannedExpr() == 1){
genExprAll(prednode->npredexp1());
}else if (prednode->scannedExpr() == 2){
genExprAll(prednode->npredexp2());
}
nn = nn->nnextpreds().get();
}
addop(SAVEANDCHAIN, n->chainIdx(), fileno);
}
void cgen::genScannedJoinExprs(astnode &n, int fileno){
if (n == nullptr) return;
e("join exprs");
bool gotExpr = false;
switch (n->label){
case N_PREDCOMP:
if (n->andChain()) //this is just for valpos joins
return;
if (n->relop() == SP_LPAREN)
genScannedJoinExprs(n->nmorepreds(), fileno);
else if (n->scannedExpr() == 1){
genExprAll(n->npredexp1());
gotExpr = true;
}else if (n->scannedExpr() == 2){
genExprAll(n->npredexp2());
gotExpr = true;
}else{
error("invalid join comparision");
}
if (gotExpr){
valposTypes.push_back(n->datatype);
if (n->datatype == T_STRING)
addop(NUL_TO_STR);
}
break;
case N_PREDICATES:
if (n->andChain()){ //handle andchains separately
genScanAndChain(n, fileno);
return;
}
default:
genScannedJoinExprs(n->node1, fileno);
genScannedJoinExprs(n->node2, fileno);
genScannedJoinExprs(n->node3, fileno);
genScannedJoinExprs(n->node4, fileno);
break;
}
}
void cgen::genNormalQuery(astnode &n){
e("normal");
int message = (q->whereFiltering || q->distinctFiltering) ?
messager::readingfiltered : messager::reading;
int endfile = jumps.newPlaceholder(); //where to jump when done reading file
pushvars();
genHeader();
addop(START_MESSAGE, message);
normal_read = v.size();
wherenot = normal_read;
addop(RDLINE, endfile, 0);
genWhere(n->nafterfrom());
vs.setscope(SELECT_FILTER, V_READ1_SCOPE);
genVars(n->npreselect());
genSelect(n->nselect());
genDistinct(normal_read);
genPrint();
addop((q->quantityLimit > 0 ? JMPCNT : JMP), normal_read);
jumps.setPlace(endfile, v.size());
addop(STOP_MESSAGE);
genEndrun();
}
void cgen::genNormalOrderedQuery(astnode &n){
int sorter = jumps.newPlaceholder(); //where to jump when done scanning file
int reread = jumps.newPlaceholder();
int endreread = jumps.newPlaceholder();
pushvars();
addop(START_MESSAGE, messager::scanning);
normal_read = v.size();
wherenot = normal_read;
addop(RDLINE, sorter, 0);
genWhere(n->nafterfrom());
genNormalSortList(n->nafterfrom());
addop(SAVEPOS);
addop(JMP, normal_read);
jumps.setPlace(sorter, v.size());
addop(START_MESSAGE, messager::sorting);
addop(SORT);
addop(PREP_REREAD);
addop(START_MESSAGE, messager::retrieving);
genHeader();
jumps.setPlace(reread, v.size());
addop(RDLINE_ORDERED, endreread);
vs.setscope(SELECT_FILTER, V_READ2_SCOPE);
genVars(n->npreselect());
genSelect(n->nselect());
genDistinct(reread);
genPrint();
addop((q->quantityLimit > 0 ? JMPCNT : JMP), reread);
jumps.setPlace(endreread, v.size());
addop(STOP_MESSAGE);
genEndrun();
};
//given afterfrom node
void cgen::genNormalSortList(astnode &n){
e("normal sort list");
if (n == nullptr) return;
vs.setscope(ORDER_FILTER, V_READ1_SCOPE);
genVars(q->tree->npreselect());
auto& ordnode = findFirstNode(n, N_ORDER);
int i = 0;
for (auto x = ordnode->norderlist().get(); x; x = x->nnextlist().get()){
genExprAll(x->nsubexpr());
if (x->datatype == T_STRING)
addop(NUL_TO_STR);
addop(operations[OPSVSRT][x->datatype], i++);
q->sortInfo.push_back({x->orderdirection(), x->datatype});
}
}
void cgen::genGroupingQuery(astnode &n){
e("grouping");
agg_phase = 1;
int getgroups = jumps.newPlaceholder();
pushvars();
addop(START_MESSAGE, messager::scanning);
genHeader();
normal_read = v.size();
wherenot = normal_read;
addop(RDLINE, getgroups, 0);
genWhere(n->nafterfrom());
genGetGroup(n->nafterfrom()->ngroups());
vs.setscope(SELECT_FILTER|HAVING_FILTER|ORDER_FILTER, V_READ1_SCOPE);
genVars(n->npreselect());
genPredicates(n->nafterfrom()->nhaving()); //having phase 1
genSelect(n->nselect());
genAggSortList(n);
addop(JMP, normal_read);
jumps.setPlace(getgroups, v.size());
agg_phase = 2;
addop(STOP_MESSAGE);
genIterateGroups(n->nafterfrom()->ngroups());
genEndrun();
}
void cgen::genAggSortList(astnode &n){
if (n == nullptr) return;
e("agg sort list");
switch (n->label){
case N_QUERY: genAggSortList(n->nafterfrom()); break;
case N_AFTERFROM: genAggSortList(n->norder()); break;
case N_ORDER: genAggSortList(n->norderlist()); break;
case N_EXPRESSIONS: // sort list
genExprAdd(n->nsubexpr());
genAggSortList(n->nnextlist());
}
}
void cgen::genVars(astnode &n){
if (n == nullptr) return;
e("gen vars");
switch (n->label){
case N_PRESELECT: //currently only has 'with' branch
case N_WITH:
genVars(n->node1);
break;
case N_VARS:
{
int i = q->getVarIdx(n->varname());
auto& var = q->vars[i];
if (vs.neededHere(i, var.filter, var.maxfileno)){
genExprAll(n->nsubexpr());
if (n->phase == (1|2)){
//non-aggs in phase2
if (agg_phase == 1){
if (vs.scopefilter == GROUPING_FILTER || (vs.scopefilter == WHERE_FILTER && q->grouping)){ //need to get group before storing it there
addop1(PUTVAR, i);
dualPhaseGroupVars.push_back({i,n->varmididx()});
} else {
addop2(PUTVAR2, i, n->varmididx());
}
} else {
addop1(LDMID, n->varmididx());
addop1(PUTVAR, i);
if (q->sorting && q->getVarType(n->varname()) == T_STRING){
addop1(HOLDVAR, i);
}
}
} else {
addop1(PUTVAR, i);
if (agg_phase == 2 && q->sorting && q->getVarType(n->varname()) == T_STRING){
addop1(HOLDVAR, i);
}
}
}
genVars(n->nnextvar());
}
break;
}
}
void cgen::genExprAdd(astnode &n){
if (n == nullptr) return;
e("gen add");
genExprAll(n->node1);
if (!n->mathop()) return;
genExprAll(n->node2);
switch (n->mathop()){
case SP_PLUS:
addop0(operations[OPADD][n->datatype]);
break;
case SP_MINUS:
addop0(operations[OPSUB][n->datatype]);
break;
}
}
void cgen::genExprMult(astnode &n){
if (n == nullptr) return;
e("gen mult");
genExprAll(n->node1);
if (!n->mathop()) return;
genExprAll(n->node2);
switch (n->mathop()){
case SP_STAR:
addop0(operations[OPMULT][n->datatype]);
break;
case SP_DIV:
addop0(operations[OPDIV][n->datatype]);
break;
case SP_CARROT:
addop0(operations[OPPOW][n->datatype]);
break;
case SP_MOD:
addop0(operations[OPMOD][n->datatype]);
break;
}
}
void cgen::genExprNeg(astnode &n){
if (n == nullptr) return;
e("gen neg");
genExprAll(n->node1);
if (!n->mathop()) return;
addop0(operations[OPNEG][n->datatype]);
}
void cgen::genValue(astnode &n){
if (n == nullptr) return;
e("gen value: "+n->tok1.val);
dat lit;
int vtype, op;
switch (n->valtype()){
case COLUMN:
addop2(operations[OPLD][n->datatype], q->getFileNo(n->dotsrc()), n->colidx());
break;
case LITERAL:
if (n->tok1 == "null"){
addop0(PUSH);
} else {
switch (n->datatype){
case T_INT: lit = parseIntDat(n->val().c_str()); break;
case T_FLOAT: lit = parseFloatDat(n->val().c_str()); break;
case T_DATE: lit = parseDateDat(n->val().c_str()); break;
case T_DURATION: lit = parseDurationDat(n->val().c_str()); break;
case T_STRING: lit = parseStringDat(n->val().c_str()); break;
}
addop1(LDLIT, q->dataholder.size());
q->dataholder.push_back(lit);
}
break;
case VARIABLE:
addop1(LDVAR, q->getVarIdx(n->varname()));
//variable may be used in operations with different types
vtype = q->getVarType(n->varname());
op = typeConv[vtype][n->datatype];
if (op == CVER)
error("Cannot use alias '",n->val(),"' of type ",gettypename(vtype)," with incompatible type ",gettypename(n->datatype));
if (op != CVNO)
addop0(op);
break;
case FUNCTION:
genExprAll(n->nsubexpr());
break;
}
}
void cgen::genExprCase(astnode &n){
if (n == nullptr) return;
e("gen case");
int caseEnd = jumps.newPlaceholder();
switch (n->casenodetype()){
case KW_CASE:
switch (n->casetype()){
//when predicates are true
case KW_WHEN:
genCPredList(n->node1, caseEnd);
genExprAll(n->node3);
if (n->node3 == nullptr)
addop0(PUSH);
jumps.setPlace(caseEnd, v.size());
break;
//expression matches expression list
case WORD_TK:
case SP_LPAREN:
genExprAll(n->node1);
genCWExprList(n->node2, caseEnd);
addop0(POP); //don't need comparison value anymore
genExprAll(n->node3);
if (n->node3 == nullptr)
addop0(PUSH);
jumps.setPlace(caseEnd, v.size());
break;
}
break;
case SP_LPAREN:
case WORD_TK:
genExprAll(n->nsubexpr());
}
}
void cgen::genCWExprList(astnode &n, int end){
if (n == nullptr) return;
e("gen case w list");
genCWExpr(n->node1, end);
genCWExprList(n->node2, end);
}
void cgen::genCWExpr(astnode &n, int end){
if (n == nullptr) return;
e("gen case w expr");
int nextCase = jumps.newPlaceholder(); //get jump pos for next try
genExprAll(n->node1); //evaluate comparision expression
addop1(operations[OPEQ][n->tok1.id], 0); //leave '=' result where this comp value was
addop2(JMPFALSE, nextCase, 1);
addop0(POP); //don't need comparison value anymore
genExprAll(n->ncaseresultexpr()); //result value if eq
addop1(JMP, end);
jumps.setPlace(nextCase, v.size()); //jump here for next try
}
void cgen::genCPredList(astnode &n, int end){
if (n == nullptr) return;
e("gen case p list");
genCPred(n->node1, end);
genCPredList(n->node2, end);
}
void cgen::genCPred(astnode &n, int end){
if (n == nullptr) return;
e("gen case p");
int nextCase = jumps.newPlaceholder(); //get jump pos for next try
genPredicates(n->node1);
addop2(JMPFALSE, nextCase, 1);
genExprAll(n->node2); //result value if true
addop1(JMP, end);
jumps.setPlace(nextCase, v.size()); //jump here for next try
}
//given select node
void cgen::genSelect(astnode &n){
if (n == nullptr) {
//no selection branch
genSelectAll();
return;
}
genSelections(n->nselections());
}
//given selections node
void cgen::genSelections(astnode &n){
if (n == nullptr) {
//reached end of selections section of query
if (!select_count && agg_phase != 1) genSelectAll();
return;
}
e("gen selections");
switch (n->label){
case N_SELECTIONS:
if (n->startok() == "*") {
genSelectAll();
} else if (isTrivialColumn(n)) {
switch (agg_phase){
case 0:
for (auto nn = n.get(); nn; nn = nn->node1.get()) if (nn->label == N_VALUE){
addop3(LDPUT, n->selectiondestidx(), nn->colidx(), q->getFileNo(nn->dotsrc()));
break;
} break;
case 1:
for (auto nn = n.get(); nn; nn = nn->node1.get()) if (nn->label == N_VALUE){
addop3(LDPUTGRP, n->selectionmididx(), nn->colidx(), q->getFileNo(nn->dotsrc()));
break;
} break;
case 2:
addop2(LDPUTMID, n->selectiondestidx(), n->selectionmididx());
break;
}
incSelectCount();
} else if (agg_phase == 2 && n->selectionlpmid()) {
addop2(LDPUTMID, n->selectiondestidx(), n->selectionmididx());
} else {
genExprAll(n->node1);
int dest = agg_phase == 1 ? n->selectionmididx() : n->selectiondestidx();
addop1(PUT, dest);
incSelectCount();
}
break;
default:
error("selections generator error");
return;
}
genSelections(n->node2);
}
void cgen::genPredicates(astnode &n){
if (n == nullptr) return;
e("gen preds");
genPredCompare(n->npredcomp());
int doneAndOr = jumps.newPlaceholder();
int xor1true;
switch (n->logop()){
case KW_AND:
addop2(JMPFALSE, doneAndOr, 0);
addop0(POP); //don't need old result
genPredicates(n->nnextpreds());
break;
case KW_OR:
addop2(JMPTRUE, doneAndOr, 0);
addop0(POP); //don't need old result
genPredicates(n->nnextpreds());
break;
case KW_XOR:
xor1true = jumps.newPlaceholder();
genPredicates(n->nnextpreds());
addop2(JMPTRUE, xor1true, 0);
addop0(POP);
addop1(JMP, doneAndOr);
jumps.setPlace(xor1true, v.size());
addop0(POP);
addop0(PNEG);
break;
}
jumps.setPlace(doneAndOr, v.size());
if (n->tok2 == SP_NEGATE)
addop0(PNEG);
}
void cgen::genPredCompare(astnode &n){
if (n == nullptr) return;
e("gen pred compare");
int negation = n->negated();
int endcomp, greaterThanExpr3, subq=0;
genExprAll(n->npredexp1());
switch (n->relop()){
case SP_NOEQ: negation ^= 1;
case SP_EQ:
genExprAll(n->npredexp2());
addop2(operations[OPEQ][n->datatype], 1, negation);
break;
case SP_GREATEQ: negation ^= 1;
case SP_LESS:
genExprAll(n->npredexp2());
addop2(operations[OPLT][n->datatype], 1, negation);
break;
case SP_GREAT: negation ^= 1;
case SP_LESSEQ:
genExprAll(n->npredexp2());
addop2(operations[OPLEQ][n->datatype], 1, negation);
break;
case KW_BETWEEN:
endcomp = jumps.newPlaceholder();
greaterThanExpr3 = jumps.newPlaceholder();
addop2(NULFALSE, endcomp, 0);
genExprAll(n->node2);
addop2(NULFALSE, endcomp, 1);
genExprAll(n->node3);
addop2(NULFALSE, endcomp, 2);
addop2(BETWEEN, funcTypes[n->datatype], negation);
jumps.setPlace(endcomp, v.size());
break;
case KW_IN:
if (n->nsetlist()->hassubquery()){
addop(INSUBQUERY, n->nsetlist()->subqidx());
subq = 1;
} else {
endcomp = jumps.newPlaceholder();
for (auto nn=n->nsetlist()->node1.get(); nn; nn=nn->nnextlist().get()){
genExprAll(nn->nsubexpr());
addop1(operations[OPEQ][n->npredexp1()->datatype], 0);
addop2(JMPTRUE, endcomp, 0);
if (nn->nnextlist().get())
addop0(POP);
}
jumps.setPlace(endcomp, v.size());
}
if (negation)
addop0(PNEG);
if (!subq)
addop0(POPCPY); //put result where 1st expr was
break;
case KW_LIKE:
addop2(LIKE, q->dataholder.size(), negation);
q->dataholder.push_back(prepareLike(n));
break;
}
}
void cgen::genSelectAll(){
addop(LDPUTALL, select_count);
for (auto& f : q->filevec)
select_count += f->numFields;
}
//given afterfrom node
void cgen::genWhere(astnode &nn){
auto& n = findFirstNode(nn, N_WHERE);
if (n == nullptr) return;
e("gen where");
vs.setscope(WHERE_FILTER, V_READ1_SCOPE);
genVars(q->tree->npreselect());
genPredicates(n->nwhere());
addop2(JMPFALSE, wherenot, 1);
}
void cgen::genDistinct(int goWhenNot){
if (!q->distinctFiltering) return;
auto& n = findFirstNode(q->tree, N_SELECTIONS);
e("gen distinct");
if (n) {
for (auto nn = n.get(); nn && nn->label == N_SELECTIONS; nn = nn->nnextselection().get()){
if (n->startok() == SP_STAR){
for (auto& f: q->filevec)
for (auto t : f->types)
q->selectiontypes.push_back(T_STRING);
} else {
q->selectiontypes.push_back(nn->datatype);
}
}
} else {
for (auto& f: q->filevec)
for (auto t : f->types)
q->selectiontypes.push_back(T_STRING);
}
auto types = q->selectiontypes;
if (q->grouping && q->sorting){
addop(DIST_NOALLOC, goWhenNot);
q->datArrayLess = [types](const dat*l, const dat*r) -> bool {
int i = 0;
for (auto t : types){
if (t == T_STRING && r[i].u.s && l[i].u.s){
if (int dif = strcmp(l[i].u.s, r[i].u.s); dif < 0) return true;
} else {
if (int dif = r[i].u.i - l[i].u.i; dif < 0) return true;
}
++i;
}
return false;
};
} else {
addop(DIST_NORM, goWhenNot);
q->unionArrayLess = [types](const datunion*l, const datunion*r) -> bool {
int i = 0;
for (auto t : types){
if (t == T_STRING && r[i].s && l[i].s){
if (int dif = strcmp(l[i].s, r[i].s); dif < 0) return true;
} else {
if (int dif = r[i].i - l[i].i; dif < 0) return true;
}
++i;
}
return false;
};
}
}
void cgen::genFunction(astnode &n){
if (n == nullptr) return;
e("gen function");
int funcDone = jumps.newPlaceholder();
int idx;
//stuff common to all aggregate functions
if ((n->funcid() & AGG_BIT) != 0 ) {
genExprAll(n->nsubexpr());
if (n->tok3 == "distinct" && agg_phase == 1){
int setIndex = n->funcdistnum();
int separateSets = 1;
if (q->grouping == 1){ //when onegroup, btree not indexed by rowgroup
setIndex = addBtree(n->nsubexpr()->datatype, q);
separateSets = 0;
}
addop(DIST_FUNC, funcDone, setIndex, separateSets);
addop(LDDIST);