-
Notifications
You must be signed in to change notification settings - Fork 0
/
programStructure.cpp
2279 lines (2070 loc) · 91.1 KB
/
programStructure.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "programStructure.h"
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <set>
#include <algorithm>
#include "lib/path.h"
#include "lib/gmputil.h"
#include "converters.h"
#include "frontends/common/options.h"
#include "frontends/parsers/parserDriver.h"
#include "frontends/p4/reservedWords.h"
#include "frontends/p4/coreLibrary.h"
#include "frontends/p4/tableKeyNames.h"
namespace P4FLX {
ProgramStructure::ProgramStructure() :
v1model(P4FLX::V1Model::instance), p4lib(P4::P4CoreLibrary::instance),
types(&allNames), metadata(&allNames), headers(&allNames), stacks(&allNames),
controls(&allNames), parserStates(&allNames), tables(&allNames),
actions(&allNames), counters(&allNames), registers(&allNames), meters(&allNames),
action_profiles(nullptr), field_lists(nullptr), field_list_calculations(&allNames),
action_selectors(nullptr), extern_types(&allNames), externs(&allNames),
calledActions("actions"), calledControls("controls"), calledCounters("counters"),
calledMeters("meters"), calledRegisters("registers"), calledExterns("externs"),
parsers("parsers"), parserPacketIn(nullptr), parserHeadersOut(nullptr),
verifyChecksums(nullptr), updateChecksums(nullptr),
deparser(nullptr), latest(nullptr) {
ingress = nullptr;
declarations = new IR::IndexedVector<IR::Node>();
emptyTypeArguments = new IR::Vector<IR::Type>();
conversionContext.clear();
for (auto c : P4::reservedWords)
allNames.emplace(c);
}
const IR::Annotations*
ProgramStructure::addNameAnnotation(cstring name, const IR::Annotations* annos) {
if (annos == nullptr)
annos = IR::Annotations::empty;
return annos->addAnnotationIfNew(IR::Annotation::nameAnnotation,
new IR::StringLiteral(name));
}
const IR::Annotations*
ProgramStructure::addGlobalNameAnnotation(cstring name,
const IR::Annotations* annos) {
return addNameAnnotation(cstring(".") + name, annos);
}
cstring ProgramStructure::makeUniqueName(cstring base) {
cstring name = cstring::make_unique(allNames, base, '_');
allNames.emplace(name);
return name;
}
bool ProgramStructure::isHeader(const IR::ConcreteHeaderRef* nhr) const {
cstring name = nhr->ref->name.name;
auto hdr = headers.get(name);
if (hdr != nullptr)
return true;
auto stack = stacks.get(name);
if (stack != nullptr)
return true;
auto meta = metadata.get(name);
if (meta != nullptr)
return false;
BUG("Unexpected reference %1%", nhr);
}
void ProgramStructure::checkHeaderType(const IR::Type_StructLike* hdr, bool metadata) {
LOG1("Checking " << hdr << " " << (metadata ? "M" : "H"));
for (auto f : hdr->fields) {
if (f->type->is<IR::Type_Varbits>()) {
if (metadata)
::error("%1%: varbit types illegal in metadata", f);
} else if (!f->type->is<IR::Type_Bits>()) {
// These come from P4-14, so they cannot be anything else
BUG("%1%: unexpected type", f); }
}
}
cstring ProgramStructure::createType(const IR::Type_StructLike* type, bool header,
std::unordered_set<const IR::Type*> *converted) {
if (converted->count(type))
return type->name;
converted->emplace(type);
auto type_name = types.get(type);
auto newType = type->apply(TypeConverter(this));
if (newType->name.name != type_name) {
auto annos = addNameAnnotation(type->name.name, type->annotations);
if (header) {
newType = new IR::Type_Header(newType->srcInfo, type_name, annos, newType->fields);
} else {
newType = new IR::Type_Struct(newType->srcInfo, type_name, annos, newType->fields);
}
}
if (header)
finalHeaderType.emplace(type->externalName(), newType);
checkHeaderType(newType, !header);
LOG3("Added type " << dbp(newType) << " named " << type_name << " from " << dbp(type));
declarations->push_back(newType);
converted->emplace(newType);
return type_name;
}
void ProgramStructure::createTypes() {
std::unordered_set<const IR::Type *> converted;
// Metadata first
for (auto it : metadata) {
auto type = it.first->type;
if (type->name.name == v1model.standardMetadataType.name)
continue;
createType(type, false, &converted);
}
for (auto it : registers) {
if (it.first->layout) {
cstring layoutTypeName = it.first->layout;
auto type = types.get(layoutTypeName);
if (converted.count(type) || !type->is<IR::Type_StructLike>())
continue;
auto st = type->to<IR::Type_StructLike>();
if (type->is<IR::Type_Struct>()) {
cstring newName = createType(type, false, &converted);
registerLayoutType.emplace(layoutTypeName, newName);
continue;
}
BUG_CHECK(type->is<IR::Type_Header>(), "%1%: unexpected type", type);
// Must convert to a struct type
cstring type_name = makeUniqueName(st->name);
// Registers always use struct types
auto annos = addNameAnnotation(layoutTypeName, type->annotations);
auto newType = new IR::Type_Struct(type->srcInfo, type_name, annos, st->fields);
checkHeaderType(newType, false);
LOG3("Added type " << dbp(newType) << " named " << type_name << " from " << dbp(type));
declarations->push_back(newType);
registerLayoutType.emplace(layoutTypeName, newType->name);
}
}
// Now headers
converted.clear();
for (auto it : headers) {
auto type = it.first->type;
CHECK_NULL(type);
createType(type, true, &converted);
}
for (auto it : stacks) {
auto type = it.first->type;
CHECK_NULL(type);
createType(type, true, &converted);
}
}
const IR::Type_Struct* ProgramStructure::createFieldListType(const IR::Expression* expression) {
if (!expression->is<IR::PathExpression>()) {
::error("%1%: expected a field list", expression);
return nullptr;
}
auto nr = expression->to<IR::PathExpression>();
auto fl = field_lists.get(nr->path->name);
if (fl == nullptr) {
::error("%1%: Expected a field list", expression);
return nullptr;
}
auto name = makeUniqueName(nr->path->name);
auto annos = addNameAnnotation(nr->path->name);
auto result = new IR::Type_Struct(expression->srcInfo, name, annos);
std::set<cstring> fieldNames;
for (auto f : fl->fields) {
cstring name;
if (f->is<IR::PathExpression>())
name = f->to<IR::PathExpression>()->path->name;
else if (f->is<IR::Member>())
name = f->to<IR::Member>()->member;
name = cstring::make_unique(fieldNames, name, '_');
fieldNames.emplace(name);
auto type = f->type;
CHECK_NULL(type);
BUG_CHECK(!type->is<IR::Type_Unknown>(), "%1%: Unknown field list member type", f);
auto sf = new IR::StructField(f->srcInfo, name, type);
result->fields.push_back(sf);
}
return result;
}
void ProgramStructure::createStructures() {
auto metadata = new IR::Type_Struct(v1model.metadataType.Id());
for (auto it : this->metadata) {
if (it.first->name == v1model.standardMetadata.name)
continue;
IR::ID id = it.first->name;
auto type = it.first->type;
auto type_name = types.get(type);
auto ht = type->to<IR::Type_Struct>();
auto path = new IR::Path(type_name);
auto tn = new IR::Type_Name(ht->name.srcInfo, path);
auto annos = addNameAnnotation(id, it.first->annotations);
auto field = new IR::StructField(id.srcInfo, id, annos, tn);
metadata->fields.push_back(field);
}
declarations->push_back(metadata);
auto headers = new IR::Type_Struct(IR::ID(v1model.headersType.name));
for (auto it : this->headers) {
IR::ID id = it.first->name;
auto type = it.first->type;
auto type_name = types.get(type);
auto ht = type->to<IR::Type_Header>();
auto path = new IR::Path(type_name);
auto tn = new IR::Type_Name(ht->name.srcInfo, path);
auto annos = addNameAnnotation(id, it.first->annotations);
auto field = new IR::StructField(id.srcInfo, id, annos, tn);
headers->fields.push_back(field);
}
for (auto it : stacks) {
IR::ID id = it.first->name;
auto type = it.first->type;
auto type_name = types.get(type);
int size = it.first->size;
auto ht = type->to<IR::Type_Header>();
auto path = new IR::Path(type_name);
auto tn = new IR::Type_Name(ht->name.srcInfo, path);
auto stack = new IR::Type_Stack(id.srcInfo, tn, new IR::Constant(size));
auto annos = addGlobalNameAnnotation(id, it.first->annotations);
auto field = new IR::StructField(id.srcInfo, id, annos, stack);
headers->fields.push_back(field);
}
declarations->push_back(headers);
}
void ProgramStructure::createExterns() {
for (auto it : extern_types) {
if (auto et = ExternConverter::cvtExternType(this, it.first, it.second)) {
if (et != it.first)
extern_remap[it.first] = et;
if (et != declarations->getDeclaration(et->name))
declarations->push_back(et); } }
}
const IR::Expression* ProgramStructure::paramReference(const IR::Parameter* param) {
auto result = new IR::PathExpression(param->name);
auto tn = param->type->to<IR::Type_Name>();
cstring name = tn->path->toString();
auto type = types.get(name);
if (type != nullptr)
result->type = type;
else
result->type = param->type;
return result;
}
const IR::AssignmentStatement* ProgramStructure::assign(
Util::SourceInfo srcInfo, const IR::Expression* left,
const IR::Expression* right, const IR::Type* type) {
if (type != nullptr && type != right->type)
right = new IR::Cast(type, right);
return new IR::AssignmentStatement(srcInfo, left, right);
}
const IR::Statement* ProgramStructure::convertParserStatement(const IR::Expression* expr) {
ExpressionConverter conv(this);
if (expr->is<IR::Primitive>()) {
auto primitive = expr->to<IR::Primitive>();
if (primitive->name == "extract") {
BUG_CHECK(primitive->operands.size() == 1, "Expected 1 operand for %1%", primitive);
auto dest = primitive->operands.at(0);
auto destType = dest->type;
CHECK_NULL(destType);
BUG_CHECK(destType->is<IR::Type_Header>(), "%1%: expected a header", destType);
auto finalDestType = ::get(
finalHeaderType, destType->to<IR::Type_Header>()->externalName());
BUG_CHECK(finalDestType != nullptr, "%1%: could not find final type",
destType->to<IR::Type_Header>()->externalName());
destType = finalDestType;
BUG_CHECK(destType->is<IR::Type_Header>(), "%1%: expected a header", destType);
auto current = conv.convert(dest);
auto args = new IR::Vector<IR::Expression>();
args->push_back(current);
// A second conversion of dest is used to compute the
// 'latest' (P4-14 keyword) value if referenced later.
conv.replaceNextWithLast = true;
this->latest = conv.convert(dest);
conv.replaceNextWithLast = false;
const IR::Expression* method = new IR::Member(
paramReference(parserPacketIn),
p4lib.packetIn.extract.Id());
auto mce = new IR::MethodCallExpression(expr->srcInfo, method, args);
LOG3("Inserted extract " << dbp(mce) << " " << dbp(destType));
extractsSynthesized.emplace(mce, destType->to<IR::Type_Header>());
auto result = new IR::MethodCallStatement(expr->srcInfo, mce);
return result;
} else if (primitive->name == "set_metadata") {
BUG_CHECK(primitive->operands.size() == 2, "Expected 2 operands for %1%", primitive);
auto dest = conv.convert(primitive->operands.at(0));
auto src = conv.convert(primitive->operands.at(1));
return assign(primitive->srcInfo, dest, src, primitive->operands.at(0)->type);
}
}
BUG("Unhandled expression %1%", expr);
}
const IR::PathExpression* ProgramStructure::getState(IR::ID dest) {
auto ps = parserStates.get(dest.name);
if (ps != nullptr) {
return new IR::PathExpression(dest);
} else {
auto ctrl = controls.get(dest);
if (ctrl != nullptr) {
if (ingress != nullptr) {
if (ingress != ctrl)
::error("Parser exits to two different control blocks: %1% and %2%",
dest, ingressReference);
} else {
ingress = ctrl;
ingressReference = dest;
}
return new IR::PathExpression(IR::ParserState::accept);
} else {
::error("%1%: unknown state", dest);
return nullptr;
}
}
}
static const IR::Expression*
explodeLabel(const IR::Constant* value, const IR::Constant* mask,
const std::vector<int> &sizes) {
if (mask->value == 0)
return new IR::DefaultExpression(value->srcInfo);
bool useMask = mask->value != -1;
mpz_class v = value->value;
mpz_class m = mask->value;
auto rv = new IR::ListExpression(value->srcInfo, {});
for (auto it = sizes.rbegin(); it != sizes.rend(); ++it) {
int s = *it;
auto bits = Util::ripBits(v, s);
auto type = IR::Type_Bits::get(s);
const IR::Expression* expr = new IR::Constant(value->srcInfo, type, bits, value->base);
if (useMask) {
auto maskbits = Util::ripBits(m, s);
auto maskcst = new IR::Constant(mask->srcInfo, type, maskbits, mask->base);
expr = new IR::Mask(mask->srcInfo, expr, maskcst);
}
rv->components.insert(rv->components.begin(), expr);
}
if (rv->components.size() == 1)
return rv->components.at(0);
return rv;
}
const IR::ParserState* ProgramStructure::convertParser(const IR::V1Parser* parser) {
ExpressionConverter conv(this);
latest = nullptr;
IR::IndexedVector<IR::StatOrDecl> components;
for (auto e : parser->stmts) {
auto stmt = convertParserStatement(e);
components.push_back(stmt);
}
const IR::Expression* select = nullptr;
if (parser->select != nullptr) {
auto list = new IR::ListExpression(parser->select->srcInfo, {});
std::vector<int> sizes;
for (auto e : *parser->select) {
auto c = conv.convert(e);
list->components.push_back(c);
int w = c->type->width_bits();
BUG_CHECK(w > 0, "Unknown width for expression %1%", e);
sizes.push_back(w);
}
BUG_CHECK(list->components.size() > 0, "No select expression in %1%", parser);
// select always expects a ListExpression
IR::Vector<IR::SelectCase> cases;
for (auto c : *parser->cases) {
IR::ID state = c->action;
auto deststate = getState(state);
if (deststate == nullptr)
return nullptr;
for (auto v : c->values) {
auto expr = explodeLabel(v.first, v.second, sizes);
auto sc = new IR::SelectCase(c->srcInfo, expr, deststate);
cases.push_back(sc);
}
}
select = new IR::SelectExpression(parser->select->srcInfo, list, std::move(cases));
} else if (!parser->default_return.name.isNullOrEmpty()) {
IR::ID id = parser->default_return;
select = getState(id);
if (select == nullptr)
return nullptr;
} else {
BUG("No select or default_return %1%", parser);
}
latest = nullptr;
auto annos = addGlobalNameAnnotation(parser->name, parser->annotations);
auto result = new IR::ParserState(parser->srcInfo, parser->name, annos, components, select);
return result;
}
void ProgramStructure::createParser() {
auto paramList = new IR::ParameterList;
auto pinpath = new IR::Path(p4lib.packetIn.Id());
auto pintype = new IR::Type_Name(pinpath);
parserPacketIn = new IR::Parameter(v1model.parser.packetParam.Id(),
IR::Direction::None, pintype);
paramList->push_back(parserPacketIn);
auto headpath = new IR::Path(v1model.headersType.Id());
auto headtype = new IR::Type_Name(headpath);
parserHeadersOut = new IR::Parameter(v1model.parser.headersParam.Id(),
IR::Direction::Out, headtype);
paramList->push_back(parserHeadersOut);
conversionContext.header = paramReference(parserHeadersOut);
auto metapath = new IR::Path(v1model.metadataType.Id());
auto metatype = new IR::Type_Name(metapath);
auto meta = new IR::Parameter(v1model.parser.metadataParam.Id(),
IR::Direction::InOut, metatype);
paramList->push_back(meta);
conversionContext.userMetadata = paramReference(meta);
auto stdMetaPath = new IR::Path(v1model.standardMetadataType.Id());
auto stdMetaType = new IR::Type_Name(stdMetaPath);
auto stdmeta = new IR::Parameter(v1model.ingress.standardMetadataParam.Id(),
IR::Direction::InOut, stdMetaType);
paramList->push_back(stdmeta);
conversionContext.standardMetadata = paramReference(stdmeta);
auto type = new IR::Type_Parser(v1model.parser.Id(), new IR::TypeParameters(), paramList);
IR::IndexedVector<IR::Declaration> stateful;
IR::IndexedVector<IR::ParserState> states;
for (auto p : parserStates) {
auto ps = convertParser(p.first);
if (ps == nullptr)
return;
states.push_back(ps);
}
if (states.empty())
::error("No parsers specified");
auto result = new IR::P4Parser(v1model.parser.Id(), type, stateful, states);
declarations->push_back(result);
conversionContext.clear();
}
void ProgramStructure::include(cstring filename) {
// the p4c driver sets environment variables for include
// paths. check the environment and add these to the command
// line for the preporicessor
char * drvP4IncludePath = getenv("P4C_16_INCLUDE_PATH");
Util::PathName path(drvP4IncludePath ? drvP4IncludePath : p4includePath);
path = path.join(filename);
CompilerOptions options;
options.langVersion = CompilerOptions::FrontendVersion::P4_16;
options.file = path.toString();
if (FILE* file = options.preprocess()) {
if (!::errorCount()) {
auto code = P4::P4ParserDriver::parse(options.file, file);
if (code && !::errorCount())
for (auto decl : code->declarations)
declarations->push_back(decl); }
options.closeInput(file); }
}
void ProgramStructure::loadModel() {
// This includes in turn core.p4
include("v1model.p4");
}
namespace {
// Must return a 'canonical' representation of each header.
// If a header appears twice this must return the SAME expression.
class HeaderRepresentation {
private:
const IR::Expression* hdrsParam; // reference to headers parameter in deparser
std::map<cstring, const IR::Expression*> header;
std::map<cstring, const IR::Expression*> fakeHeader;
std::map<const IR::Expression*, std::map<int, const IR::Expression*>> stackElement;
public:
explicit HeaderRepresentation(const IR::Expression* hdrsParam) :
hdrsParam(hdrsParam) { CHECK_NULL(hdrsParam); }
const IR::Expression* getHeader(const IR::Expression* expression) {
CHECK_NULL(expression);
// expression is a reference to a header in an 'extract' statement
if (expression->is<IR::ConcreteHeaderRef>()) {
cstring name = expression->to<IR::ConcreteHeaderRef>()->ref->name;
if (header.find(name) == header.end())
header[name] = new IR::Member(hdrsParam, name);
return header[name];
} else if (expression->is<IR::HeaderStackItemRef>()) {
auto hsir = expression->to<IR::HeaderStackItemRef>();
auto hdr = getHeader(hsir->base_);
if (hsir->index_->is<IR::PathExpression>())
// This is most certainly 'next'.
return hdr;
BUG_CHECK(hsir->index_->is<IR::Constant>(), "%1%: expected a constant", hsir->index_);
int index = hsir->index_->to<IR::Constant>()->asInt();
if (stackElement.find(hdr) != stackElement.end()) {
if (stackElement[hdr].find(index) != stackElement[hdr].end())
return stackElement[hdr][index];
}
auto ai = new IR::ArrayIndex(hdr, hsir->index_);
stackElement[hdr][index] = ai;
return ai;
}
BUG("%1%: Unexpected expression in 'extract'", expression);
}
const IR::Expression* getFakeHeader(cstring state) {
if (fakeHeader.find(state) == fakeHeader.end())
fakeHeader[state] = new IR::StringLiteral(state);
return fakeHeader[state];
}
};
} // namespace
void ProgramStructure::createDeparser() {
auto headpath = new IR::Path(v1model.headersType.Id());
auto headtype = new IR::Type_Name(headpath);
auto headers = new IR::Parameter(v1model.deparser.headersParam.Id(),
IR::Direction::In, headtype);
auto hdrsParam = paramReference(headers);
HeaderRepresentation hr(hdrsParam);
P4::CallGraph<const IR::Expression*> headerOrder("headerOrder");
for (auto it : parsers) {
cstring caller = it.first;
const IR::Expression* lastExtract = nullptr;
if (extracts.count(caller) == 0) {
lastExtract = hr.getFakeHeader(caller);
} else {
for (auto e : extracts[caller]) {
auto h = hr.getHeader(e);
if (lastExtract != nullptr)
headerOrder.calls(lastExtract, h);
lastExtract = h;
}
}
for (auto callee : *it.second) {
const IR::Expression* firstExtract;
if (extracts.count(callee) == 0) {
firstExtract = hr.getFakeHeader(callee);
} else {
auto e = extracts[callee].at(0);
auto h = hr.getHeader(e);
firstExtract = h;
}
headerOrder.calls(lastExtract, firstExtract);
}
}
cstring start = IR::ParserState::start;
const IR::Expression* startHeader;
// find starting point
if (extracts.count(start) != 0) {
auto e = extracts[start].at(0);
startHeader = hr.getHeader(e);
} else {
startHeader = hr.getFakeHeader(start);
}
std::vector<const IR::Expression*> sortedHeaders;
bool loop = headerOrder.sccSort(startHeader, sortedHeaders);
if (loop)
::warning("The order of headers in deparser is not uniquely determined by parser!");
auto params = new IR::ParameterList;
auto poutpath = new IR::Path(p4lib.packetOut.Id());
auto pouttype = new IR::Type_Name(poutpath);
auto packetOut = new IR::Parameter(v1model.deparser.packetParam.Id(),
IR::Direction::None, pouttype);
params->push_back(packetOut);
params->push_back(headers);
conversionContext.header = paramReference(headers);
auto type = new IR::Type_Control(v1model.deparser.Id(), params);
ExpressionConverter conv(this);
auto body = new IR::BlockStatement;
for (auto it = sortedHeaders.rbegin(); it != sortedHeaders.rend(); it++) {
auto exp = *it;
if (exp->is<IR::StringLiteral>())
// a "fake" header
continue;
auto args = new IR::Vector<IR::Expression>();
args->push_back(exp);
const IR::Expression* method = new IR::Member(
paramReference(packetOut),
p4lib.packetOut.emit.Id());
auto mce = new IR::MethodCallExpression(method, args);
auto stat = new IR::MethodCallStatement(mce);
body->push_back(stat);
}
deparser = new IR::P4Control(v1model.deparser.Id(), type, body);
declarations->push_back(deparser);
}
const IR::P4Table*
ProgramStructure::convertTable(const IR::V1Table* table, cstring newName,
IR::IndexedVector<IR::Declaration> &stateful,
std::map<cstring, cstring> &mapNames) {
ExpressionConverter conv(this);
auto props = new IR::TableProperties(table->properties.properties);
auto actionList = new IR::ActionList({});
cstring profile = table->action_profile.name;
const IR::ActionProfile* action_profile = nullptr;
const IR::ActionSelector* action_selector = nullptr;
if (!profile.isNullOrEmpty()) {
action_profile = action_profiles.get(profile);
if (!action_profile->selector.name.isNullOrEmpty()) {
action_selector = action_selectors.get(action_profile->selector.name);
if (action_selector == nullptr)
::error("Cannot locate action selector %1%", action_profile->selector);
}
}
auto mtr = get(directMeters, table->name);
auto ctr = get(directCounters, table->name);
const std::vector<IR::ID> &actionsToDo =
action_profile ? action_profile->actions : table->actions;
for (auto a : actionsToDo) {
auto action = actions.get(a);
cstring newname;
if (mtr != nullptr || ctr != nullptr) {
// we must synthesize a new action, which has a writeback to
// the meter/counter
newname = makeUniqueName(a);
auto actCont = convertAction(action, newname, mtr, ctr);
stateful.push_back(actCont);
mapNames[table->name + '.' + a] = newname;
} else {
newname = actions.get(action);
}
auto ale = new IR::ActionListElement(a.srcInfo, new IR::PathExpression(newname));
actionList->push_back(ale);
}
if (!table->default_action.name.isNullOrEmpty() &&
!actionList->getDeclaration(table->default_action)) {
actionList->push_back(
new IR::ActionListElement(
new IR::Annotations(
{new IR::Annotation(IR::Annotation::defaultOnlyAnnotation, {})}),
new IR::PathExpression(table->default_action))); }
props->push_back(new IR::Property(IR::ID(IR::TableProperties::actionsPropertyName),
actionList, false));
if (table->reads != nullptr) {
auto key = new IR::Key({});
for (size_t i = 0; i < table->reads->size(); i++) {
auto e = table->reads->at(i);
auto rt = table->reads_types.at(i);
if (rt.name == "valid")
rt.name = p4lib.exactMatch.Id();
auto ce = conv.convert(e);
// If the key has a P4-14 mask, we add here a @name annotation.
// A mask generates a BAnd; a BAnd can only come from a mask.
const IR::Annotations* annos = IR::Annotations::empty;
if (ce->is<IR::BAnd>()) {
auto mask = ce->to<IR::BAnd>();
auto expr = mask->left;
if (mask->left->is<IR::Constant>())
expr = mask->right;
P4::KeyNameGenerator kng(nullptr);
expr->apply(kng);
cstring anno = kng.getName(expr);
annos = annos->addAnnotation(IR::Annotation::nameAnnotation,
new IR::StringLiteral(key->srcInfo, anno));
}
// Here we rely on the fact that the spelling of 'rt' is
// the same in P4-14 and core.p4/v1model.p4.
auto keyComp = new IR::KeyElement(annos, ce, new IR::PathExpression(rt));
key->push_back(keyComp);
}
if (action_selector != nullptr) {
auto flc = field_list_calculations.get(action_selector->key.name);
if (flc == nullptr) {
::error("Cannot locate field list %1%", action_selector->key);
} else {
auto fl = getFieldLists(flc);
if (fl != nullptr) {
for (auto f : fl->fields) {
auto ce = conv.convert(f);
auto keyComp = new IR::KeyElement(ce,
new IR::PathExpression(v1model.selectorMatchType.Id()));
key->push_back(keyComp);
}
}
}
}
props->push_back(new IR::Property(IR::ID(IR::TableProperties::keyPropertyName),
key, false));
}
if (table->size != 0) {
auto prop = new IR::Property(IR::ID("size"),
new IR::ExpressionValue(new IR::Constant(table->size)), false);
props->push_back(prop);
}
if (table->min_size != 0) {
auto prop = new IR::Property(IR::ID("min_size"),
new IR::ExpressionValue(new IR::Constant(table->min_size)), false);
props->push_back(prop);
}
if (table->max_size != 0) {
auto prop = new IR::Property(IR::ID("max_size"),
new IR::ExpressionValue(new IR::Constant(table->max_size)), false);
props->push_back(prop);
}
if (!table->default_action.name.isNullOrEmpty()) {
auto act = new IR::PathExpression(table->default_action);
auto args = table->default_action_args ?
table->default_action_args : new IR::Vector<IR::Expression>();
auto methodCall = new IR::MethodCallExpression(act, args);
auto prop = new IR::Property(
IR::ID(IR::TableProperties::defaultActionPropertyName),
new IR::ExpressionValue(methodCall),
/* isConstant = */ false);
props->push_back(prop);
}
if (action_selector != nullptr) {
auto type = new IR::Type_Name(new IR::Path(v1model.action_selector.Id()));
auto args = new IR::Vector<IR::Expression>();
auto flc = field_list_calculations.get(action_selector->key.name);
auto algorithm = convertHashAlgorithm(flc->algorithm);
if (algorithm == nullptr)
return nullptr;
args->push_back(algorithm);
auto size = new IR::Constant(v1model.action_selector.sizeType, action_profile->size);
args->push_back(size);
auto width = new IR::Constant(v1model.action_selector.widthType, flc->output_width);
args->push_back(width);
auto constructor = new IR::ConstructorCallExpression(type, args);
auto propvalue = new IR::ExpressionValue(constructor);
auto annos = addGlobalNameAnnotation(action_profile->name);
if (action_selector->mode)
annos = annos->addAnnotation("mode", new IR::StringLiteral(action_selector->mode));
if (action_selector->type)
annos = annos->addAnnotation("type", new IR::StringLiteral(action_selector->type));
auto prop = new IR::Property(
IR::ID(v1model.tableAttributes.tableImplementation.Id()),
annos, propvalue, false);
props->push_back(prop);
} else if (action_profile != nullptr) {
auto size = new IR::Constant(v1model.action_profile.sizeType, action_profile->size);
auto type = new IR::Type_Name(new IR::Path(v1model.action_profile.Id()));
auto args = new IR::Vector<IR::Expression>();
args->push_back(size);
auto constructor = new IR::ConstructorCallExpression(type, args);
auto propvalue = new IR::ExpressionValue(constructor);
auto annos = addGlobalNameAnnotation(action_profile->name);
auto prop = new IR::Property(
IR::ID(v1model.tableAttributes.tableImplementation.Id()),
annos, propvalue, false);
props->push_back(prop);
}
if (!ctr.isNullOrEmpty()) {
auto counter = counters.get(ctr);
auto kindarg = counterType(counter);
auto type = new IR::Type_Name(new IR::Path(v1model.directCounter.Id()));
auto args = new IR::Vector<IR::Expression>();
args->push_back(kindarg);
auto constructor = new IR::ConstructorCallExpression(type, args);
auto propvalue = new IR::ExpressionValue(constructor);
auto annos = addGlobalNameAnnotation(ctr);
auto prop = new IR::Property(
IR::ID(v1model.tableAttributes.counters.Id()),
annos, propvalue, false);
props->push_back(prop);
}
if (mtr != nullptr) {
auto meter = new IR::PathExpression(mtr->name);
auto propvalue = new IR::ExpressionValue(meter);
auto prop = new IR::Property(
IR::ID(v1model.tableAttributes.meters.Id()), propvalue, false);
props->push_back(prop);
}
auto annos = addGlobalNameAnnotation(table->name, table->annotations);
auto result = new IR::P4Table(table->srcInfo, newName, annos, props);
return result;
}
const IR::Expression* ProgramStructure::convertHashAlgorithm(IR::ID algorithm) {
IR::ID result;
if (algorithm == "crc32") {
result = v1model.algorithm.crc32.Id();
} else if (algorithm == "crc32_custom") {
result = v1model.algorithm.crc32_custom.Id();
} else if (algorithm == "crc16") {
result = v1model.algorithm.crc16.Id();
} else if (algorithm == "crc16_custom") {
result = v1model.algorithm.crc16_custom.Id();
} else if (algorithm == "random") {
result = v1model.algorithm.random.Id();
} else if (algorithm == "identity") {
result = v1model.algorithm.identity.Id();
} else {
::warning("%1%: unexpected algorithm", algorithm);
result = algorithm;
}
auto pe = new IR::TypeNameExpression(v1model.algorithm.Id());
auto mem = new IR::Member(pe, result);
return mem;
}
static bool sameBitsType(const IR::Type* left, const IR::Type* right) {
if (typeid(*left) != typeid(*right))
return false;
if (left->is<IR::Type_Bits>())
return left->to<IR::Type_Bits>()->operator==(* right->to<IR::Type_Bits>());
BUG("%1%: Expected a bit/int type", right);
}
// Implement modify_field(left, right, mask)
const IR::Statement* ProgramStructure::sliceAssign(
Util::SourceInfo srcInfo, const IR::Expression* left,
const IR::Expression* right, const IR::Expression* mask) {
if (mask->is<IR::Constant>()) {
auto cst = mask->to<IR::Constant>();
if (cst->value < 0) {
::error("%1%: Negative mask not supported", mask);
return nullptr;
}
auto range = Util::findOnes(cst->value);
if (cst->value == range.value) {
auto h = new IR::Constant(range.highIndex);
auto l = new IR::Constant(range.lowIndex);
left = new IR::Slice(left->srcInfo, left, h, l);
right = new IR::Slice(right->srcInfo, right, h, l);
return assign(srcInfo, left, right, nullptr);
}
// else value is too complex for a slice
}
auto type = left->type;
if (!sameBitsType(mask->type, left->type))
mask = new IR::Cast(type, mask);
if (!sameBitsType(right->type, left->type))
right = new IR::Cast(type, right);
auto op1 = new IR::BAnd(left->srcInfo, left, new IR::Cmpl(mask));
auto op2 = new IR::BAnd(right->srcInfo, right, mask);
auto result = new IR::BOr(mask->srcInfo, op1, op2);
return assign(srcInfo, left, result, type);
}
const IR::Expression* ProgramStructure::convertFieldList(const IR::Expression* expression) {
ExpressionConverter conv(this);
if (!expression->is<IR::PathExpression>()) {
::error("%1%: expected a field list", expression);
return expression;
}
auto nr = expression->to<IR::PathExpression>();
auto fl = field_lists.get(nr->path->name);
if (fl == nullptr) {
::error("%1%: Expected a field list", expression);
return expression;
}
auto result = conv.convert(fl);
return result;
}
const IR::Statement* ProgramStructure::convertPrimitive(const IR::Primitive* primitive) {
ExpressionConverter conv(this);
const IR::GlobalRef *glob = nullptr;
const IR::Declaration_Instance *extrn = nullptr;
if (primitive->operands.size() >= 1)
glob = primitive->operands[0]->to<IR::GlobalRef>();
if (glob) extrn = glob->obj->to<IR::Declaration_Instance>();
if (extrn)
return ExternConverter::cvtExternCall(this, extrn, primitive);
if (auto *st = PrimitiveConverter::cvtPrimitive(this, primitive))
return st;
// If everything else failed maybe we are invoking an action
auto action = actions.get(primitive->name);
if (action != nullptr) {
auto newname = actions.get(action);
auto act = new IR::PathExpression(newname);
auto args = new IR::Vector<IR::Expression>();
for (auto a : primitive->operands) {
auto e = conv.convert(a);
args->push_back(e);
}
auto call = new IR::MethodCallExpression(primitive->srcInfo, act, args);
auto stat = new IR::MethodCallStatement(primitive->srcInfo, call);
return stat;
}
BUG("Unhandled primitive %1%", primitive);
return nullptr;
}
#define OPS_CK(primitive, n) BUG_CHECK((primitive)->operands.size() == n, \
"Expected " #n " operands for %1%", primitive)
CONVERT_PRIMITIVE(modify_field) {
auto args = convertArgs(structure, primitive);
if (args.size() == 2) {
return structure->assign(primitive->srcInfo, args[0], args[1],
primitive->operands.at(0)->type);
} else if (args.size() == 3) {
return structure->sliceAssign(primitive->srcInfo, args[0], args[1], args[2]); }
return nullptr;
}
CONVERT_PRIMITIVE(bit_xor) {
OPS_CK(primitive, 3);
auto args = convertArgs(structure, primitive);
if (!sameBitsType(args[1]->type, args[2]->type))
args[2] = new IR::Cast(args[2]->srcInfo, args[1]->type, args[2]);
auto op = new IR::BXor(primitive->srcInfo, args[1], args[2]);
return structure->assign(primitive->srcInfo, args[0], op, primitive->operands.at(0)->type);
}
CONVERT_PRIMITIVE(min) {
OPS_CK(primitive, 3);
auto args = convertArgs(structure, primitive);
if (!sameBitsType(args[1]->type, args[2]->type))
args[2] = new IR::Cast(args[2]->srcInfo, args[1]->type, args[2]);
auto op = new IR::Mux(primitive->srcInfo,
new IR::Leq(primitive->srcInfo, args[1], args[2]), args[1], args[2]);
return structure->assign(primitive->srcInfo, args[0], op, primitive->operands.at(0)->type);
}
CONVERT_PRIMITIVE(max) {
OPS_CK(primitive, 3);
auto args = convertArgs(structure, primitive);
if (!sameBitsType(args[1]->type, args[2]->type))
args[2] = new IR::Cast(args[2]->srcInfo, args[1]->type, args[2]);
auto op = new IR::Mux(primitive->srcInfo,
new IR::Geq(primitive->srcInfo, args[1], args[2]), args[1], args[2]);
return structure->assign(primitive->srcInfo, args[0], op, primitive->operands.at(0)->type);
}
CONVERT_PRIMITIVE(bit_or) {
OPS_CK(primitive, 3);
auto args = convertArgs(structure, primitive);
if (!sameBitsType(args[1]->type, args[2]->type))
args[2] = new IR::Cast(args[2]->srcInfo, args[1]->type, args[2]);
auto op = new IR::BOr(primitive->srcInfo, args[1], args[2]);
return structure->assign(primitive->srcInfo, args[0], op, primitive->operands.at(0)->type);
}
CONVERT_PRIMITIVE(bit_xnor) {
OPS_CK(primitive, 3);
auto args = convertArgs(structure, primitive);
if (!sameBitsType(args[1]->type, args[2]->type))
args[2] = new IR::Cast(args[2]->srcInfo, args[1]->type, args[2]);
auto op = new IR::Cmpl(primitive->srcInfo, new IR::BXor(primitive->srcInfo, args[1], args[2]));
return structure->assign(primitive->srcInfo, args[0], op, primitive->operands.at(0)->type);
}
CONVERT_PRIMITIVE(add) {