-
Notifications
You must be signed in to change notification settings - Fork 195
/
RamTranslator.cpp
1353 lines (1144 loc) · 55.1 KB
/
RamTranslator.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 RamTranslator.cpp
*
* Implementations of a translator from AST to RAM structures.
*
***********************************************************************/
#include "RamTranslator.h"
#include "AstClause.h"
#include "AstIODirective.h"
#include "AstProgram.h"
#include "AstRelation.h"
#include "AstTypeAnalysis.h"
#include "AstUtils.h"
#include "AstVisitor.h"
#include "BinaryConstraintOps.h"
#include "Global.h"
#include "PrecedenceGraph.h"
#include "RamStatement.h"
#include "RamVisitor.h"
namespace souffle {
namespace {
SymbolMask getSymbolMask(const AstRelation& rel, const TypeEnvironment& typeEnv) {
auto arity = rel.getArity();
SymbolMask res(arity);
for (size_t i = 0; i < arity; i++) {
res.setSymbol(i, isSymbolType(typeEnv.getType(rel.getAttribute(i)->getTypeName())));
}
return res;
}
/**
* Converts the given relation identifier into a relation name.
*/
std::string getRelationName(const AstRelationIdentifier& id) {
return toString(join(id.getNames(), "-"));
}
RamRelationIdentifier getRamRelationIdentifier(const AstRelation* rel, const TypeEnvironment* typeEnv,
std::string name, size_t arity, const bool istemp = false, std::string filePath = std::string(),
std::string fileExt = std::string()) {
// avoid name conflicts for temporary identifiers
if (istemp) {
name.insert(0, "@");
}
if (!rel) {
return RamRelationIdentifier(name, arity, istemp);
}
assert(arity == rel->getArity());
std::vector<std::string> attributeNames;
std::vector<std::string> attributeTypeQualifiers;
for (unsigned int i = 0; i < arity; i++) {
attributeNames.push_back(rel->getAttribute(i)->getAttributeName());
if (typeEnv) {
attributeTypeQualifiers.push_back(
getTypeQualifier(typeEnv->getType(rel->getAttribute(i)->getTypeName())));
}
}
IODirectives directives;
std::vector<IODirectives> outputDirectives;
// If IO directives have been specified then set them up
for (const auto& current : rel->getIODirectives()) {
if (current->isInput()) {
for (const auto& currentPair : current->getIODirectiveMap()) {
directives.set(currentPair.first, currentPair.second);
}
} else if (current->isOutput()) {
IODirectives ioDirectives;
for (const auto& currentPair : current->getIODirectiveMap()) {
ioDirectives.set(currentPair.first, currentPair.second);
}
outputDirectives.push_back(ioDirectives);
}
}
// handle defaults
if (rel->isInput()) {
const std::string inputFilePath = (filePath.empty()) ? Global::config().get("fact-dir") : filePath;
const std::string inputFileExt = (fileExt.empty()) ? ".facts" : fileExt;
directives.setRelationName(getRelationName(rel->getName()));
// Set a default IO type of file and a default filename if not supplied.
if (!directives.has("IO")) {
directives.setIOType("file");
}
// load intermediate relations from correct files
if (directives.getIOType() == "file" &&
(!directives.has("filename") || directives.has("intermediate"))) {
directives.setFileName(directives.getRelationName() + inputFileExt);
}
// all intermediate relations are given the default delimiter
if (directives.has("intermediate")) directives.set("delimiter", "\t");
// if filename is not an absolute path, concat with cmd line facts directory
if (directives.getIOType() == "file" && directives.getFileName().front() != '/') {
directives.setFileName(inputFilePath + "/" + directives.getFileName());
}
}
if (rel->isOutput()) {
const std::string outputFilePath = (filePath.empty()) ? Global::config().get("output-dir") : filePath;
const std::string outputFileExt = (fileExt.empty()) ? ".csv" : fileExt;
if (Global::config().get("output-dir") == "-") {
outputDirectives.clear();
IODirectives ioDirectives;
ioDirectives.setIOType("stdout");
outputDirectives.push_back(ioDirectives);
} else if (outputDirectives.empty()) {
IODirectives ioDirectives;
ioDirectives.setIOType("file");
ioDirectives.setFileName(getRelationName(rel->getName()) + outputFileExt);
outputDirectives.push_back(ioDirectives);
}
// If stdout is requested then remove all directives from the datalog file.
for (auto& ioDirectives : outputDirectives) {
ioDirectives.setRelationName(getRelationName(rel->getName()));
if (!ioDirectives.has("IO")) {
ioDirectives.setIOType("file");
}
if (ioDirectives.getIOType() == "file" && !ioDirectives.has("filename")) {
ioDirectives.setFileName(ioDirectives.getRelationName() + outputFileExt);
}
if (ioDirectives.getIOType() == "file" && ioDirectives.getFileName().front() != '/') {
ioDirectives.setFileName(outputFilePath + "/" + ioDirectives.get("filename"));
}
}
}
return RamRelationIdentifier(name, arity, attributeNames, attributeTypeQualifiers,
getSymbolMask(*rel, *typeEnv), rel->isInput(), rel->isComputed(), rel->isOutput(), rel->isBTree(),
rel->isBrie(), rel->isEqRel(), rel->isData(), directives, outputDirectives, istemp);
}
RamRelationIdentifier getRamRelationIdentifier(const AstRelation* rel, const TypeEnvironment* typeEnv) {
return getRamRelationIdentifier(rel, typeEnv, getRelationName(rel->getName()), rel->getArity());
}
} // namespace
std::string RamTranslator::translateRelationName(const AstRelationIdentifier& id) {
return getRelationName(id);
}
namespace {
/**
* The location of some value in a loop nest.
*/
struct Location {
int level; // < the loop level
int component; // < the component within the tuple created in the given level
std::string name; // < name of the variable
bool operator==(const Location& loc) const {
return level == loc.level && component == loc.component;
}
bool operator!=(const Location& loc) const {
return !(*this == loc);
}
bool operator<(const Location& loc) const {
return level < loc.level || (level == loc.level && component < loc.component);
}
void print(std::ostream& out) const {
out << "(" << level << "," << component << ")";
}
friend std::ostream& operator<<(std::ostream& out, const Location& loc) {
loc.print(out);
return out;
}
};
/**
* A class indexing the location of variables and record
* references within a loop nest resulting from the conversion
* of a rule.
*/
class ValueIndex {
/**
* The type mapping variables (referenced by their names) to the
* locations where they are used.
*/
typedef std::map<std::string, std::set<Location>> variable_reference_map;
/**
* The type mapping record init expressions to their definition points,
* hence the point where they get grounded/bound.
*/
typedef std::map<const AstRecordInit*, Location> record_definition_map;
/**
* The type mapping record init expressions to the loop level where
* they get unpacked.
*/
typedef std::map<const AstRecordInit*, int> record_unpack_map;
/**
* A map from AstAggregators to storage locations. Note, since in this case
* AstAggregators are indexed by their values (not their address) no standard
* map can be utilized.
*/
typedef std::vector<std::pair<const AstAggregator*, Location>> aggregator_location_map;
/** The index of variable accesses */
variable_reference_map var_references;
/** The index of record definition points */
record_definition_map record_definitions;
/** The index of record-unpack levels */
record_unpack_map record_unpacks;
/** The level of a nested ram operation that is handling a given aggregator operation */
aggregator_location_map aggregator_locations;
public:
// -- variables --
void addVarReference(const AstVariable& var, const Location& l) {
std::set<Location>& locs = var_references[var.getName()];
locs.insert(l);
}
void addVarReference(const AstVariable& var, int level, int pos, const std::string& name = "") {
addVarReference(var, Location({level, pos, name}));
}
bool isDefined(const AstVariable& var) const {
return var_references.find(var.getName()) != var_references.end();
}
const Location& getDefinitionPoint(const AstVariable& var) const {
auto pos = var_references.find(var.getName());
assert(pos != var_references.end() && "Undefined variable referenced!");
return *pos->second.begin();
}
const variable_reference_map& getVariableReferences() const {
return var_references;
}
// -- records --
// - definition -
void setRecordDefinition(const AstRecordInit& init, const Location& l) {
record_definitions[&init] = l;
}
void setRecordDefinition(const AstRecordInit& init, int level, int pos, std::string name = "") {
setRecordDefinition(init, Location({level, pos, name}));
}
const Location& getDefinitionPoint(const AstRecordInit& init) const {
auto pos = record_definitions.find(&init);
if (pos != record_definitions.end()) {
return pos->second;
}
assert(false && "Requested location for undefined record!");
static Location fail;
return fail;
}
// - unpacking -
void setRecordUnpackLevel(const AstRecordInit& init, int level) {
record_unpacks[&init] = level;
}
int getRecordUnpackLevel(const AstRecordInit& init) const {
auto pos = record_unpacks.find(&init);
if (pos != record_unpacks.end()) {
return pos->second;
}
assert(false && "Requested record is not unpacked properly!");
return 0;
}
// -- aggregates --
void setAggregatorLocation(const AstAggregator& agg, const Location& loc) {
aggregator_locations.push_back(std::make_pair(&agg, loc));
}
const Location& getAggregatorLocation(const AstAggregator& agg) const {
// search list
for (const auto& cur : aggregator_locations) {
if (*cur.first == agg) {
return cur.second;
}
}
// fail
std::cout << "Lookup of " << &agg << " = " << agg << " failed\n";
assert(false && "Requested aggregation operation is not processed!");
const static Location fail = Location();
return fail;
}
// -- others --
bool isSomethingDefinedOn(int level) const {
// check for variable definitions
for (const auto& cur : var_references) {
if (cur.second.begin()->level == level) {
return true;
}
}
// check for record definitions
for (const auto& cur : record_definitions) {
if (cur.second.level == level) {
return true;
}
}
// nothing defined on this level
return false;
}
void print(std::ostream& out) const {
out << "Variables:\n\t";
out << join(var_references, "\n\t");
}
friend std::ostream& operator<<(std::ostream& out, const ValueIndex& index) __attribute__((unused)) {
index.print(out);
return out;
}
};
std::unique_ptr<RamValue> translateValue(const AstArgument* arg, const ValueIndex& index = ValueIndex()) {
std::unique_ptr<RamValue> val;
if (!arg) {
return val;
}
if (const AstVariable* var = dynamic_cast<const AstVariable*>(arg)) {
ASSERT(index.isDefined(*var) && "variable not grounded");
const Location& loc = index.getDefinitionPoint(*var);
val = std::unique_ptr<RamValue>(new RamElementAccess(loc.level, loc.component, loc.name));
} else if (dynamic_cast<const AstUnnamedVariable*>(arg)) {
return nullptr; // utilized to identify _ values
} else if (const AstConstant* c = dynamic_cast<const AstConstant*>(arg)) {
val = std::unique_ptr<RamValue>(new RamNumber(c->getIndex()));
} else if (const AstUnaryFunctor* uf = dynamic_cast<const AstUnaryFunctor*>(arg)) {
val = std::unique_ptr<RamValue>(
new RamUnaryOperator(uf->getFunction(), translateValue(uf->getOperand(), index)));
} else if (const AstBinaryFunctor* bf = dynamic_cast<const AstBinaryFunctor*>(arg)) {
val = std::unique_ptr<RamValue>(new RamBinaryOperator(
bf->getFunction(), translateValue(bf->getLHS(), index), translateValue(bf->getRHS(), index)));
} else if (const AstTernaryFunctor* tf = dynamic_cast<const AstTernaryFunctor*>(arg)) {
val = std::unique_ptr<RamValue>(
new RamTernaryOperator(tf->getFunction(), translateValue(tf->getArg(0), index),
translateValue(tf->getArg(1), index), translateValue(tf->getArg(2), index)));
} else if (dynamic_cast<const AstCounter*>(arg)) {
val = std::unique_ptr<RamValue>(new RamAutoIncrement());
} else if (const AstRecordInit* init = dynamic_cast<const AstRecordInit*>(arg)) {
std::vector<std::unique_ptr<RamValue>> values;
for (const auto& cur : init->getArguments()) {
values.push_back(translateValue(cur, index));
}
val = std::unique_ptr<RamValue>(new RamPack(std::move(values)));
} else if (const AstAggregator* agg = dynamic_cast<const AstAggregator*>(arg)) {
// here we look up the location the aggregation result gets bound
auto loc = index.getAggregatorLocation(*agg);
val = std::unique_ptr<RamValue>(new RamElementAccess(loc.level, loc.component, loc.name));
} else if (const AstSubroutineArgument* subArg = dynamic_cast<const AstSubroutineArgument*>(arg)) {
val = std::unique_ptr<RamValue>(new RamArgument(subArg->getNumber()));
} else {
std::cout << "Unsupported node type of " << arg << ": " << typeid(*arg).name() << "\n";
ASSERT(false && "unknown AST node type not permissible");
}
return val;
}
std::unique_ptr<RamValue> translateValue(const AstArgument& arg, const ValueIndex& index = ValueIndex()) {
return translateValue(&arg, index);
}
} // namespace
/** generate RAM code for a clause */
std::unique_ptr<RamStatement> RamTranslator::translateClause(const AstClause& clause,
const AstProgram* program, const TypeEnvironment* typeEnv, int version, bool ret) {
// check whether there is an imposed order constraint
if (clause.getExecutionPlan() && clause.getExecutionPlan()->hasOrderFor(version)) {
// get the imposed order
const AstExecutionOrder& order = clause.getExecutionPlan()->getOrderFor(version);
// create a copy and fix order
std::unique_ptr<AstClause> copy(clause.clone());
// Change order to start at zero
std::vector<unsigned int> newOrder(order.size());
std::transform(order.begin(), order.end(), newOrder.begin(),
[](unsigned int i) -> unsigned int { return i - 1; });
// re-order atoms
copy->reorderAtoms(newOrder);
// clear other order and fix plan
copy->clearExecutionPlan();
copy->setFixedExecutionPlan();
// translate reordered clause
return translateClause(*copy, program, typeEnv, version);
}
// get extract some details
const AstAtom& head = *clause.getHead();
// a utility to translate atoms to relations
auto getRelation = [&](const AstAtom* atom) {
return getRamRelationIdentifier((program ? getAtomRelation(atom, program) : nullptr), typeEnv,
getRelationName(atom->getName()), atom->getArity());
};
// handle facts
if (clause.isFact()) {
// translate arguments
std::vector<std::unique_ptr<const RamValue>> values;
for (auto& arg : clause.getHead()->getArguments()) {
values.push_back(translateValue(*arg));
}
// create a fact statement
return std::make_unique<RamFact>(getRelation(&head), std::move(values));
}
// the rest should be rules
assert(clause.isRule());
// -- index values in rule --
// create value index
ValueIndex valueIndex;
// the order of processed operations
std::vector<const AstNode*> op_nesting;
int level = 0;
for (AstAtom* atom : clause.getAtoms()) {
// index nested variables and records
typedef std::vector<AstArgument*> arg_list;
// std::map<const arg_list*, int> arg_level;
std::map<const AstNode*, std::unique_ptr<arg_list>> nodeArgs;
std::function<arg_list*(const AstNode*)> getArgList = [&](const AstNode* curNode) {
if (!nodeArgs.count(curNode)) {
if (auto rec = dynamic_cast<const AstRecordInit*>(curNode)) {
nodeArgs.insert(std::make_pair(
curNode, std::unique_ptr<arg_list>(new arg_list(rec->getArguments()))));
} else if (auto atom = dynamic_cast<const AstAtom*>(curNode)) {
nodeArgs.insert(std::make_pair(
curNode, std::unique_ptr<arg_list>(new arg_list(atom->getArguments()))));
} else {
assert(false && "node type doesn't have arguments!");
}
}
arg_list* cur = nodeArgs[curNode].get();
return cur;
};
std::map<const arg_list*, int> arg_level;
nodeArgs.insert(std::make_pair(atom, std::unique_ptr<arg_list>(new arg_list(atom->getArguments()))));
// the atom is obtained at the current level
arg_level[nodeArgs[atom].get()] = level;
op_nesting.push_back(atom);
// increment nesting level for the atom
level++;
// relation
RamRelationIdentifier relation = getRelation(atom);
std::function<void(const AstNode*)> indexValues = [&](const AstNode* curNode) {
arg_list* cur = getArgList(curNode);
for (size_t pos = 0; pos < cur->size(); pos++) {
// get argument
auto& arg = (*cur)[pos];
// check for variable references
if (auto var = dynamic_cast<const AstVariable*>(arg)) {
if (pos < relation.getArity()) {
valueIndex.addVarReference(*var, arg_level[cur], pos, relation.getArg(pos));
} else {
valueIndex.addVarReference(*var, arg_level[cur], pos);
}
}
// check for nested records
if (auto rec = dynamic_cast<const AstRecordInit*>(arg)) {
// introduce new nesting level for unpack
int unpack_level = level++;
op_nesting.push_back(rec);
arg_level[getArgList(rec)] = unpack_level;
valueIndex.setRecordUnpackLevel(*rec, unpack_level);
// register location of record
valueIndex.setRecordDefinition(*rec, arg_level[cur], pos);
// resolve nested components
indexValues(rec);
}
}
};
indexValues(atom);
}
// add aggregation functions
std::vector<const AstAggregator*> aggregators;
visitDepthFirstPostOrder(clause, [&](const AstAggregator& cur) {
// add each aggregator expression only once
if (any_of(aggregators, [&](const AstAggregator* agg) { return *agg == cur; })) {
return;
}
int aggLoc = level++;
valueIndex.setAggregatorLocation(cur, Location({aggLoc, 0}));
// bind aggregator variables to locations
assert(dynamic_cast<const AstAtom*>(cur.getBodyLiterals()[0]));
const AstAtom& atom = static_cast<const AstAtom&>(*cur.getBodyLiterals()[0]);
for (size_t pos = 0; pos < atom.getArguments().size(); ++pos) {
if (const AstVariable* var = dynamic_cast<const AstVariable*>(atom.getArgument(pos))) {
valueIndex.addVarReference(*var, aggLoc, (int)pos, getRelation(&atom).getArg(pos));
}
};
// and remember aggregator
aggregators.push_back(&cur);
});
// -- create RAM statement --
// begin with projection
std::unique_ptr<RamOperation> op;
if (ret) {
RamReturn* returnValue = new RamReturn(level);
// get all values in the body
for (AstLiteral* lit : clause.getBodyLiterals()) {
if (auto atom = dynamic_cast<AstAtom*>(lit)) {
for (AstArgument* arg : atom->getArguments()) {
returnValue->addValue(translateValue(arg, valueIndex));
}
} else if (auto neg = dynamic_cast<AstNegation*>(lit)) {
for (size_t i = 0; i < neg->getAtom()->getArguments().size() - 2; i++) {
auto arg = neg->getAtom()->getArguments()[i];
returnValue->addValue(translateValue(arg, valueIndex));
}
returnValue->addValue(std::unique_ptr<RamValue>(new RamNumber(-1)));
returnValue->addValue(std::unique_ptr<RamValue>(new RamNumber(-1)));
}
}
op = std::unique_ptr<RamOperation>(returnValue);
} else {
RamProject* project = new RamProject(getRelation(&head), level);
for (AstArgument* arg : head.getArguments()) {
project->addArg(translateValue(arg, valueIndex));
}
// check existence for original tuple if we have provenance
if (Global::config().has("provenance")) {
auto uniquenessEnforcement = new RamNotExists(getRelation(&head));
auto arity = head.getArity() - 2;
bool add = true;
// add args for original tuple
for (size_t i = 0; i < arity; i++) {
auto arg = head.getArgument(i);
// don't add counters
if (dynamic_cast<AstCounter*>(arg)) {
add = false;
break;
}
uniquenessEnforcement->addArg(translateValue(arg, valueIndex));
}
// add two unnamed args for provenance columns
uniquenessEnforcement->addArg(nullptr);
uniquenessEnforcement->addArg(nullptr);
if (add) {
project->addCondition(std::unique_ptr<RamCondition>(uniquenessEnforcement), project);
}
}
// build up insertion call
op = std::unique_ptr<RamOperation>(project); // start with innermost
}
// add aggregator levels
for (auto it = aggregators.rbegin(); it != aggregators.rend(); ++it) {
const AstAggregator* cur = *it;
level--;
// translate aggregation function
RamAggregate::Function fun = RamAggregate::MIN;
switch (cur->getOperator()) {
case AstAggregator::min:
fun = RamAggregate::MIN;
break;
case AstAggregator::max:
fun = RamAggregate::MAX;
break;
case AstAggregator::count:
fun = RamAggregate::COUNT;
break;
case AstAggregator::sum:
fun = RamAggregate::SUM;
break;
}
// translate target expression
std::unique_ptr<RamValue> value = translateValue(cur->getTargetExpression(), valueIndex);
// translate body literal
assert(cur->getBodyLiterals().size() == 1 && "Unsupported complex aggregation body encountered!");
const AstAtom* atom = dynamic_cast<const AstAtom*>(cur->getBodyLiterals()[0]);
assert(atom && "Unsupported complex aggregation body encountered!");
// add Ram-Aggregation layer
op = std::unique_ptr<RamOperation>(
new RamAggregate(std::move(op), fun, std::move(value), getRelation(atom)));
// add constant constraints
for (size_t pos = 0; pos < atom->argSize(); ++pos) {
if (AstConstant* c = dynamic_cast<AstConstant*>(atom->getArgument(pos))) {
op->addCondition(std::unique_ptr<RamCondition>(new RamBinaryRelation(BinaryConstraintOp::EQ,
std::unique_ptr<RamValue>(
new RamElementAccess(level, pos, getRelation(atom).getArg(pos))),
std::unique_ptr<RamValue>(new RamNumber(c->getIndex())))));
}
}
}
// build operation bottom-up
while (!op_nesting.empty()) {
// get next operator
const AstNode* cur = op_nesting.back();
op_nesting.pop_back();
// get current nesting level
auto level = op_nesting.size();
if (const AstAtom* atom = dynamic_cast<const AstAtom*>(cur)) {
// find out whether a "search" or "if" should be issued
bool isExistCheck = !valueIndex.isSomethingDefinedOn(level);
for (size_t pos = 0; pos < atom->argSize(); ++pos) {
if (dynamic_cast<AstAggregator*>(atom->getArgument(pos))) {
isExistCheck = false;
}
}
// add a scan level
op = std::unique_ptr<RamOperation>(new RamScan(getRelation(atom), std::move(op), isExistCheck));
// add constraints
for (size_t pos = 0; pos < atom->argSize(); ++pos) {
if (AstConstant* c = dynamic_cast<AstConstant*>(atom->getArgument(pos))) {
op->addCondition(std::unique_ptr<RamCondition>(new RamBinaryRelation(
BinaryConstraintOp::EQ, std::unique_ptr<RamValue>(new RamElementAccess(
level, pos, getRelation(atom).getArg(pos))),
std::unique_ptr<RamValue>(new RamNumber(c->getIndex())))));
} else if (AstAggregator* agg = dynamic_cast<AstAggregator*>(atom->getArgument(pos))) {
auto loc = valueIndex.getAggregatorLocation(*agg);
op->addCondition(std::unique_ptr<RamCondition>(new RamBinaryRelation(
BinaryConstraintOp::EQ, std::unique_ptr<RamValue>(new RamElementAccess(
level, pos, getRelation(atom).getArg(pos))),
std::unique_ptr<RamValue>(
new RamElementAccess(loc.level, loc.component, loc.name)))));
}
}
// TODO: support constants in nested records!
} else if (const AstRecordInit* rec = dynamic_cast<const AstRecordInit*>(cur)) {
// add an unpack level
const Location& loc = valueIndex.getDefinitionPoint(*rec);
op = std::unique_ptr<RamOperation>(
new RamLookup(std::move(op), loc.level, loc.component, rec->getArguments().size()));
// add constant constraints
for (size_t pos = 0; pos < rec->getArguments().size(); ++pos) {
if (AstConstant* c = dynamic_cast<AstConstant*>(rec->getArguments()[pos])) {
op->addCondition(
std::unique_ptr<RamCondition>(new RamBinaryRelation(BinaryConstraintOp::EQ,
std::unique_ptr<RamValue>(new RamElementAccess(level, pos)),
std::unique_ptr<RamValue>(new RamNumber(c->getIndex())))));
}
}
} else {
std::cout << "Unsupported AST node type: " << typeid(*cur).name() << "\n";
assert(false && "Unsupported AST node for creation of scan-level!");
}
}
/* add equivalence constraints imposed by variable binding */
for (const auto& cur : valueIndex.getVariableReferences()) {
// the first appearance
const Location& first = *cur.second.begin();
// all other appearances
for (const Location& loc : cur.second) {
if (first != loc) {
op->addCondition(std::unique_ptr<RamCondition>(new RamBinaryRelation(BinaryConstraintOp::EQ,
std::unique_ptr<RamValue>(
new RamElementAccess(first.level, first.component, first.name)),
std::unique_ptr<RamValue>(
new RamElementAccess(loc.level, loc.component, loc.name)))));
}
}
}
/* add conditions caused by atoms, negations, and binary relations */
for (const auto& lit : clause.getBodyLiterals()) {
// for atoms
if (dynamic_cast<const AstAtom*>(lit)) {
// covered already within the scan/lookup generation step
// for binary relations
} else if (auto binRel = dynamic_cast<const AstConstraint*>(lit)) {
std::unique_ptr<RamValue> valLHS = translateValue(binRel->getLHS(), valueIndex);
std::unique_ptr<RamValue> valRHS = translateValue(binRel->getRHS(), valueIndex);
op->addCondition(std::unique_ptr<RamCondition>(
new RamBinaryRelation(binRel->getOperator(), translateValue(binRel->getLHS(), valueIndex),
translateValue(binRel->getRHS(), valueIndex))));
// for negations
} else if (auto neg = dynamic_cast<const AstNegation*>(lit)) {
// get contained atom
const AstAtom* atom = neg->getAtom();
// create constraint
RamNotExists* notExists = new RamNotExists(getRelation(atom));
auto arity = atom->getArity();
// account for two extra provenance columns
if (Global::config().has("provenance")) {
arity -= 2;
}
for (size_t i = 0; i < arity; i++) {
const auto& arg = atom->getArgument(i);
// for (const auto& arg : atom->getArguments()) {
notExists->addArg(translateValue(*arg, valueIndex));
}
// we don't care about the provenance columns when doing the existence check
if (Global::config().has("provenance")) {
notExists->addArg(nullptr);
notExists->addArg(nullptr);
}
// add constraint
op->addCondition(std::unique_ptr<RamCondition>(notExists));
} else {
std::cout << "Unsupported node type: " << typeid(*lit).name();
assert(false && "Unsupported node type!");
}
}
/* generate the final RAM Insert statement */
return std::make_unique<RamInsert>(clause, std::move(op));
}
/* utility for appending statements */
static void appendStmt(std::unique_ptr<RamStatement>& stmtList, std::unique_ptr<RamStatement> stmt) {
if (stmt) {
if (stmtList) {
RamSequence* stmtSeq;
if ((stmtSeq = dynamic_cast<RamSequence*>(stmtList.get()))) {
stmtSeq->add(std::move(stmt));
} else {
stmtList = std::make_unique<RamSequence>(std::move(stmtList), std::move(stmt));
}
} else {
stmtList = std::move(stmt);
}
}
};
/** generate RAM code for a non-recursive relation */
std::unique_ptr<RamStatement> RamTranslator::translateNonRecursiveRelation(const AstRelation& rel,
const AstProgram* program, const RecursiveClauses* recursiveClauses, const TypeEnvironment& typeEnv) {
/* start with an empty sequence */
std::unique_ptr<RamStatement> res;
// the ram table reference
RamRelationIdentifier rrel =
getRamRelationIdentifier(&rel, &typeEnv, getRelationName(rel.getName()), rel.getArity());
/* iterate over all clauses that belong to the relation */
for (AstClause* clause : rel.getClauses()) {
// skip recursive rules
if (recursiveClauses->recursive(clause)) {
continue;
}
// translate clause
std::unique_ptr<RamStatement> rule = translateClause(*clause, program, &typeEnv);
// add logging
if (logging) {
std::string clauseText = stringify(toString(*clause));
std::ostringstream line;
line << "nonrecursive-rule;" << rel.getName() << ";";
line << clause->getSrcLoc() << ";";
line << clauseText << ";";
std::string label = line.str();
rule = std::unique_ptr<RamStatement>(new RamSequence(
std::unique_ptr<RamStatement>(new RamLogTimer(std::move(rule), "@t-" + label)),
std::make_unique<RamLogSize>(rrel, "@n-" + label)));
}
// add debug info
std::ostringstream ds;
ds << toString(*clause) << "\nin file ";
ds << clause->getSrcLoc();
rule = std::make_unique<RamDebugInfo>(std::move(rule), ds.str());
// add rule to result
appendStmt(res, std::move(rule));
}
// if no clauses have been translated, we are done
if (!res) {
return res;
}
// add logging for entire relation
if (logging) {
// compute label
std::ostringstream line;
line << "nonrecursive-relation;" << rel.getName() << ";";
line << rel.getSrcLoc() << ";";
std::string label = line.str();
// add timer
res = std::make_unique<RamLogTimer>(std::move(res), "@t-" + label);
// add table size printer
appendStmt(res, std::make_unique<RamLogSize>(rrel, "@n-" + label));
}
// done
return res;
}
namespace {
/**
* A utility function assigning names to unnamed variables such that enclosing
* constructs may be cloned without losing the variable-identity.
*/
void nameUnnamedVariables(AstClause* clause) {
// the node mapper conducting the actual renaming
struct Instantiator : public AstNodeMapper {
mutable int counter;
Instantiator() : counter(0) {}
std::unique_ptr<AstNode> operator()(std::unique_ptr<AstNode> node) const override {
// apply recursive
node->apply(*this);
// replace unknown variables
if (dynamic_cast<AstUnnamedVariable*>(node.get())) {
auto name = " _unnamed_var" + toString(++counter);
return std::unique_ptr<AstNode>(new AstVariable(name));
}
// otherwise nothing
return node;
}
};
// name all variables in the atoms
Instantiator init;
for (auto& atom : clause->getAtoms()) {
atom->apply(init);
}
}
} // namespace
/** generate RAM code for recursive relations in a strongly-connected component */
std::unique_ptr<RamStatement> RamTranslator::translateRecursiveRelation(
const std::set<const AstRelation*>& scc, const AstProgram* program,
const RecursiveClauses* recursiveClauses, const TypeEnvironment& typeEnv) {
// initialize sections
std::unique_ptr<RamStatement> preamble;
std::unique_ptr<RamSequence> updateTable(new RamSequence());
std::unique_ptr<RamStatement> postamble;
// --- create preamble ---
// mappings for temporary relations
std::map<const AstRelation*, RamRelationIdentifier> rrel;
std::map<const AstRelation*, RamRelationIdentifier> relDelta;
std::map<const AstRelation*, RamRelationIdentifier> relNew;
/* Compute non-recursive clauses for relations in scc and push
the results in their delta tables. */
for (const AstRelation* rel : scc) {
std::unique_ptr<RamStatement> updateRelTable;
/* create two temporary tables for relaxed semi-naive evaluation */
auto relName = getRelationName(rel->getName());
rrel[rel] = getRamRelationIdentifier(rel, &typeEnv, relName, rel->getArity());
relDelta[rel] = getRamRelationIdentifier(rel, &typeEnv, "delta_" + relName, rel->getArity(), true);
relNew[rel] = getRamRelationIdentifier(rel, &typeEnv, "new_" + relName, rel->getArity(), true);
/* create update statements for fixpoint (even iteration) */
if (Global::config().has("fault-tolerance") && !rel->hasRecordInHead()) {
appendStmt(updateRelTable,
std::unique_ptr<RamStatement>(new RamSequence(
std::unique_ptr<RamStatement>(new RamMerge(rrel[rel], relNew[rel])),
// TODO (#466): uncomment the following line to store new recursive
// relations immediately upon discovery
// std::unique_ptr<RamStatement>(new RamStore(relNew[rel])),
std::unique_ptr<RamStatement>(new RamSwap(relDelta[rel], relNew[rel])),
std::make_unique<RamClear>(relNew[rel]))));
} else {
appendStmt(updateRelTable,
std::unique_ptr<RamStatement>(new RamSequence(
std::unique_ptr<RamStatement>(new RamMerge(rrel[rel], relNew[rel])),
std::unique_ptr<RamStatement>(new RamSwap(relDelta[rel], relNew[rel])),
std::make_unique<RamClear>(relNew[rel]))));
}
/* measure update time for each relation */
if (logging) {
std::ostringstream ost, osn;
ost << "@c-recursive-relation;" << rel->getName() << ";" << rel->getSrcLoc() << ";";
updateRelTable = std::make_unique<RamLogTimer>(std::move(updateRelTable), ost.str());
}
/* drop temporary tables after recursion */
appendStmt(postamble, std::unique_ptr<RamStatement>(new RamSequence(
std::unique_ptr<RamStatement>(new RamDrop(relDelta[rel])),
std::make_unique<RamDrop>(relNew[rel]))));
/* Generate code for non-recursive part of relation */
appendStmt(preamble, translateNonRecursiveRelation(*rel, program, recursiveClauses, typeEnv));
/* Generate merge operation for temp tables */
appendStmt(preamble, std::make_unique<RamMerge>(relDelta[rel], rrel[rel]));
/* Add update operations of relations to parallel statements */
updateTable->add(std::move(updateRelTable));
}
// --- build main loop ---
std::unique_ptr<RamParallel> loopSeq(new RamParallel());
// create a utility to check SCC membership
auto isInSameSCC = [&](
const AstRelation* rel) { return std::find(scc.begin(), scc.end(), rel) != scc.end(); };
/* Compute temp for the current tables */
for (const AstRelation* rel : scc) {
std::unique_ptr<RamStatement> loopRelSeq;
/* Find clauses for relation rel */
for (size_t i = 0; i < rel->clauseSize(); i++) {
AstClause* cl = rel->getClause(i);
// skip non-recursive clauses
if (!recursiveClauses->recursive(cl)) {
continue;
}
// each recursive rule results in several operations
int version = 0;
const auto& atoms = cl->getAtoms();
for (size_t j = 0; j < atoms.size(); ++j) {
const AstAtom* atom = atoms[j];
const AstRelation* atomRelation = getAtomRelation(atom, program);
// only interested in atoms within the same SCC