/
Synthesiser.cpp
3286 lines (2805 loc) · 134 KB
/
Synthesiser.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
/**
* Souffle - A Datalog Compiler
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved
* Licensed under the Universal Permissive License v 1.0 as shown at:
* - https://opensource.org/licenses/UPL
* - <souffle root>/licenses/SOUFFLE-UPL.txt
*/
/************************************************************************
*
* @file Synthesiser.cpp
*
* Implementation of the C++ synthesiser for RAM programs.
*
***********************************************************************/
#include "synthesiser/Synthesiser.h"
#include "AggregateOp.h"
#include "FunctorOps.h"
#include "GenDb.h"
#include "Global.h"
#include "RelationTag.h"
#include "config.h"
#include "ram/AbstractParallel.h"
#include "ram/Aggregate.h"
#include "ram/Aggregator.h"
#include "ram/AutoIncrement.h"
#include "ram/Break.h"
#include "ram/Call.h"
#include "ram/Clear.h"
#include "ram/Condition.h"
#include "ram/Conjunction.h"
#include "ram/Constraint.h"
#include "ram/DebugInfo.h"
#include "ram/EmptinessCheck.h"
#include "ram/Erase.h"
#include "ram/ExistenceCheck.h"
#include "ram/Exit.h"
#include "ram/Expression.h"
#include "ram/False.h"
#include "ram/Filter.h"
#include "ram/FloatConstant.h"
#include "ram/IO.h"
#include "ram/IfExists.h"
#include "ram/IndexAggregate.h"
#include "ram/IndexIfExists.h"
#include "ram/IndexScan.h"
#include "ram/Insert.h"
#include "ram/IntrinsicAggregator.h"
#include "ram/IntrinsicOperator.h"
#include "ram/LogRelationTimer.h"
#include "ram/LogSize.h"
#include "ram/LogTimer.h"
#include "ram/Loop.h"
#include "ram/MergeExtend.h"
#include "ram/Negation.h"
#include "ram/NestedIntrinsicOperator.h"
#include "ram/NestedOperation.h"
#include "ram/Node.h"
#include "ram/Operation.h"
#include "ram/PackRecord.h"
#include "ram/Parallel.h"
#include "ram/ParallelAggregate.h"
#include "ram/ParallelIfExists.h"
#include "ram/ParallelIndexAggregate.h"
#include "ram/ParallelIndexIfExists.h"
#include "ram/ParallelIndexScan.h"
#include "ram/ParallelScan.h"
#include "ram/Program.h"
#include "ram/ProvenanceExistenceCheck.h"
#include "ram/Query.h"
#include "ram/Relation.h"
#include "ram/RelationOperation.h"
#include "ram/RelationSize.h"
#include "ram/Scan.h"
#include "ram/Sequence.h"
#include "ram/SignedConstant.h"
#include "ram/Statement.h"
#include "ram/SubroutineArgument.h"
#include "ram/SubroutineReturn.h"
#include "ram/Swap.h"
#include "ram/TranslationUnit.h"
#include "ram/True.h"
#include "ram/TupleElement.h"
#include "ram/TupleOperation.h"
#include "ram/UndefValue.h"
#include "ram/UnpackRecord.h"
#include "ram/UnsignedConstant.h"
#include "ram/UserDefinedAggregator.h"
#include "ram/UserDefinedOperator.h"
#include "ram/analysis/Index.h"
#include "ram/utility/Utils.h"
#include "ram/utility/Visitor.h"
#include "souffle/BinaryConstraintOps.h"
#include "souffle/RamTypes.h"
#include "souffle/TypeAttribute.h"
#include "souffle/utility/ContainerUtil.h"
#include "souffle/utility/FileUtil.h"
#include "souffle/utility/MiscUtil.h"
#include "souffle/utility/StreamUtil.h"
#include "souffle/utility/StringUtil.h"
#include "souffle/utility/json11.h"
#include "souffle/utility/tinyformat.h"
#include "synthesiser/GenDb.h"
#include "synthesiser/Relation.h"
#include "synthesiser/Utils.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iterator>
#include <limits>
#include <map>
#include <sstream>
#include <tuple>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <vector>
namespace souffle::synthesiser {
using json11::Json;
using ram::analysis::IndexAnalysis;
using namespace ram;
using namespace stream_write_qualified_char_as_number;
/** Lookup frequency counter */
unsigned Synthesiser::lookupFreqIdx(const std::string& txt) {
static unsigned ctr;
auto pos = idxMap.find(txt);
if (pos == idxMap.end()) {
return idxMap[txt] = ctr++;
} else {
return idxMap[txt];
}
}
/** Lookup frequency counter */
std::size_t Synthesiser::lookupReadIdx(const std::string& txt) {
std::string modifiedTxt = txt;
std::replace(modifiedTxt.begin(), modifiedTxt.end(), '-', '.');
static unsigned counter;
auto pos = neIdxMap.find(modifiedTxt);
if (pos == neIdxMap.end()) {
return neIdxMap[modifiedTxt] = counter++;
} else {
return neIdxMap[modifiedTxt];
}
}
/** Convert RAM identifier */
const std::string Synthesiser::convertRamIdent(const std::string& name) {
auto it = identifiers.find(name);
if (it != identifiers.end()) {
return it->second;
}
std::string id = uniqueCppIdent(name);
identifiers.insert(std::make_pair(name, id));
return id;
}
const std::string Synthesiser::convertStratumIdent(const std::string& name) {
return convertRamIdent(name);
}
/** Get relation name */
const std::string Synthesiser::getRelationName(const ram::Relation& rel) {
return "rel_" + convertRamIdent(rel.getName());
}
const std::string Synthesiser::getRelationName(const ram::Relation* rel) {
return "rel_" + convertRamIdent(rel->getName());
}
/** Get context name */
const std::string Synthesiser::getOpContextName(const ram::Relation& rel) {
return getRelationName(rel) + "_op_ctxt";
}
/** Get relation type struct */
void Synthesiser::generateRelationTypeStruct(GenDb& db, Own<Relation> relationType) {
std::string name = relationType->getTypeName();
// If this type has been generated already, use the cached version
if (typeCache.find(name) != typeCache.end()) {
return;
}
typeCache.insert(name);
// Generate the type struct for the relation
relationType->generateTypeStruct(db);
}
/** Get referenced relations */
ram::RelationSet Synthesiser::getReferencedRelations(const Operation& op) {
ram::RelationSet res;
visit(op, [&](const Node& node) {
if (auto scan = as<RelationOperation>(node)) {
res.insert(lookup(scan->getRelation()));
} else if (auto agg = as<Aggregate>(node)) {
res.insert(lookup(agg->getRelation()));
} else if (auto exists = as<ExistenceCheck>(node)) {
res.insert(lookup(exists->getRelation()));
} else if (auto provExists = as<ProvenanceExistenceCheck>(node)) {
res.insert(lookup(provExists->getRelation()));
} else if (auto insert = as<Insert>(node)) {
res.insert(lookup(insert->getRelation()));
}
});
return res;
}
std::optional<std::size_t> Synthesiser::compileRegex(const std::string& pattern) {
auto i = regexes.find(pattern);
if (i != regexes.end()) {
return i->second;
}
try {
const std::regex regex(pattern);
std::size_t index = regexes.size();
return regexes.emplace(pattern, index).first->second;
} catch (const std::exception&) {
std::cerr << "warning: wrong pattern provided \"" << pattern << "\"\n";
return std::nullopt;
}
}
void Synthesiser::emitCode(std::ostream& out, const Statement& stmt) {
class CodeEmitter : public ram::Visitor<void, Node const, std::ostream&> {
using ram::Visitor<void, Node const, std::ostream&>::visit_;
private:
Synthesiser& synthesiser;
Global& glb;
IndexAnalysis* const isa = &synthesiser.getTranslationUnit().getAnalysis<IndexAnalysis>();
// macros to add comments to generated code for debugging
#ifndef PRINT_BEGIN_COMMENT
#define PRINT_BEGIN_COMMENT(os) \
if (glb.config().has("debug-report") || glb.config().has("verbose")) \
os << "/* BEGIN " << __FUNCTION__ << " @" << __FILE__ << ":" << __LINE__ << " */\n"
#endif
#ifndef PRINT_END_COMMENT
#define PRINT_END_COMMENT(os) \
if (glb.config().has("debug-report") || glb.config().has("verbose")) \
os << "/* END " << __FUNCTION__ << " @" << __FILE__ << ":" << __LINE__ << " */\n"
#endif
// used to populate tuple literal init expressions
std::function<void(std::ostream&, const Expression*)> rec;
std::function<void(std::ostream&, const Expression*)> recWithDefault;
std::ostringstream preamble;
bool preambleIssued = false;
public:
CodeEmitter(Synthesiser& syn) : synthesiser(syn), glb(synthesiser.glb) {
rec = [&](auto& out, const auto* value) {
out << "ramBitCast(";
dispatch(*value, out);
out << ")";
};
recWithDefault = [&](auto& out, const auto* value) {
if (!isUndefValue(&*value)) {
rec(out, value);
} else {
out << "0";
}
};
}
std::pair<std::stringstream, std::stringstream> getPaddedRangeBounds(const ram::Relation& rel,
const std::vector<Expression*>& rangePatternLower,
const std::vector<Expression*>& rangePatternUpper) {
std::stringstream low;
std::stringstream high;
// making this distinction for provenance
std::size_t realArity = rel.getArity();
std::size_t arity = rangePatternLower.size();
low << "Tuple<RamDomain," << realArity << ">{{";
high << "Tuple<RamDomain," << realArity << ">{{";
for (std::size_t column = 0; column < arity; column++) {
std::string supremum;
std::string infimum;
switch (rel.getAttributeTypes()[column][0]) {
case 'f':
supremum = "ramBitCast<RamDomain>(MIN_RAM_FLOAT)";
infimum = "ramBitCast<RamDomain>(MAX_RAM_FLOAT)";
break;
case 'u':
supremum = "ramBitCast<RamDomain>(MIN_RAM_UNSIGNED)";
infimum = "ramBitCast<RamDomain>(MAX_RAM_UNSIGNED)";
break;
default:
supremum = "ramBitCast<RamDomain>(MIN_RAM_SIGNED)";
infimum = "ramBitCast<RamDomain>(MAX_RAM_SIGNED)";
}
// if we have an inequality where either side is not set
if (column != 0) {
low << ", ";
high << ", ";
}
if (isUndefValue(rangePatternLower[column])) {
low << supremum;
} else {
low << "ramBitCast(";
dispatch(*rangePatternLower[column], low);
low << ")";
}
if (isUndefValue(rangePatternUpper[column])) {
high << infimum;
} else {
high << "ramBitCast(";
dispatch(*rangePatternUpper[column], high);
high << ")";
}
}
low << "}}";
high << "}}";
return std::make_pair(std::move(low), std::move(high));
}
// -- relation statements --
void visit_(type_identity<IO>, const IO& io, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
synthesiser.currentClass->addInclude("\"souffle/io/IOSystem.h\"", true);
// print directives as C++ initializers
auto printDirectives = [&](const std::map<std::string, std::string>& registry) {
auto cur = registry.begin();
if (cur == registry.end()) {
return;
}
out << "{{\"" << cur->first << "\",\"" << escape(cur->second) << "\"}";
++cur;
for (; cur != registry.end(); ++cur) {
out << ",{\"" << cur->first << "\",\"" << escape(cur->second) << "\"}";
}
out << '}';
};
const auto& directives = io.getDirectives();
const std::string& op = io.get("operation");
out << "if (performIO) {\n";
// get some table details
if (op == "input") {
out << "try {";
out << "std::map<std::string, std::string> directiveMap(";
printDirectives(directives);
out << ");\n";
out << R"_(if (!inputDirectory.empty()) {)_";
out << R"_(directiveMap["fact-dir"] = inputDirectory;)_";
out << "}\n";
out << "IOSystem::getInstance().getReader(";
out << "directiveMap, symTable, recordTable";
out << ")->readAll(*" << synthesiser.getRelationName(synthesiser.lookup(io.getRelation()));
out << ");\n";
out << "} catch (std::exception& e) {std::cerr << \"Error loading " << io.getRelation()
<< " data: \" << e.what() "
"<< "
"'\\n';\nexit(1);\n}\n";
} else if (op == "output" || op == "printsize") {
out << "try {";
out << "std::map<std::string, std::string> directiveMap(";
printDirectives(directives);
out << ");\n";
out << R"_(if (outputDirectory == "-"){)_";
out << R"_(directiveMap["IO"] = "stdout"; directiveMap["headers"] = "true";)_";
out << "}\n";
out << R"_(else if (!outputDirectory.empty()) {)_";
out << R"_(directiveMap["output-dir"] = outputDirectory;)_";
out << "}\n";
out << "IOSystem::getInstance().getWriter(";
out << "directiveMap, symTable, recordTable";
out << ")->writeAll(*" << synthesiser.getRelationName(synthesiser.lookup(io.getRelation()))
<< ");\n";
out << "} catch (std::exception& e) {std::cerr << e.what();exit(1);}\n";
} else {
assert("Wrong i/o operation");
}
out << "}\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<Query>, const Query& query, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
// split terms of conditions of outer filter operation
// into terms that require a context and terms that
// do not require a context
const Operation* next = &query.getOperation();
VecOwn<Condition> requireCtx;
VecOwn<Condition> freeOfCtx;
if (const auto* filter = as<Filter>(query.getOperation())) {
next = &filter->getOperation();
// Check terms of outer filter operation whether they can be pushed before
// the context-generation for speed imrovements
auto conditions = toConjunctionList(&filter->getCondition());
for (auto const& cur : conditions) {
bool needContext = false;
visit(*cur, [&](const ExistenceCheck&) { needContext = true; });
visit(*cur, [&](const ProvenanceExistenceCheck&) { needContext = true; });
if (needContext) {
requireCtx.push_back(clone(cur));
} else {
freeOfCtx.push_back(clone(cur));
}
}
// discharge conditions that do not require a context
if (freeOfCtx.size() > 0) {
out << "if(";
dispatch(*toCondition(freeOfCtx), out);
out << ") {\n";
}
}
// outline each search operation to improve compilation time
out << "[&]()";
// enclose operation in its own scope
out << "{\n";
// check whether loop nest can be parallelized
bool isParallel = visitExists(
*next, [&](const Node& n) { return as<AbstractParallel, AllowCrossCast>(n); });
// reset preamble
preamble.str("");
preamble.clear();
preambleIssued = false;
// create operation contexts for this operation
for (const ram::Relation* rel : synthesiser.getReferencedRelations(query.getOperation())) {
preamble << "CREATE_OP_CONTEXT(" << synthesiser.getOpContextName(*rel);
preamble << "," << synthesiser.getRelationName(*rel);
preamble << "->createContext());\n";
}
// discharge conditions that require a context
if (isParallel) {
if (requireCtx.size() > 0) {
preamble << "if(";
dispatch(*toCondition(requireCtx), preamble);
preamble << ") {\n";
dispatch(*next, out);
out << "}\n";
} else {
dispatch(*next, out);
}
} else {
out << preamble.str();
if (requireCtx.size() > 0) {
out << "if(";
dispatch(*toCondition(requireCtx), out);
out << ") {\n";
dispatch(*next, out);
out << "}\n";
} else {
dispatch(*next, out);
}
}
if (isParallel) {
out << "PARALLEL_END\n"; // end parallel
}
out << "}\n";
out << "();"; // call lambda
if (freeOfCtx.size() > 0) {
out << "}\n";
}
PRINT_END_COMMENT(out);
}
void visit_(type_identity<Clear>, const Clear& clear, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
auto Relation = synthesiser.lookup(clear.getRelation());
bool isIntermediate =
!contains(synthesiser.storeRelations, Relation->getName()) && !Relation->isTemp();
if (isIntermediate) {
out << "if (pruneImdtRels) ";
}
if (Relation->isTemp() || isIntermediate) {
out << synthesiser.getRelationName(Relation) << "->purge();\n";
}
PRINT_END_COMMENT(out);
}
void visit_(type_identity<LogSize>, const LogSize& size, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
out << "ProfileEventSingleton::instance().makeQuantityEvent( R\"(";
out << size.getMessage() << ")\",";
out << synthesiser.getRelationName(synthesiser.lookup(size.getRelation())) << "->size(),iter);";
PRINT_END_COMMENT(out);
}
// -- control flow statements --
void visit_(type_identity<Sequence>, const Sequence& seq, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
for (const auto& cur : seq.getStatements()) {
dispatch(*cur, out);
}
PRINT_END_COMMENT(out);
}
void visit_(type_identity<Parallel>, const Parallel& parallel, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
auto stmts = parallel.getStatements();
// special handling cases
if (stmts.empty()) {
PRINT_END_COMMENT(out);
return;
}
// a single statement => save the overhead
if (stmts.size() == 1) {
dispatch(*stmts[0], out);
PRINT_END_COMMENT(out);
return;
}
// more than one => parallel sections
// start parallel section
out << "SECTIONS_START;\n";
// put each thread in another section
for (const auto& cur : stmts) {
out << "SECTION_START;\n";
dispatch(*cur, out);
out << "SECTION_END\n";
}
// done
out << "SECTIONS_END;\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<Loop>, const Loop& loop, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
out << "iter = 0;\n";
out << "for(;;) {\n";
dispatch(loop.getBody(), out);
out << "iter++;\n";
out << "}\n";
out << "iter = 0;\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<Assign>, const Assign& assign, std::ostream& out) override {
if (assign.isInit()) {
out << "auto ";
}
dispatch(assign.getVariable(), out);
out << " = ";
dispatch(assign.getValue(), out);
assign.getValue();
out << ";\n";
}
void visit_(type_identity<Swap>, const Swap& swap, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
const std::string& deltaKnowledge =
synthesiser.getRelationName(synthesiser.lookup(swap.getFirstRelation()));
const std::string& newKnowledge =
synthesiser.getRelationName(synthesiser.lookup(swap.getSecondRelation()));
out << "std::swap(" << deltaKnowledge << ", " << newKnowledge << ");\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<MergeExtend>, const MergeExtend& extend, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
out << synthesiser.getRelationName(synthesiser.lookup(extend.getSourceRelation())) << "->"
<< "extendAndInsert("
<< "*" << synthesiser.getRelationName(synthesiser.lookup(extend.getTargetRelation()))
<< ");\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<Exit>, const Exit& exit, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
out << "if(";
dispatch(exit.getCondition(), out);
out << ") break;\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<Call>, const Call& call, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
out << "{\n";
out << " std::vector<RamDomain> args, ret;\n";
out << synthesiser.convertStratumIdent(call.getName()) << ".run(args, ret);\n";
out << "}\n";
PRINT_END_COMMENT(out);
}
void visit_(
type_identity<LogRelationTimer>, const LogRelationTimer& timer, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
// create local scope for name resolution
out << "{\n";
const std::string ext = fileExtension(glb.config().get("profile"));
const auto* rel = synthesiser.lookup(timer.getRelation());
auto relName = synthesiser.getRelationName(rel);
out << "\tLogger logger(R\"_(" << timer.getMessage() << ")_\",iter, [&](){return " << relName
<< "->size();});\n";
// insert statement to be measured
dispatch(timer.getStatement(), out);
// done
out << "}\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<LogTimer>, const LogTimer& timer, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
// create local scope for name resolution
out << "{\n";
const std::string ext = fileExtension(glb.config().get("profile"));
// create local timer
out << "\tLogger logger(R\"_(" << timer.getMessage() << ")_\",iter);\n";
// insert statement to be measured
dispatch(timer.getStatement(), out);
// done
out << "}\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<DebugInfo>, const DebugInfo& dbg, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
out << "signalHandler->setMsg(R\"_(";
out << dbg.getMessage();
out << ")_\");\n";
// insert statements of the rule
dispatch(dbg.getStatement(), out);
PRINT_END_COMMENT(out);
}
// -- operations --
void visit_(
type_identity<NestedOperation>, const NestedOperation& nested, std::ostream& out) override {
dispatch(nested.getOperation(), out);
if (glb.config().has("profile") && glb.config().has("profile-frequency") &&
!nested.getProfileText().empty()) {
out << "freqs[" << synthesiser.lookupFreqIdx(nested.getProfileText()) << "]++;\n";
}
}
void visit_(type_identity<TupleOperation>, const TupleOperation& search, std::ostream& out) override {
PRINT_BEGIN_COMMENT(out);
visit_(type_identity<NestedOperation>(), search, out);
PRINT_END_COMMENT(out);
}
void visit_(type_identity<ParallelScan>, const ParallelScan& pscan, std::ostream& out) override {
const auto* rel = synthesiser.lookup(pscan.getRelation());
const auto& relName = synthesiser.getRelationName(rel);
assert(pscan.getTupleId() == 0 && "not outer-most loop");
assert(rel->getArity() > 0 && "AstToRamTranslator failed/no parallel scans for nullaries");
assert(!preambleIssued && "only first loop can be made parallel");
preambleIssued = true;
PRINT_BEGIN_COMMENT(out);
out << "auto part = " << relName << "->partition();\n";
out << "PARALLEL_START\n";
out << preamble.str();
out << R"cpp(
#if defined _OPENMP && _OPENMP < 200805
auto count = std::distance(part.begin(), part.end());
auto base = part.begin();
pfor(int index = 0; index < count; index++) {
auto it = base + index;
#else
pfor(auto it = part.begin(); it < part.end(); it++) {
#endif
)cpp";
out << "try{\n";
out << "for(const auto& env0 : *it) {\n";
visit_(type_identity<TupleOperation>(), pscan, out);
out << "}\n";
out << "} catch(std::exception &e) { signalHandler->error(e.what());}\n";
out << "}\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<Scan>, const Scan& scan, std::ostream& out) override {
const auto* rel = synthesiser.lookup(scan.getRelation());
auto relName = synthesiser.getRelationName(rel);
auto id = scan.getTupleId();
PRINT_BEGIN_COMMENT(out);
assert(rel->getArity() > 0 && "AstToRamTranslator failed/no scans for nullaries");
out << "for(const auto& env" << id << " : "
<< "*" << relName << ") {\n";
visit_(type_identity<TupleOperation>(), scan, out);
out << "}\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<IfExists>, const IfExists& ifexists, std::ostream& out) override {
const auto* rel = synthesiser.lookup(ifexists.getRelation());
auto relName = synthesiser.getRelationName(rel);
auto identifier = ifexists.getTupleId();
assert(rel->getArity() > 0 && "AstToRamTranslator failed/no ifexists for nullaries");
PRINT_BEGIN_COMMENT(out);
out << "for(const auto& env" << identifier << " : "
<< "*" << relName << ") {\n";
out << "if( ";
dispatch(ifexists.getCondition(), out);
out << ") {\n";
visit_(type_identity<TupleOperation>(), ifexists, out);
out << "break;\n";
out << "}\n";
out << "}\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<ParallelIfExists>, const ParallelIfExists& pifexists,
std::ostream& out) override {
const auto* rel = synthesiser.lookup(pifexists.getRelation());
auto relName = synthesiser.getRelationName(rel);
assert(pifexists.getTupleId() == 0 && "not outer-most loop");
assert(rel->getArity() > 0 && "AstToRamTranslator failed/no parallel ifexists for nullaries");
assert(!preambleIssued && "only first loop can be made parallel");
preambleIssued = true;
PRINT_BEGIN_COMMENT(out);
out << "auto part = " << relName << "->partition();\n";
out << "PARALLEL_START\n";
out << preamble.str();
out << R"cpp(
#if defined _OPENMP && _OPENMP < 200805
auto count = std::distance(part.begin(), part.end());
auto base = part.begin();
pfor(int index = 0; index < count; index++) {
auto it = base + index;
#else
pfor(auto it = part.begin(); it < part.end(); it++) {
#endif
)cpp";
out << "try{\n";
out << "for(const auto& env0 : *it) {\n";
out << "if( ";
dispatch(pifexists.getCondition(), out);
out << ") {\n";
visit_(type_identity<TupleOperation>(), pifexists, out);
out << "break;\n";
out << "}\n";
out << "}\n";
out << "} catch(std::exception &e) { signalHandler->error(e.what());}\n";
out << "}\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<IndexScan>, const IndexScan& iscan, std::ostream& out) override {
const auto* rel = synthesiser.lookup(iscan.getRelation());
auto relName = synthesiser.getRelationName(rel);
auto identifier = iscan.getTupleId();
auto keys = isa->getSearchSignature(&iscan);
const auto& rangePatternLower = iscan.getRangePattern().first;
const auto& rangePatternUpper = iscan.getRangePattern().second;
assert(0 < rel->getArity() && "AstToRamTranslator failed/no index scans for nullaries");
PRINT_BEGIN_COMMENT(out);
auto ctxName = "READ_OP_CONTEXT(" + synthesiser.getOpContextName(*rel) + ")";
auto rangeBounds = getPaddedRangeBounds(*rel, rangePatternLower, rangePatternUpper);
out << "auto range = " << relName << "->"
<< "lowerUpperRange_" << keys << "(" << rangeBounds.first.str() << ","
<< rangeBounds.second.str() << "," << ctxName << ");\n";
out << "for(const auto& env" << identifier << " : range) {\n";
visit_(type_identity<TupleOperation>(), iscan, out);
out << "}\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<EstimateJoinSize>, const EstimateJoinSize& estimateJoinSize,
std::ostream& out) override {
const auto* rel = synthesiser.lookup(estimateJoinSize.getRelation());
auto relName = synthesiser.getRelationName(rel);
auto keys = isa->getSearchSignature(&estimateJoinSize);
std::size_t indexNumber = 0;
if (!keys.empty()) {
indexNumber = isa->getIndexSelection(estimateJoinSize.getRelation()).getLexOrderNum(keys);
}
auto relationType =
Relation::getSynthesiserRelation(*rel, isa->getIndexSelection(rel->getName()));
const std::string& type = relationType->getTypeName();
auto indexName = relName + (type == "t_eqrel" ? "->ind" : "->ind_" + std::to_string(indexNumber));
bool onlyConstants = true;
for (auto col : estimateJoinSize.getKeyColumns()) {
if (estimateJoinSize.getConstantsMap().count(col) == 0) {
onlyConstants = false;
break;
}
}
// create a copy of the map to the real numeric constants
std::map<std::size_t, RamDomain> keyConstants;
for (auto [k, constant] : estimateJoinSize.getConstantsMap()) {
RamDomain value;
if (const auto* signedConstant = as<ram::SignedConstant>(constant)) {
value = ramBitCast<RamDomain>(signedConstant->getValue());
} else if (const auto* stringConstant = as<ram::StringConstant>(constant)) {
value = ramBitCast<RamDomain>(
synthesiser.convertSymbol2Idx(stringConstant->getConstant()));
} else if (const auto* unsignedConstant = as<ram::UnsignedConstant>(constant)) {
value = ramBitCast<RamDomain>(unsignedConstant->getValue());
} else if (const auto* floatConstant = as<ram::FloatConstant>(constant)) {
value = ramBitCast<RamDomain>(floatConstant->getValue());
} else {
fatal("Something went wrong. Should have gotten a constant!");
}
keyConstants[k] = value;
}
std::stringstream columnsStream;
columnsStream << estimateJoinSize.getKeyColumns();
std::string columns = columnsStream.str();
std::stringstream constantsStream;
constantsStream << "{";
bool first = true;
for (auto& [k, constant] : estimateJoinSize.getConstantsMap()) {
if (first) {
first = false;
} else {
constantsStream << ",";
}
constantsStream << k << "->" << *constant;
}
constantsStream << "}";
std::string constants = stringify(constantsStream.str());
std::string profilerText =
(estimateJoinSize.isRecursiveRelation() ? stringify("@recursive-estimate-join-size;" +
estimateJoinSize.getRelation() + ";" +
columns + ";" + constants)
: stringify("@non-recursive-estimate-join-size;" +
estimateJoinSize.getRelation() + ";" +
columns + ";" + constants));
PRINT_BEGIN_COMMENT(out);
auto ctxName = "READ_OP_CONTEXT(" + synthesiser.getOpContextName(*rel) + ")";
out << "{\n";
out << "double total = 0;\n";
out << "double duplicates = 0;\n";
out << "if (!" << indexName << ".empty()) {\n";
out << "bool first = true;\n";
out << "auto prev = *" << indexName << ".begin();\n";
out << "for(const auto& tup : " << indexName << ") {\n";
out << " bool matchesConstants = true;\n";
for (auto& [k, constant] : keyConstants) {
if (rel->getArity() > 6) {
out << "matchesConstants &= (tup[0][" << k << "] == " << constant << ");\n";
} else {
out << "matchesConstants &= (tup[" << k << "] == " << constant << ");\n";
}
}
out << "if (!matchesConstants) {\n";
out << " continue;\n";
out << "}\n";
out << "if (first) { first = false; }\n";
out << "else {\n";
out << " bool matchesPrev = true;\n";
for (auto k : estimateJoinSize.getKeyColumns()) {
if (rel->getArity() > 6) {
out << "matchesPrev &= (tup[0][" << k << "] == prev[0][" << k << "]);\n";
} else {
out << "matchesPrev &= (tup[" << k << "] == prev[" << k << "]);\n";
}
}
out << "if (matchesPrev) { ++duplicates; }\n";
out << "}\n";
out << "prev = tup; ++total;\n";
out << "\n";
out << "}\n";
out << "}\n";
out << "double joinSize = ("
<< (onlyConstants ? "total" : "total / std::max(1.0, (total - duplicates))") << ");\n";
if (estimateJoinSize.isRecursiveRelation()) {
out << "ProfileEventSingleton::instance().makeRecursiveCountEvent(\"" << profilerText
<< "\", joinSize, iter);\n";
} else {
out << "ProfileEventSingleton::instance().makeNonRecursiveCountEvent(\"" << profilerText
<< "\", joinSize);\n";
}
out << "}\n";
PRINT_END_COMMENT(out);
}
void visit_(type_identity<ParallelIndexScan>, const ParallelIndexScan& piscan,
std::ostream& out) override {
const auto* rel = synthesiser.lookup(piscan.getRelation());
auto relName = synthesiser.getRelationName(rel);
auto keys = isa->getSearchSignature(&piscan);
const auto& rangePatternLower = piscan.getRangePattern().first;
const auto& rangePatternUpper = piscan.getRangePattern().second;
assert(piscan.getTupleId() == 0 && "not outer-most loop");
assert(0 < rel->getArity() && "AstToRamTranslator failed/no parallel index scan for nullaries");
assert(!preambleIssued && "only first loop can be made parallel");
preambleIssued = true;
PRINT_BEGIN_COMMENT(out);
auto rangeBounds = getPaddedRangeBounds(*rel, rangePatternLower, rangePatternUpper);
out << "auto range = " << relName
<< "->"
// TODO (b-scholz): context may be missing here?
<< "lowerUpperRange_" << keys << "(" << rangeBounds.first.str() << ","
<< rangeBounds.second.str() << ");\n";
out << "auto part = range.partition();\n";
out << "PARALLEL_START\n";
out << preamble.str();
out << R"cpp(
#if defined _OPENMP && _OPENMP < 200805
auto count = std::distance(part.begin(), part.end());
auto base = part.begin();
pfor(int index = 0; index < count; index++) {
auto it = base + index;
#else
pfor(auto it = part.begin(); it < part.end(); it++) {
#endif
)cpp";
out << "try{\n";
out << "for(const auto& env0 : *it) {\n";
visit_(type_identity<TupleOperation>(), piscan, out);
out << "}\n";
out << "} catch(std::exception &e) { signalHandler->error(e.what());}\n";
out << "}\n";