/
simpleSwitch.cpp
1273 lines (1178 loc) · 55.9 KB
/
simpleSwitch.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.
*/
/// This file implements the simple switch model.
#include "simpleSwitch.h"
#include <algorithm>
#include <cstring>
#include <set>
#include "backends/bmv2/common/annotations.h"
#include "backends/bmv2/simple_switch/options.h"
#include "frontends/p4/cloner.h"
#include "frontends/p4/fromv1.0/v1model.h"
#include "midend/flattenLogMsg.h"
using BMV2::mkArrayField;
using BMV2::mkParameters;
using BMV2::mkPrimitive;
using BMV2::nextId;
using BMV2::stringRepr;
namespace BMV2 {
void ParseV1Architecture::modelError(const char *format, const IR::Node *node) {
::error(ErrorType::ERR_MODEL,
(cstring(format) + "\nAre you using an up-to-date v1model.p4?").c_str(), node);
}
bool ParseV1Architecture::preorder(const IR::PackageBlock *main) {
auto prsr = main->findParameterValue(v1model.sw.parser.name);
if (prsr == nullptr || !prsr->is<IR::ParserBlock>()) {
modelError("%1%: main package match the expected model", main);
return false;
}
structure->parser = prsr->to<IR::ParserBlock>()->container;
auto ingress = main->findParameterValue(v1model.sw.ingress.name);
if (ingress == nullptr || !ingress->is<IR::ControlBlock>()) {
modelError("%1%: main package does not match the expected model", main);
return false;
}
auto ingress_name = ingress->to<IR::ControlBlock>()->container->name;
structure->ingress = ingress->to<IR::ControlBlock>()->container;
structure->pipeline_controls.emplace(ingress_name);
auto verify = main->findParameterValue(v1model.sw.verify.name);
if (verify == nullptr || !verify->is<IR::ControlBlock>()) {
modelError("%1%: main package does not match the expected model", main);
return false;
}
structure->verify_checksum = verify->to<IR::ControlBlock>()->container;
structure->non_pipeline_controls.emplace(verify->to<IR::ControlBlock>()->container->name);
auto egress = main->findParameterValue(v1model.sw.egress.name);
if (egress == nullptr || !egress->is<IR::ControlBlock>()) {
modelError("%1%: main package does not match the expected model", main);
return false;
}
auto egress_name = egress->to<IR::ControlBlock>()->container->name;
structure->egress = egress->to<IR::ControlBlock>()->container;
structure->pipeline_controls.emplace(egress_name);
auto compute = main->findParameterValue(v1model.sw.compute.name);
if (compute == nullptr || !compute->is<IR::ControlBlock>()) {
modelError("%1%: main package does not match the expected model", main);
return false;
}
structure->compute_checksum = compute->to<IR::ControlBlock>()->container;
structure->non_pipeline_controls.emplace(compute->to<IR::ControlBlock>()->container->name);
auto deparser = main->findParameterValue(v1model.sw.deparser.name);
if (deparser == nullptr || !deparser->is<IR::ControlBlock>()) {
modelError("%1%: main package match the expected model", main);
return false;
}
structure->deparser = deparser->to<IR::ControlBlock>()->container;
structure->non_pipeline_controls.emplace(deparser->to<IR::ControlBlock>()->container->name);
return false;
}
ExternConverter_clone ExternConverter_clone::singleton;
ExternConverter_clone_preserving_field_list ExternConverter_clone_preserving_field_list::singleton;
ExternConverter_hash ExternConverter_hash::singleton;
ExternConverter_digest ExternConverter_digest::singleton;
ExternConverter_resubmit_preserving_field_list
ExternConverter_resubmit_preserving_field_list::singleton;
ExternConverter_recirculate_preserving_field_list
ExternConverter_recirculate_preserving_field_list::singleton;
ExternConverter_mark_to_drop ExternConverter_mark_to_drop::singleton;
ExternConverter_random ExternConverter_random::singleton;
ExternConverter_truncate ExternConverter_truncate::singleton;
ExternConverter_register ExternConverter_register::singleton;
ExternConverter_counter ExternConverter_counter::singleton;
ExternConverter_meter ExternConverter_meter::singleton;
ExternConverter_direct_counter ExternConverter_direct_counter::singleton;
ExternConverter_direct_meter ExternConverter_direct_meter::singleton;
ExternConverter_action_profile ExternConverter_action_profile::singleton;
ExternConverter_action_selector ExternConverter_action_selector::singleton;
ExternConverter_log_msg ExternConverter_log_msg::singleton;
Util::IJson *ExternConverter_clone::convertExternFunction(ConversionContext *ctxt,
UNUSED const P4::ExternFunction *ef,
const IR::MethodCallExpression *mc,
UNUSED const IR::StatOrDecl *s,
UNUSED const bool emitExterns) {
int id = -1;
if (mc->arguments->size() != 2) {
modelError("Expected 2 arguments for %1%", mc);
return nullptr;
}
cstring name = ctxt->refMap->newName("fl");
auto emptylist = new IR::ListExpression({});
id = ctxt->createFieldList(emptylist, name);
auto cloneType = mc->arguments->at(0);
auto ei = P4::EnumInstance::resolve(cloneType->expression, ctxt->typeMap);
if (ei == nullptr) {
modelError("%1%: must be a constant on this target", cloneType);
return nullptr;
}
cstring prim;
if (ei->name == "I2E") {
prim = "clone_ingress_pkt_to_egress";
if (ctxt->blockConverted != BlockConverted::Ingress) {
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"'clone(I2E, ...) not invoked in ingress %1%", mc);
return nullptr;
}
} else {
prim = "clone_egress_pkt_to_egress";
if (ctxt->blockConverted != BlockConverted::Egress) {
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"'clone(E2E, ...) not invoked in egress %1%", mc);
return nullptr;
}
}
auto session = ctxt->conv->convert(mc->arguments->at(1)->expression);
auto primitive = mkPrimitive(prim);
auto parameters = mkParameters(primitive);
primitive->emplace_non_null("source_info", mc->sourceInfoJsonObj());
parameters->append(session);
if (id >= 0) {
auto cst = new IR::Constant(id);
ctxt->typeMap->setType(cst, IR::Type_Bits::get(32));
auto jcst = ctxt->conv->convert(cst);
parameters->append(jcst);
}
return primitive;
}
/// Returns the id of the Json field list called "field_list<index>".
static unsigned getFieldListById(ConversionContext *ctxt, unsigned index) {
cstring search = cstring("field_list") + Util::toString(index);
int id = -1;
for (auto it : *ctxt->json->field_lists) {
auto j = it->to<Util::JsonObject>();
CHECK_NULL(j);
auto name = j->get("name")->to<Util::JsonValue>()->getString();
if (name == search) {
id = j->get("id")->to<Util::JsonValue>()->getInt();
break;
}
}
if (id == -1) {
::warning(ErrorType::WARN_INVALID, "no user metadata fields tagged with @field_list(%1%)",
index);
// Create an empty list.
cstring name = ctxt->refMap->newName("empty");
id = ctxt->createFieldList(new IR::ListExpression({}), name);
}
return (unsigned)id;
}
Util::IJson *ExternConverter_clone_preserving_field_list::convertExternFunction(
ConversionContext *ctxt, UNUSED const P4::ExternFunction *ef,
const IR::MethodCallExpression *mc, UNUSED const IR::StatOrDecl *s,
UNUSED const bool emitExterns) {
int id = -1;
if (mc->arguments->size() != 3) {
modelError("Expected 3 arguments for %1%", mc);
return nullptr;
}
auto cloneType = mc->arguments->at(0);
auto ei = P4::EnumInstance::resolve(cloneType->expression, ctxt->typeMap);
if (ei == nullptr) {
modelError("%1%: must be a constant on this target", cloneType);
return nullptr;
}
cstring prim;
if (ei->name == "I2E") {
prim = "clone_ingress_pkt_to_egress";
if (ctxt->blockConverted != BlockConverted::Ingress) {
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"'clone_preserving_field_list(I2E, ...) not invoked in ingress %1%", mc);
return nullptr;
}
} else {
prim = "clone_egress_pkt_to_egress";
if (ctxt->blockConverted != BlockConverted::Egress) {
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"'clone_preserving_field_list(E2E, ...) not invoked in egress %1%", mc);
return nullptr;
}
}
auto session = ctxt->conv->convert(mc->arguments->at(1)->expression);
auto primitive = mkPrimitive(prim);
auto parameters = mkParameters(primitive);
primitive->emplace_non_null("source_info", mc->sourceInfoJsonObj());
parameters->append(session);
auto fl = mc->arguments->at(2);
auto cst = fl->expression->to<IR::Constant>();
if (cst == nullptr) {
modelError("%1%: Expected a constant", fl);
return nullptr;
}
id = getFieldListById(ctxt, cst->asUnsigned());
cst = new IR::Constant(id);
ctxt->typeMap->setType(cst, IR::Type_Bits::get(32));
auto jcst = ctxt->conv->convert(cst);
parameters->append(jcst);
return primitive;
}
Util::IJson *ExternConverter_hash::convertExternFunction(ConversionContext *ctxt,
UNUSED const P4::ExternFunction *ef,
const IR::MethodCallExpression *mc,
UNUSED const IR::StatOrDecl *s,
UNUSED const bool emitExterns) {
static std::set<cstring> supportedHashAlgorithms = {
v1model.algorithm.crc32.name, v1model.algorithm.crc32_custom.name,
v1model.algorithm.crc16.name, v1model.algorithm.crc16_custom.name,
v1model.algorithm.random.name, v1model.algorithm.identity.name,
v1model.algorithm.csum16.name, v1model.algorithm.xor16.name};
if (mc->arguments->size() != 5) {
modelError("Expected 5 arguments for %1%", mc);
return nullptr;
}
auto primitive = mkPrimitive("modify_field_with_hash_based_offset");
auto parameters = mkParameters(primitive);
primitive->emplace_non_null("source_info", s->sourceInfoJsonObj());
auto dest = ctxt->conv->convert(mc->arguments->at(0)->expression);
parameters->append(dest);
auto base = ctxt->conv->convert(mc->arguments->at(2)->expression);
parameters->append(base);
auto calculation = new Util::JsonObject();
auto ei = P4::EnumInstance::resolve(mc->arguments->at(1)->expression, ctxt->typeMap);
CHECK_NULL(ei);
if (supportedHashAlgorithms.find(ei->name) == supportedHashAlgorithms.end()) {
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET, "%1%: unexpected algorithm", ei->name);
return nullptr;
}
auto fields = mc->arguments->at(3);
auto calcName = ctxt->createCalculation(ei->name, fields->expression, ctxt->json->calculations,
false, nullptr);
calculation->emplace("type", "calculation");
calculation->emplace("value", calcName);
parameters->append(calculation);
auto max = ctxt->conv->convert(mc->arguments->at(4)->expression);
parameters->append(max);
return primitive;
}
Util::IJson *ExternConverter_digest::convertExternFunction(ConversionContext *ctxt,
UNUSED const P4::ExternFunction *ef,
const IR::MethodCallExpression *mc,
UNUSED const IR::StatOrDecl *s,
UNUSED const bool emitExterns) {
if (mc->arguments->size() != 2) {
modelError("Expected 2 arguments for %1%", mc);
return nullptr;
}
auto primitive = mkPrimitive("generate_digest");
auto parameters = mkParameters(primitive);
primitive->emplace_non_null("source_info", mc->sourceInfoJsonObj());
auto dest = ctxt->conv->convert(mc->arguments->at(0)->expression);
parameters->append(dest);
cstring listName = "digest";
// If we are supplied a type argument that is a named type use
// that for the list name.
if (mc->typeArguments->size() == 1) {
auto typeArg = mc->typeArguments->at(0);
if (typeArg->is<IR::Type_Name>()) {
auto origType = ctxt->refMap->getDeclaration(typeArg->to<IR::Type_Name>()->path, true);
if (!origType->is<IR::Type_Struct>()) {
modelError("%1%: expected a struct type", origType->getNode());
return nullptr;
}
auto st = origType->to<IR::Type_Struct>();
listName = st->controlPlaneName();
}
}
int id = ctxt->createFieldList(mc->arguments->at(1)->expression, listName, true);
auto cst = new IR::Constant(id);
ctxt->typeMap->setType(cst, IR::Type_Bits::get(32));
auto jcst = ctxt->conv->convert(cst);
parameters->append(jcst);
return primitive;
}
Util::IJson *ExternConverter_resubmit_preserving_field_list::convertExternFunction(
ConversionContext *ctxt, UNUSED const P4::ExternFunction *ef,
const IR::MethodCallExpression *mc, UNUSED const IR::StatOrDecl *s,
UNUSED const bool emitExterns) {
if (ctxt->blockConverted != BlockConverted::Ingress) {
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"'resubmit' can only be invoked in ingress %1%", mc);
return nullptr;
}
if (mc->arguments->size() == 1) {
auto primitive = mkPrimitive("resubmit");
auto parameters = mkParameters(primitive);
primitive->emplace_non_null("source_info", mc->sourceInfoJsonObj());
auto arg = mc->arguments->at(0);
auto cst = arg->expression->to<IR::Constant>();
if (cst == nullptr) {
modelError("%1%: expected a constant", arg);
return nullptr;
}
unsigned index = cst->asUnsigned();
int id = getFieldListById(ctxt, index);
cst = new IR::Constant(id);
ctxt->typeMap->setType(cst, IR::Type_Bits::get(32));
auto jcst = ctxt->conv->convert(cst);
parameters->append(jcst);
return primitive;
}
modelError("Expected 0 or 1 arguments for %1%", mc);
return nullptr;
}
Util::IJson *ExternConverter_recirculate_preserving_field_list::convertExternFunction(
ConversionContext *ctxt, UNUSED const P4::ExternFunction *ef,
const IR::MethodCallExpression *mc, UNUSED const IR::StatOrDecl *s,
UNUSED const bool emitExterns) {
if (ctxt->blockConverted != BlockConverted::Egress) {
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"'resubmit' can only be invoked in egress %1%", mc);
return nullptr;
}
if (mc->arguments->size() == 1) {
auto primitive = mkPrimitive("recirculate");
auto parameters = mkParameters(primitive);
primitive->emplace_non_null("source_info", mc->sourceInfoJsonObj());
auto arg = mc->arguments->at(0);
auto cst = arg->expression->to<IR::Constant>();
if (cst == nullptr) {
modelError("%1%: must be a constant", arg);
return nullptr;
}
unsigned index = cst->asUnsigned();
int id = getFieldListById(ctxt, index);
cst = new IR::Constant(id);
ctxt->typeMap->setType(cst, IR::Type_Bits::get(32));
auto jcst = ctxt->conv->convert(cst);
parameters->append(jcst);
return primitive;
} else {
modelError("Expected 1 argument for %1%", mc);
return nullptr;
}
}
Util::IJson *ExternConverter_mark_to_drop::convertExternFunction(
ConversionContext *ctxt, UNUSED const P4::ExternFunction *ef,
const IR::MethodCallExpression *mc, UNUSED const IR::StatOrDecl *s,
UNUSED const bool emitExterns) {
if (mc->arguments->size() != 1) {
modelError("Expected 1 argument for %1%", mc);
return nullptr;
}
auto primitive = mkPrimitive("mark_to_drop");
auto params = mkParameters(primitive);
auto dest = ctxt->conv->convert(mc->arguments->at(0)->expression);
params->append(dest);
primitive->emplace_non_null("source_info", s->sourceInfoJsonObj());
return primitive;
}
Util::IJson *ExternConverter_random::convertExternFunction(ConversionContext *ctxt,
UNUSED const P4::ExternFunction *ef,
const IR::MethodCallExpression *mc,
UNUSED const IR::StatOrDecl *s,
UNUSED const bool emitExterns) {
if (mc->arguments->size() != 3) {
modelError("Expected 3 arguments for %1%", mc);
return nullptr;
}
auto primitive = mkPrimitive(v1model.random.modify_field_rng_uniform.name);
auto params = mkParameters(primitive);
primitive->emplace_non_null("source_info", mc->sourceInfoJsonObj());
auto dest = ctxt->conv->convert(mc->arguments->at(0)->expression);
auto lo = ctxt->conv->convert(mc->arguments->at(1)->expression);
auto hi = ctxt->conv->convert(mc->arguments->at(2)->expression);
params->append(dest);
params->append(lo);
params->append(hi);
return primitive;
}
Util::IJson *ExternConverter_truncate::convertExternFunction(UNUSED ConversionContext *ctxt,
UNUSED const P4::ExternFunction *ef,
const IR::MethodCallExpression *mc,
UNUSED const IR::StatOrDecl *s,
UNUSED const bool emitExterns) {
if (mc->arguments->size() != 1) {
modelError("Expected 1 arguments for %1%", mc);
return nullptr;
}
auto primitive = mkPrimitive(v1model.truncate.name);
auto params = mkParameters(primitive);
primitive->emplace_non_null("source_info", mc->sourceInfoJsonObj());
auto len = ctxt->conv->convert(mc->arguments->at(0)->expression);
params->append(len);
return primitive;
}
Util::IJson *ExternConverter_counter::convertExternObject(ConversionContext *ctxt,
const P4::ExternMethod *em,
const IR::MethodCallExpression *mc,
UNUSED const IR::StatOrDecl *s,
UNUSED const bool &emitExterns) {
if (mc->arguments->size() != 1) {
modelError("Expected 1 argument for %1%", mc);
return nullptr;
}
auto primitive = mkPrimitive("count");
auto parameters = mkParameters(primitive);
primitive->emplace_non_null("source_info", s->sourceInfoJsonObj());
auto ctr = new Util::JsonObject();
ctr->emplace("type", "counter_array");
ctr->emplace("value", em->object->controlPlaneName());
parameters->append(ctr);
auto index = ctxt->conv->convert(mc->arguments->at(0)->expression);
parameters->append(index);
return primitive;
}
void ExternConverter_counter::convertExternInstance(ConversionContext *ctxt,
const IR::Declaration *c,
const IR::ExternBlock *eb,
UNUSED const bool &emitExterns) {
auto inst = c->to<IR::Declaration_Instance>();
cstring name = inst->controlPlaneName();
auto jctr = new Util::JsonObject();
jctr->emplace("name", name);
jctr->emplace("id", nextId("counter_arrays"));
jctr->emplace_non_null("source_info", eb->sourceInfoJsonObj());
auto sz = eb->findParameterValue(v1model.counter.sizeParam.name);
CHECK_NULL(sz);
if (!sz->is<IR::Constant>()) {
modelError("%1%: expected a constant", sz->getNode());
return;
}
jctr->emplace("size", sz->to<IR::Constant>()->value);
jctr->emplace("is_direct", false);
ctxt->json->counters->append(jctr);
}
Util::IJson *ExternConverter_meter::convertExternObject(ConversionContext *ctxt,
const P4::ExternMethod *em,
const IR::MethodCallExpression *mc,
UNUSED const IR::StatOrDecl *s,
UNUSED const bool &emitExterns) {
if (mc->arguments->size() != 2) {
modelError("Expected 2 arguments for %1%", mc);
return nullptr;
}
auto primitive = mkPrimitive("execute_meter");
auto parameters = mkParameters(primitive);
primitive->emplace_non_null("source_info", s->sourceInfoJsonObj());
auto mtr = new Util::JsonObject();
mtr->emplace("type", "meter_array");
mtr->emplace("value", em->object->controlPlaneName());
parameters->append(mtr);
auto index = ctxt->conv->convert(mc->arguments->at(0)->expression);
parameters->append(index);
auto result = ctxt->conv->convert(mc->arguments->at(1)->expression);
parameters->append(result);
return primitive;
}
void ExternConverter_meter::convertExternInstance(ConversionContext *ctxt, const IR::Declaration *c,
const IR::ExternBlock *eb,
UNUSED const bool &emitExterns) {
auto inst = c->to<IR::Declaration_Instance>();
cstring name = inst->controlPlaneName();
auto jmtr = new Util::JsonObject();
jmtr->emplace("name", name);
jmtr->emplace("id", nextId("meter_arrays"));
jmtr->emplace_non_null("source_info", eb->sourceInfoJsonObj());
jmtr->emplace("is_direct", false);
auto sz = eb->findParameterValue(v1model.meter.sizeParam.name);
CHECK_NULL(sz);
if (!sz->is<IR::Constant>()) {
modelError("%1%: expected a constant", sz->getNode());
return;
}
jmtr->emplace("size", sz->to<IR::Constant>()->value);
jmtr->emplace("rate_count", 2);
auto mkind = eb->findParameterValue(v1model.meter.typeParam.name);
CHECK_NULL(mkind);
if (!mkind->is<IR::Declaration_ID>()) {
modelError("%1%: expected a member", mkind->getNode());
return;
}
cstring mkind_name = mkind->to<IR::Declaration_ID>()->name;
cstring type = "?";
if (mkind_name == v1model.meter.meterType.packets.name)
type = "packets";
else if (mkind_name == v1model.meter.meterType.bytes.name)
type = "bytes";
else
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET, "Unexpected meter type %1%",
mkind->getNode());
jmtr->emplace("type", type);
ctxt->json->meter_arrays->append(jmtr);
}
Util::IJson *ExternConverter_register::convertExternObject(ConversionContext *ctxt,
const P4::ExternMethod *em,
const IR::MethodCallExpression *mc,
UNUSED const IR::StatOrDecl *s,
UNUSED const bool &emitExterns) {
if (mc->arguments->size() != 2) {
modelError("Expected 2 arguments for %1%", mc);
return nullptr;
}
auto reg = new Util::JsonObject();
reg->emplace("type", "register_array");
cstring name = em->object->controlPlaneName();
reg->emplace("value", name);
if (em->method->name == v1model.registers.read.name) {
auto primitive = mkPrimitive("register_read");
auto parameters = mkParameters(primitive);
primitive->emplace_non_null("source_info", s->sourceInfoJsonObj());
auto dest = ctxt->conv->convert(mc->arguments->at(0)->expression);
parameters->append(dest);
parameters->append(reg);
auto index = ctxt->conv->convert(mc->arguments->at(1)->expression);
parameters->append(index);
return primitive;
} else if (em->method->name == v1model.registers.write.name) {
auto primitive = mkPrimitive("register_write");
auto parameters = mkParameters(primitive);
primitive->emplace_non_null("source_info", s->sourceInfoJsonObj());
parameters->append(reg);
auto index = ctxt->conv->convert(mc->arguments->at(0)->expression);
parameters->append(index);
auto value = ctxt->conv->convert(mc->arguments->at(1)->expression);
parameters->append(value);
return primitive;
}
return nullptr;
}
void ExternConverter_register::convertExternInstance(ConversionContext *ctxt,
const IR::Declaration *c,
const IR::ExternBlock *eb,
UNUSED const bool &emitExterns) {
auto inst = c->to<IR::Declaration_Instance>();
cstring name = inst->controlPlaneName();
auto jreg = new Util::JsonObject();
jreg->emplace("name", name);
jreg->emplace("id", nextId("register_arrays"));
jreg->emplace_non_null("source_info", eb->sourceInfoJsonObj());
auto sz = eb->findParameterValue(v1model.registers.sizeParam.name);
CHECK_NULL(sz);
if (!sz->is<IR::Constant>()) {
modelError("%1%: expected a constant", sz->getNode());
return;
}
if (sz->to<IR::Constant>()->value == 0)
error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"%1%: direct registers are not supported in bmv2", inst);
jreg->emplace("size", sz->to<IR::Constant>()->value);
if (auto st = eb->instanceType->to<IR::Type_SpecializedCanonical>()) {
if (st->arguments->size() < 1 || st->arguments->size() > 2) {
modelError("%1%: expected 1 or 2 type arguments", st);
return;
}
auto regType = st->arguments->at(0);
if (!regType->is<IR::Type_Bits>()) {
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"%1%: Only registers with bit or int types are currently supported", eb);
return;
}
unsigned width = regType->width_bits();
if (width == 0) {
::error(ErrorType::ERR_EXPRESSION, "%1%: unknown width", st->arguments->at(0));
return;
}
jreg->emplace("bitwidth", width);
ctxt->json->register_arrays->append(jreg);
} else {
modelError("%1%: Expected a generic specialized type", eb->instanceType);
}
}
Util::IJson *ExternConverter_direct_counter::convertExternObject(UNUSED ConversionContext *ctxt,
UNUSED const P4::ExternMethod *em,
const IR::MethodCallExpression *mc,
UNUSED const IR::StatOrDecl *s,
UNUSED const bool &emitExterns) {
if (mc->arguments->size() != 0) {
modelError("Expected 0 argument for %1%", mc);
return nullptr;
}
// Do not generate any code for this operation
return nullptr;
}
void ExternConverter_direct_counter::convertExternInstance(ConversionContext *ctxt,
const IR::Declaration *c,
const IR::ExternBlock *eb,
UNUSED const bool &emitExterns) {
auto inst = c->to<IR::Declaration_Instance>();
cstring name = inst->controlPlaneName();
auto it = ctxt->structure->directCounterMap.find(name);
if (it == ctxt->structure->directCounterMap.end()) {
::warning(ErrorType::WARN_UNUSED, "%1%: Direct counter not used; ignoring", inst);
} else {
auto jctr = new Util::JsonObject();
jctr->emplace("name", name);
jctr->emplace("id", nextId("counter_arrays"));
jctr->emplace("is_direct", true);
jctr->emplace("binding", it->second->controlPlaneName());
jctr->emplace_non_null("source_info", eb->sourceInfoJsonObj());
ctxt->json->counters->append(jctr);
}
}
Util::IJson *ExternConverter_direct_meter::convertExternObject(ConversionContext *ctxt,
const P4::ExternMethod *em,
const IR::MethodCallExpression *mc,
UNUSED const IR::StatOrDecl *s,
UNUSED const bool &emitExterns) {
if (mc->arguments->size() != 1) {
modelError("Expected 1 argument for %1%", mc);
return nullptr;
}
auto dest = mc->arguments->at(0);
ctxt->structure->directMeterMap.setDestination(em->object, dest->expression);
// Do not generate any code for this operation
return nullptr;
}
void ExternConverter_direct_meter::convertExternInstance(ConversionContext *ctxt,
const IR::Declaration *c,
const IR::ExternBlock *eb,
UNUSED const bool &emitExterns) {
auto inst = c->to<IR::Declaration_Instance>();
cstring name = inst->controlPlaneName();
auto info = ctxt->structure->directMeterMap.getInfo(c);
if (info == nullptr) {
// This can happen if a direct_meter object is constructed,
// but then not associated with any table. A warning message
// is already generated elsewhere regarding this. We should
// not crash here.
return;
}
if (info->table == nullptr) {
// This can happen if a direct_meter object is constructed,
// and:
// + a read call is made in a table's action for the direct
// meter, but the table has no 'meters = my_meter;' table
// property.
// + the meter is incorrectly associated with a table via a
// property like 'counters = my_meter;'.
::error(ErrorType::ERR_INVALID,
"%1%: direct meter is not associated with any table"
" via 'meters' table property",
inst);
return;
}
CHECK_NULL(info->destinationField);
auto jmtr = new Util::JsonObject();
jmtr->emplace("name", name);
jmtr->emplace("id", nextId("meter_arrays"));
jmtr->emplace_non_null("source_info", eb->sourceInfoJsonObj());
jmtr->emplace("is_direct", true);
jmtr->emplace("rate_count", 2);
auto mkind = eb->findParameterValue(v1model.directMeter.typeParam.name);
CHECK_NULL(mkind);
if (!mkind->is<IR::Declaration_ID>()) {
modelError("%1%: expected a member", mkind->getNode());
return;
}
cstring mkind_name = mkind->to<IR::Declaration_ID>()->name;
cstring type = "?";
if (mkind_name == v1model.meter.meterType.packets.name) {
type = "packets";
} else if (mkind_name == v1model.meter.meterType.bytes.name) {
type = "bytes";
} else {
modelError("%1%: unexpected meter type", mkind->getNode());
return;
}
jmtr->emplace("type", type);
jmtr->emplace("size", info->tableSize);
cstring tblname = info->table->controlPlaneName();
jmtr->emplace("binding", tblname);
auto result = ctxt->conv->convert(info->destinationField);
jmtr->emplace("result_target", result->to<Util::JsonObject>()->get("value"));
ctxt->json->meter_arrays->append(jmtr);
}
void ExternConverter_action_profile::convertExternInstance(ConversionContext *ctxt,
const IR::Declaration *c,
const IR::ExternBlock *eb,
UNUSED const bool &emitExterns) {
auto inst = c->to<IR::Declaration_Instance>();
cstring name = inst->controlPlaneName();
// Might call this multiple times if the selector/profile is used more than
// once in a pipeline, so only add it to the action_profiles once
if (BMV2::JsonObjects::find_object_by_name(ctxt->action_profiles, name)) return;
auto action_profile = new Util::JsonObject();
action_profile->emplace("name", name);
action_profile->emplace("id", nextId("action_profiles"));
action_profile->emplace_non_null("source_info", eb->sourceInfoJsonObj());
auto add_size = [&action_profile, &eb](const cstring &pname) {
auto sz = eb->findParameterValue(pname);
BUG_CHECK(sz, "%1%Invalid declaration of extern ctor: no size param",
eb->constructor->srcInfo);
if (!sz->is<IR::Constant>()) {
::error(ErrorType::ERR_EXPECTED, "%1%: expected a constant", sz);
return;
}
action_profile->emplace("max_size", sz->to<IR::Constant>()->value);
};
if (eb->type->name == v1model.action_profile.name) {
add_size(v1model.action_profile.sizeParam.name);
} else {
add_size(v1model.action_selector.sizeParam.name);
auto selector = new Util::JsonObject();
auto hash = eb->findParameterValue(v1model.action_selector.algorithmParam.name);
if (!hash->is<IR::Declaration_ID>()) {
modelError("%1%: expected a member", hash->getNode());
return;
}
auto algo = ExternConverter::convertHashAlgorithm(hash->to<IR::Declaration_ID>()->name);
selector->emplace("algo", algo);
auto input = ctxt->get_selector_input(inst);
if (input == nullptr) {
// the selector is never used by any table, we cannot figure out its
// input and therefore cannot include it in the JSON
::warning(ErrorType::WARN_UNUSED,
"Action selector '%1%' is never referenced by a table "
"and cannot be included in bmv2 JSON",
c);
return;
}
auto j_input = mkArrayField(selector, "input");
for (auto expr : *input) {
auto jk = ctxt->conv->convert(expr);
j_input->append(jk);
}
action_profile->emplace("selector", selector);
}
ctxt->action_profiles->append(action_profile);
}
/// Action selector conversion is the same as action profile.
void ExternConverter_action_selector::convertExternInstance(ConversionContext *ctxt,
const IR::Declaration *c,
const IR::ExternBlock *eb,
UNUSED const bool &emitExterns) {
auto inst = c->to<IR::Declaration_Instance>();
cstring name = inst->controlPlaneName();
// Might call this multiple times if the selector/profile is used more than
// once in a pipeline, so only add it to the action_profiles once
if (BMV2::JsonObjects::find_object_by_name(ctxt->action_profiles, name)) return;
auto action_profile = new Util::JsonObject();
action_profile->emplace("name", name);
action_profile->emplace("id", nextId("action_profiles"));
action_profile->emplace_non_null("source_info", eb->sourceInfoJsonObj());
auto add_size = [&action_profile, &eb](const cstring &pname) {
auto sz = eb->findParameterValue(pname);
BUG_CHECK(sz, "%1%Invalid declaration of extern ctor: no size param",
eb->constructor->srcInfo);
if (!sz->is<IR::Constant>()) {
::error(ErrorType::ERR_EXPECTED, "%1%: expected a constant", sz);
return;
}
action_profile->emplace("max_size", sz->to<IR::Constant>()->value);
};
if (eb->type->name == v1model.action_profile.name) {
add_size(v1model.action_profile.sizeParam.name);
} else {
add_size(v1model.action_selector.sizeParam.name);
auto selector = new Util::JsonObject();
auto hash = eb->findParameterValue(v1model.action_selector.algorithmParam.name);
if (!hash->is<IR::Declaration_ID>()) {
modelError("%1%: expected a member", hash->getNode());
return;
}
auto algo = ExternConverter::convertHashAlgorithm(hash->to<IR::Declaration_ID>()->name);
selector->emplace("algo", algo);
auto input = ctxt->get_selector_input(inst);
if (input == nullptr) {
// the selector is never used by any table, we cannot figure out its
// input and therefore cannot include it in the JSON
::warning(ErrorType::WARN_UNUSED,
"Action selector '%1%' is never referenced by a table "
"and cannot be included in bmv2 JSON",
c);
return;
}
auto j_input = mkArrayField(selector, "input");
for (auto expr : *input) {
auto jk = ctxt->conv->convert(expr);
j_input->append(jk);
}
action_profile->emplace("selector", selector);
}
ctxt->action_profiles->append(action_profile);
}
Util::IJson *ExternConverter_log_msg::convertExternFunction(ConversionContext *ctxt,
UNUSED const P4::ExternFunction *ef,
const IR::MethodCallExpression *mc,
const IR::StatOrDecl *s,
UNUSED const bool emitExterns) {
if (mc->arguments->size() != 2 && mc->arguments->size() != 1) {
modelError("Expected 1 or 2 arguments for %1%", mc);
return nullptr;
}
auto primitive = mkPrimitive("log_msg");
auto params = mkParameters(primitive);
primitive->emplace_non_null("source_info", s->sourceInfoJsonObj());
auto paramsValue = new Util::JsonObject();
paramsValue->emplace("type", "parameters_vector");
auto str = ctxt->conv->convert(mc->arguments->at(0)->expression);
params->append(str);
if (mc->arguments->size() == 2) {
auto arg1 = mc->arguments->at(1)->expression;
// this must be a list expression, with all components
// evaluating to integral types.
auto le = convertToList(arg1, ctxt->typeMap);
if (!le) {
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"%1%: Second argument must be a list expression: %2%", mc, arg1);
return primitive;
}
auto arr = new Util::JsonArray();
for (auto v : le->components) {
auto tf = ctxt->typeMap->getType(v);
if (!tf->is<IR::Type_Bits>() && !tf->is<IR::Type_Boolean>() &&
!tf->is<IR::Type_Error>()) {
::error(ErrorType::ERR_UNSUPPORTED_ON_TARGET,
"%1%: only integral values supported for logged values", mc);
return primitive;
}
auto val = ctxt->conv->convert(v, false, true, true);
arr->append(val);
}
paramsValue->emplace("value", arr);
} else {
auto tmp = new Util::JsonObject();
paramsValue->emplace("value", tmp);
}
params->append(paramsValue);
return primitive;
}
void SimpleSwitchBackend::modelError(const char *format, const IR::Node *node) const {
::error(ErrorType::ERR_MODEL,
(cstring("%1%") + format + "\nAre you using an up-to-date v1model.p4?").c_str(), node);
}
cstring SimpleSwitchBackend::createCalculation(cstring algo, const IR::Expression *fields,
Util::JsonArray *calculations, bool withPayload,
const IR::Node *sourcePositionNode = nullptr) {
cstring calcName = refMap->newName("calc_");
auto calc = new Util::JsonObject();
calc->emplace("name", calcName);
calc->emplace("id", nextId("calculations"));
if (sourcePositionNode != nullptr)
calc->emplace_non_null("source_info", sourcePositionNode->sourceInfoJsonObj());
calc->emplace("algo", algo);
fields = convertToList(fields, typeMap);
if (!fields) {
modelError("%1%: expected a struct", fields);
return calcName;
}
auto jright = conv->convertWithConstantWidths(fields);
if (withPayload) {
auto array = jright->to<Util::JsonArray>();
BUG_CHECK(array, "expected a JSON array");
auto payload = new Util::JsonObject();
payload->emplace("type", "payload");
payload->emplace("value", (Util::IJson *)nullptr);
array->append(payload);
}
calc->emplace("input", jright);
calculations->append(calc);
return calcName;
}
namespace {
class EnsureExpressionIsSimple : public Inspector {
cstring block;
public:
explicit EnsureExpressionIsSimple(cstring block) : block(block) {
setName("EnsureExpressionIsSimple");
}
bool preorder(const IR::Expression *expression) override {
::error(ErrorType::ERR_UNSUPPORTED, "%1%: Computations are not supported in %2%",
expression, block);
return false;
}
bool preorder(const IR::StructExpression *) override { return true; }
bool preorder(const IR::PathExpression *) override { return true; }
bool preorder(const IR::Member *) override { return true; }
bool preorder(const IR::ListExpression *) override { return true; }
bool preorder(const IR::Constant *) override { return true; }
bool preorder(const IR::ArrayIndex *) override { return true; }
};
} // namespace
void SimpleSwitchBackend::convertChecksum(const IR::BlockStatement *block,
Util::JsonArray *checksums, Util::JsonArray *calculations,
bool verify) {
if (errorCount() > 0) return;
for (auto stat : block->components) {
if (auto blk = stat->to<IR::BlockStatement>()) {
convertChecksum(blk, checksums, calculations, verify);
continue;
} else if (auto mc = stat->to<IR::MethodCallStatement>()) {
auto mi = P4::MethodInstance::resolve(mc, refMap, typeMap);
if (auto em = mi->to<P4::ExternFunction>()) {
cstring functionName = em->method->name.name;
if ((verify && (functionName == v1model.verify_checksum.name ||
functionName == v1model.verify_checksum_with_payload.name)) ||
(!verify && (functionName == v1model.update_checksum.name ||
functionName == v1model.update_checksum_with_payload.name))) {
bool usePayload = functionName.endsWith("_with_payload");
if (mi->expr->arguments->size() != 4) {
modelError("%1%: Expected 4 arguments", mc);
return;
}
auto cksum = new Util::JsonObject();
auto ei =
P4::EnumInstance::resolve(mi->expr->arguments->at(3)->expression, typeMap);
cstring algo = ExternConverter::convertHashAlgorithm(ei->name);
auto calcExpr = mi->expr->arguments->at(1)->expression;
EnsureExpressionIsSimple eeis(verify ? v1model.verify_checksum.name
: v1model.update_checksum.name);
(void)calcExpr->apply(eeis);
cstring calcName =
createCalculation(algo, calcExpr, calculations, usePayload, mc);
cksum->emplace("name", refMap->newName("cksum_"));
cksum->emplace("id", nextId("checksums"));
cksum->emplace_non_null("source_info", stat->sourceInfoJsonObj());
auto jleft = conv->convert(mi->expr->arguments->at(2)->expression);
cksum->emplace("target", jleft->to<Util::JsonObject>()->get("value"));
cksum->emplace("type", "generic");
cksum->emplace("calculation", calcName);
cksum->emplace("verify", verify);
cksum->emplace("update", !verify);
auto ifcond =
conv->convert(mi->expr->arguments->at(0)->expression, true, false);
cksum->emplace("if_cond", ifcond);
checksums->append(cksum);
continue;
}
}
}
::error(ErrorType::ERR_UNSUPPORTED, "%1%: Only calls to %2% or %3% allowed", stat,
verify ? v1model.verify_checksum.name : v1model.update_checksum.name,
verify ? v1model.verify_checksum_with_payload.name