-
Notifications
You must be signed in to change notification settings - Fork 445
/
p4RuntimeSerializer.cpp
1686 lines (1508 loc) · 74.8 KB
/
p4RuntimeSerializer.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 "p4RuntimeSerializer.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wpedantic"
#include <google/protobuf/text_format.h>
#include <google/protobuf/util/json_util.h>
#pragma GCC diagnostic pop
#include <iostream>
#include <iterator>
#include <optional>
#include <set>
#include <unordered_map>
#include <utility>
#include <vector>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wpedantic"
#include "p4/config/v1/p4info.pb.h"
#include "p4/v1/p4runtime.pb.h"
#pragma GCC diagnostic pop
#include "control-plane/bytestrings.h"
#include "control-plane/flattenHeader.h"
#include "control-plane/p4RuntimeAnnotations.h"
#include "control-plane/p4RuntimeArchHandler.h"
#include "control-plane/p4RuntimeArchStandard.h"
#include "control-plane/p4RuntimeSymbolTable.h"
#include "control-plane/typeSpecConverter.h"
#include "frontends/common/options.h"
#include "frontends/common/resolveReferences/referenceMap.h"
#include "frontends/p4/coreLibrary.h"
#include "frontends/p4/enumInstance.h"
#include "frontends/p4/evaluator/evaluator.h"
#include "frontends/p4/externInstance.h"
// TODO(antonin): this include should go away when we cleanup getMatchFields
// and tableNeedsPriority implementations.
#include "frontends/p4-14/fromv1.0/v1model.h"
#include "frontends/p4/methodInstance.h"
#include "frontends/p4/typeChecking/typeChecker.h"
#include "frontends/p4/typeMap.h"
#include "ir/ir.h"
#include "lib/error.h"
#include "lib/log.h"
#include "lib/nullstream.h"
namespace p4v1 = ::p4::v1;
namespace p4configv1 = ::p4::config::v1;
namespace P4 {
/** \defgroup control_plane Control Plane API Generation */
/** \addtogroup control_plane
* @{
*/
/// TODO(antonin): High level goals of the generator go here!!
namespace ControlPlaneAPI {
using Helpers::addAnnotations;
using Helpers::addDocumentation;
using Helpers::setPreamble;
/// @return the value of @item's explicit name annotation, if it has one. We use
/// this rather than e.g. controlPlaneName() when we want to prevent any
/// fallback.
static std::optional<cstring> explicitNameAnnotation(const IR::IAnnotated *item) {
auto *anno = item->getAnnotation(IR::Annotation::nameAnnotation);
if (!anno) return std::nullopt;
const auto &expr = anno->getExpr();
if (expr.size() != 1) {
::P4::error(ErrorType::ERR_INVALID, "A %1% annotation must have one argument", anno);
return std::nullopt;
}
auto *str = expr[0]->to<IR::StringLiteral>();
if (!str) {
::P4::error(ErrorType::ERR_INVALID, "An %1% annotation's argument must be a string", anno);
return std::nullopt;
}
return str->value;
}
namespace writers {
using google::protobuf::Message;
using google::protobuf::util::JsonPrintOptions;
/// Serialize the protobuf @message to @destination in the binary protocol
/// buffers format.
static bool writeTo(const Message &message, std::ostream *destination) {
CHECK_NULL(destination);
if (!message.SerializeToOstream(destination)) return false;
destination->flush();
return true;
}
/// Serialize the protobuf @message to @destination in the JSON protocol buffers
/// format. This is intended for debugging and testing.
static bool writeJsonTo(const Message &message, std::ostream *destination,
const JsonPrintOptions &options) {
using namespace google::protobuf::util;
CHECK_NULL(destination);
std::string output;
if (!MessageToJsonString(message, &output, options).ok()) {
::P4::error(ErrorType::ERR_IO, "Failed to serialize protobuf message to JSON");
return false;
}
*destination << output;
if (!destination->good()) {
::P4::error(ErrorType::ERR_IO, "Failed to write JSON protobuf message to the output");
return false;
}
destination->flush();
return true;
}
/// Serialize the protobuf @message to @destination in the text protocol buffers
/// format. This is intended for debugging and testing.
static bool writeTextTo(const Message &message, std::ostream *destination) {
CHECK_NULL(destination);
// According to the protobuf documentation, it would be better to use Print
// with a FileOutputStream object for performance reasons. However all we
// have here is a std::ostream and performance is not a concern.
std::string output;
google::protobuf::TextFormat::Printer textPrinter;
// set to expand google.protobuf.Any payloads
textPrinter.SetExpandAny(true);
*destination << "# proto-file: " << message.GetDescriptor()->file()->name() << "\n";
*destination << "# proto-message: " << message.GetTypeName() << "\n\n";
if (!textPrinter.PrintToString(message, &output)) {
::P4::error(ErrorType::ERR_IO, "Failed to serialize protobuf message to text");
return false;
}
*destination << output;
if (!destination->good()) {
::P4::error(ErrorType::ERR_IO, "Failed to write text protobuf message to the output");
return false;
}
destination->flush();
return true;
}
} // namespace writers
/// The information about a default action which is needed to serialize it.
struct DefaultAction {
// The action declaration
const IR::P4Action *action;
// Is this a const default action?
const bool isConst;
// The arguments for this action.
const IR::Vector<IR::Argument> *arguments;
};
/// The information about a match field which is needed to serialize it.
struct MatchField {
using MatchType = p4configv1::MatchField::MatchType;
using MatchTypes = p4configv1::MatchField; // Make short enum names visible.
const cstring name; // The fully qualified external name of this field.
const p4rt_id_t id; // The id for this field - either user-provided or auto-allocated.
const MatchType type; // The match algorithm - exact, ternary, range, etc.
const cstring other_match_type; // If the match type is an arch-specific one
// in this case, type must be MatchTypes::UNSPECIFIED
const uint32_t bitwidth; // How wide this field is.
const IR::IAnnotated *annotations; // If non-null, any annotations applied
// to this field.
const cstring type_name; // Optional field used when field is Type_Newtype.
};
struct ActionRef {
const cstring name; // The fully qualified external name of the action.
const IR::IAnnotated *annotations; // If non-null, any annotations applied to this action
// reference in the table declaration.
};
/// FieldIdAllocator is used to allocate ids for non top-level P4Info objects
/// that need them (match fields, action parameters, packet IO metadata
/// fields). Some of these ids can come from the P4 program (@id annotation),
/// the rest is auto-generated.
template <typename T>
class FieldIdAllocator {
public:
// Parameters must be iterators of Ts.
// All the user allocated ids must be provided in one-shot, which is why we
// require all objects to be provided in the constructor.
template <typename It>
FieldIdAllocator(
It begin, It end,
typename std::enable_if<
std::is_same<typename std::iterator_traits<It>::value_type, T>::value>::type * = 0) {
// first pass: user-assigned ids
for (auto it = begin; it != end; ++it) {
auto id = getIdAnnotation(*it);
if (!id) continue;
if (*id == 0) {
::P4::error(ErrorType::ERR_INVALID, "%1%: 0 is not a valid @id value", *it);
} else if (assignedIds.count(*id) > 0) {
::P4::error(ErrorType::ERR_DUPLICATE, "%1%: @id %2% is used multiple times", *it,
*id);
}
idMapping[*it] = *id;
assignedIds.insert(*id);
}
// second pass: allocate missing ids
// in the absence of any user-provided @id, ids will be allocated
// sequentially, starting at 1.
p4rt_id_t index = 1;
for (auto it = begin; it != end; ++it) {
if (idMapping.find(*it) != idMapping.end()) {
index++;
continue;
}
while (assignedIds.count(index) > 0) {
index++;
BUG_CHECK(index > 0, "Cannot allocate default id for field");
}
idMapping[*it] = index;
assignedIds.insert(index);
}
}
p4rt_id_t getId(T v) {
auto it = idMapping.find(v);
BUG_CHECK(it != idMapping.end(), "Missing id allocation");
return it->second;
}
private:
std::set<p4rt_id_t> assignedIds;
std::map<T, p4rt_id_t> idMapping;
};
/// @return @table's default action, if it has one, or std::nullopt otherwise.
static std::optional<DefaultAction> getDefaultAction(const IR::P4Table *table, ReferenceMap *refMap,
TypeMap *typeMap) {
// not using getDefaultAction() here as I actually need the property IR node
// to check if the default action is constant.
const auto *defaultActionProperty =
table->properties->getProperty(IR::TableProperties::defaultActionPropertyName);
if (defaultActionProperty == nullptr) {
::P4::error(ErrorType::ERR_EXPECTED, "Expected table %1% to have a default action", table);
return std::nullopt;
}
if (!defaultActionProperty->value->is<IR::ExpressionValue>()) {
::P4::error(ErrorType::ERR_EXPECTED, "Expected an action: %1%", defaultActionProperty);
return std::nullopt;
}
const auto *expr = defaultActionProperty->value->to<IR::ExpressionValue>()->expression;
cstring actionName;
const IR::Vector<IR::Argument> *arguments = nullptr;
const IR::P4Action *action = nullptr;
if (expr->is<IR::PathExpression>()) {
const auto *decl = refMap->getDeclaration(expr->to<IR::PathExpression>()->path, true);
action = decl->to<IR::P4Action>();
BUG_CHECK(action, "Expected an action: %1%", expr);
actionName = action->controlPlaneName();
arguments = new IR::Vector<IR::Argument>;
} else if (expr->is<IR::MethodCallExpression>()) {
const auto *callExpr = expr->to<IR::MethodCallExpression>();
auto *instance = MethodInstance::resolve(callExpr, refMap, typeMap);
BUG_CHECK(instance->is<P4::ActionCall>(), "Expected an action: %1%", expr);
actionName = instance->to<P4::ActionCall>()->action->controlPlaneName();
action = instance->to<P4::ActionCall>()->action;
arguments = callExpr->arguments;
} else {
::P4::error(ErrorType::ERR_UNEXPECTED,
"Unexpected expression in default action for table %1%: %2%",
table->controlPlaneName(), expr);
return std::nullopt;
}
return DefaultAction{action, defaultActionProperty->isConstant, arguments};
}
/// @return true if @table has a 'const entries' property.
static bool getConstTable(const IR::P4Table *table) {
BUG_CHECK(table != nullptr, "Failed precondition for getConstTable");
auto ep = table->properties->getProperty(IR::TableProperties::entriesPropertyName);
if (ep == nullptr) return false;
BUG_CHECK(ep->value->is<IR::EntriesList>(), "Invalid 'entries' property");
return ep->isConstant;
}
/// @return true if @table has an 'entries' or 'const entries'
/// property, and there is at least one entry.
static bool getHasInitialEntries(const IR::P4Table *table) {
BUG_CHECK(table != nullptr, "Failed precondition for getHasInitialEntries");
auto entriesList = table->getEntries();
if (entriesList == nullptr) return false;
return (entriesList->entries.size() >= 1);
}
static std::vector<ActionRef> getActionRefs(const IR::P4Table *table, ReferenceMap *refMap) {
std::vector<ActionRef> actions;
for (auto action : table->getActionList()->actionList) {
auto decl = refMap->getDeclaration(action->getPath(), true);
BUG_CHECK(decl->is<IR::P4Action>(), "Not an action: '%1%'", decl);
auto name = decl->to<IR::P4Action>()->controlPlaneName();
// get annotations on the reference in the action list, not on the action declaration
auto annotations = action->to<IR::IAnnotated>();
actions.push_back(ActionRef{name, annotations});
}
return actions;
}
static cstring getMatchTypeName(const IR::PathExpression *matchPathExpr,
const ReferenceMap *refMap) {
CHECK_NULL(matchPathExpr);
auto matchTypeDecl =
refMap->getDeclaration(matchPathExpr->path, true)->to<IR::Declaration_ID>();
BUG_CHECK(matchTypeDecl != nullptr, "No declaration for match type '%1%'", matchPathExpr);
return matchTypeDecl->name.name;
}
/// maps the match type name to the corresponding P4Info MatchType enum
/// member. If the match type should not be exposed to the control plane and
/// should be ignored, std::nullopt is returned. If the match type does not
/// correspond to any standard match type known to P4Info, default enum member
/// UNSPECIFIED is returned.
static std::optional<MatchField::MatchType> getMatchType(cstring matchTypeName) {
if (matchTypeName == P4CoreLibrary::instance().exactMatch.name) {
return MatchField::MatchTypes::EXACT;
} else if (matchTypeName == P4CoreLibrary::instance().lpmMatch.name) {
return MatchField::MatchTypes::LPM;
} else if (matchTypeName == P4CoreLibrary::instance().ternaryMatch.name) {
return MatchField::MatchTypes::TERNARY;
} else if (matchTypeName == P4V1::V1Model::instance.rangeMatchType.name) {
return MatchField::MatchTypes::RANGE;
} else if (matchTypeName == P4V1::V1Model::instance.optionalMatchType.name) {
return MatchField::MatchTypes::OPTIONAL;
} else if (matchTypeName == P4V1::V1Model::instance.selectorMatchType.name) {
// Nothing to do here, we cannot even perform some sanity-checking.
return std::nullopt;
} else {
return MatchField::MatchTypes::UNSPECIFIED;
}
}
/// @return the header instance fields matched against by @table's key. The
/// fields are represented as a (fully qualified field name, match type) tuple.
static std::vector<MatchField> getMatchFields(const IR::P4Table *table, ReferenceMap *refMap,
TypeMap *typeMap,
p4configv1::P4TypeInfo *p4RtTypeInfo) {
std::vector<MatchField> matchFields;
auto key = table->getKey();
if (!key) return matchFields;
FieldIdAllocator<decltype(key->keyElements)::value_type> idAllocator(key->keyElements.begin(),
key->keyElements.end());
for (auto keyElement : key->keyElements) {
auto matchTypeName = getMatchTypeName(keyElement->matchType, refMap);
auto matchType = getMatchType(matchTypeName);
if (matchType == std::nullopt) continue;
auto id = idAllocator.getId(keyElement);
auto matchFieldName = explicitNameAnnotation(keyElement);
BUG_CHECK(bool(matchFieldName),
"Table '%1%': Match field '%2%' has no "
"@name annotation",
table->controlPlaneName(), keyElement->expression);
auto *matchFieldType = typeMap->getType(keyElement->expression->getNode(), true);
BUG_CHECK(matchFieldType != nullptr, "Couldn't determine type for key element %1%",
keyElement);
// We ignore the return type on purpose, but the call is required to update p4RtTypeInfo if
// the match field has a user-defined type.
TypeSpecConverter::convert(refMap, typeMap, matchFieldType, p4RtTypeInfo);
auto type_name = getTypeName(matchFieldType, typeMap);
int width = getTypeWidth(*matchFieldType, *typeMap);
matchFields.push_back(MatchField{*matchFieldName, id, *matchType, matchTypeName,
uint32_t(width), keyElement->to<IR::IAnnotated>(),
type_name});
}
return matchFields;
}
namespace {
// It must be an iterator type pointing to a p4info.proto message with a
// 'preamble' field of type p4configv1::Preamble. Fn is an arbitrary function
// with a single parameter of type p4configv1::Preamble.
template <typename It, typename Fn>
void forEachPreamble(It first, It last, Fn fn) {
for (It it = first; it != last; it++) fn(it->preamble());
}
} // namespace
/// An analyzer which translates the information available in the P4 IR into a
/// representation of the control plane API which is consumed by P4Runtime.
class P4RuntimeAnalyzer {
using Preamble = p4configv1::Preamble;
using P4Info = p4configv1::P4Info;
P4RuntimeAnalyzer(const P4RuntimeSymbolTable &symbols, TypeMap *typeMap, ReferenceMap *refMap,
P4RuntimeArchHandlerIface *archHandler)
: p4Info(new P4Info),
symbols(symbols),
typeMap(typeMap),
refMap(refMap),
archHandler(archHandler) {
CHECK_NULL(typeMap);
}
/// @return the P4Info message generated by this analyzer. This captures
/// P4Runtime representations of all the P4 constructs added to the control
/// plane API with the add*() methods.
const P4Info *getP4Info() const {
BUG_CHECK(p4Info != nullptr, "Didn't produce a P4Info object?");
return p4Info;
}
/// Check for duplicate names among objects of the same type in the
/// generated P4Info message and @return the number of duplicates.
template <typename T>
size_t checkForDuplicatesOfSameType(const T &objs, cstring typeName,
std::unordered_set<p4rt_id_t> *ids) const {
size_t dupCnt = 0;
std::unordered_set<std::string> names;
auto checkOne = [&dupCnt, &names, &ids, typeName](const p4configv1::Preamble &pre) {
auto pName = names.insert(pre.name());
auto pId = ids->insert(pre.id());
if (!pName.second) {
::P4::error(ErrorType::ERR_DUPLICATE,
"Name '%1%' is used for multiple %2% objects in the P4Info message",
pre.name(), typeName);
dupCnt++;
return;
}
BUG_CHECK(pId.second, "Id '%1%' is used for multiple objects in the P4Info message",
pre.id());
};
forEachPreamble(objs.cbegin(), objs.cend(), checkOne);
return dupCnt;
}
/// Check for objects with duplicate names in the generated P4Info message
/// and @return the number of duplicates.
size_t checkForDuplicates() const {
size_t dupCnt = 0;
// There is no real need to check for duplicate ids since the
// SymbolTable ensures that there are not duplicates. But it certainly
// does not hurt to it. Architecture-specific implementations may be
// misusing the SymbolTable, or bypassing it and allocating incorrect
// ids.
std::unordered_set<p4rt_id_t> ids;
// I considered using Protobuf reflection, but it didn't really make the
// code less verbose, and it certainly didn't make it easier to read.
dupCnt += checkForDuplicatesOfSameType(p4Info->tables(), "table"_cs, &ids);
dupCnt += checkForDuplicatesOfSameType(p4Info->actions(), "action"_cs, &ids);
dupCnt +=
checkForDuplicatesOfSameType(p4Info->action_profiles(), "action profile"_cs, &ids);
dupCnt += checkForDuplicatesOfSameType(p4Info->counters(), "counter"_cs, &ids);
dupCnt +=
checkForDuplicatesOfSameType(p4Info->direct_counters(), "direct counter"_cs, &ids);
dupCnt += checkForDuplicatesOfSameType(p4Info->meters(), "meter"_cs, &ids);
dupCnt += checkForDuplicatesOfSameType(p4Info->direct_meters(), "direct meter"_cs, &ids);
dupCnt += checkForDuplicatesOfSameType(p4Info->controller_packet_metadata(),
"controller packet metadata"_cs, &ids);
dupCnt += checkForDuplicatesOfSameType(p4Info->value_sets(), "value set"_cs, &ids);
dupCnt += checkForDuplicatesOfSameType(p4Info->registers(), "register"_cs, &ids);
dupCnt += checkForDuplicatesOfSameType(p4Info->digests(), "digest"_cs, &ids);
for (const auto &externType : p4Info->externs()) {
dupCnt += checkForDuplicatesOfSameType(externType.instances(),
externType.extern_type_name(), &ids);
}
return dupCnt;
}
public:
/**
* Analyze a P4 program and generate a P4Runtime control plane API.
*
* @param program The P4 program to analyze.
* @param evaluatedProgram An up-to-date evaluated version of the program.
* @param refMap An up-to-date reference map.
* @param refMap An up-to-date type map.
* @param archHandler An implementation of P4RuntimeArchHandlerIface which
* handles architecture-specific constructs (e.g. externs).
* @param arch The name of the P4_16 architecture the program was written
* against.
* @return a P4Info message representing the program's control plane API.
* Never returns null.
*/
static P4RuntimeAPI analyze(const IR::P4Program *program,
const IR::ToplevelBlock *evaluatedProgram, ReferenceMap *refMap,
TypeMap *typeMap, P4RuntimeArchHandlerIface *archHandler,
cstring arch);
void addAction(const IR::P4Action *actionDeclaration) {
if (isHidden(actionDeclaration)) return;
auto name = actionDeclaration->controlPlaneName();
auto id = symbols.getId(P4RuntimeSymbolType::P4RT_ACTION(), name);
auto annotations = actionDeclaration->to<IR::IAnnotated>();
// TODO(antonin): The compiler creates a new instance of an action for
// each table that references it; this is done to make it possible to
// optimize the actions differently depending on their context. There
// are several issues with this behavior as it stands right now:
// (1) We don't rename the actions, which means they all have the same
// id and the control plane can't distinguish between them.
// (2) No version of the P4 spec allows the user to explicitly name
// a particular table's "version" of an action, which makes it
// hard to generate useful names for the replicated variants.
// (3) We don't perform any optimizations that leverage this anyway,
// so the duplication is pointless.
// Considering these three issues together, for now the best bet seems
// to be to deduplicate the actions during serialization. If we resolve
// some of these issues, we'll want to revisit this decision.
if (serializedActions.find(id) != serializedActions.end()) return;
serializedActions.insert(id);
auto action = p4Info->add_actions();
setPreamble(action->mutable_preamble(), id, name, symbols.getAlias(name), annotations,
[this](cstring anno) { return archHandler->filterAnnotations(anno); });
// Allocate ids for all action parameters.
std::vector<const IR::Parameter *> actionParams;
for (auto actionParam : *actionDeclaration->parameters->getEnumerator()) {
actionParams.push_back(actionParam);
}
FieldIdAllocator<decltype(actionParams)::value_type> idAllocator(actionParams.begin(),
actionParams.end());
for (auto actionParam : actionParams) {
auto param = action->add_params();
auto paramName = actionParam->controlPlaneName();
auto id = idAllocator.getId(actionParam);
param->set_id(id);
param->set_name(paramName);
addAnnotations(param, actionParam->to<IR::IAnnotated>());
addDocumentation(param, actionParam->to<IR::IAnnotated>());
auto paramType = typeMap->getType(actionParam, true);
if (!paramType->is<IR::Type_Bits>() && !paramType->is<IR::Type_Boolean>() &&
!paramType->is<IR::Type_Newtype>() && !paramType->is<IR::Type_SerEnum>() &&
!paramType->is<IR::Type_Enum>()) {
::P4::error(ErrorType::ERR_TYPE_ERROR,
"Action parameter %1% has a type which is not "
"bit<>, int<>, bool, type or serializable enum",
actionParam);
continue;
}
if (!paramType->is<IR::Type_Enum>()) {
int w = getTypeWidth(*paramType, *typeMap);
param->set_bitwidth(w);
}
// We ignore the return type on purpose, but the call is required to update p4RtTypeInfo
// if the action parameter has a user-defined type.
TypeSpecConverter::convert(refMap, typeMap, paramType, p4Info->mutable_type_info());
auto type_name = getTypeName(paramType, typeMap);
if (type_name) {
auto namedType = param->mutable_type_name();
namedType->set_name(type_name);
} else if (auto e = paramType->to<IR::Type_Enum>()) {
param->mutable_type_name()->set_name(std::string(e->controlPlaneName()));
}
}
}
void addControllerHeader(const IR::Type_Header *type) {
if (isHidden(type)) return;
auto flattenedHeaderType = FlattenHeader::flatten(typeMap, type);
auto name = type->controlPlaneName();
auto id = symbols.getId(P4RuntimeSymbolType::P4RT_CONTROLLER_HEADER(), name);
auto annotations = type->to<IR::IAnnotated>();
auto controllerAnnotation = type->getAnnotation("controller_header"_cs);
CHECK_NULL(controllerAnnotation);
auto nameConstant = controllerAnnotation->getExpr(0)->to<IR::StringLiteral>();
CHECK_NULL(nameConstant);
auto controllerName = nameConstant->value;
auto header = p4Info->add_controller_packet_metadata();
// According to the P4Info specification, we use the name specified in
// the annotation for the p4info preamble, not the P4 fully-qualified
// name.
setPreamble(header->mutable_preamble(), id, controllerName /* name */,
controllerName /* alias */, annotations,
[this](cstring anno) { return archHandler->filterAnnotations(anno); });
FieldIdAllocator<decltype(flattenedHeaderType->fields)::value_type> idAllocator(
flattenedHeaderType->fields.begin(), flattenedHeaderType->fields.end());
for (auto headerField : flattenedHeaderType->fields) {
if (isHidden(headerField)) continue;
auto metadata = header->add_metadata();
auto fieldName = headerField->controlPlaneName();
auto id = idAllocator.getId(headerField);
metadata->set_id(id);
metadata->set_name(fieldName);
addAnnotations(metadata, headerField->to<IR::IAnnotated>());
auto fieldType = typeMap->getType(headerField, true);
BUG_CHECK((fieldType->is<IR::Type_Bits>() || fieldType->is<IR::Type_Newtype>() ||
fieldType->is<IR::Type_SerEnum>()),
"Header field %1% has a type which is not bit<>, "
"int<>, type, or serializable enum",
headerField);
auto w = getTypeWidth(*fieldType, *typeMap);
metadata->set_bitwidth(w);
// We ignore the return type on purpose, but the call is required to update p4RtTypeInfo
// if the header field has a user-defined type.
TypeSpecConverter::convert(refMap, typeMap, fieldType, p4Info->mutable_type_info());
auto type_name = getTypeName(fieldType, typeMap);
if (type_name) {
auto namedType = metadata->mutable_type_name();
namedType->set_name(type_name);
}
}
}
void addTable(const IR::TableBlock *tableBlock) {
CHECK_NULL(tableBlock);
auto tableDeclaration = tableBlock->container;
if (isHidden(tableDeclaration)) return;
auto tableSize = Helpers::getTableSize(tableDeclaration);
auto defaultAction = getDefaultAction(tableDeclaration, refMap, typeMap);
if (!defaultAction.has_value()) {
return;
}
auto matchFields =
getMatchFields(tableDeclaration, refMap, typeMap, p4Info->mutable_type_info());
auto actions = getActionRefs(tableDeclaration, refMap);
bool isConstTable = getConstTable(tableDeclaration);
bool hasInitialEntries = getHasInitialEntries(tableDeclaration);
auto name = archHandler->getControlPlaneName(tableBlock);
auto annotations = tableDeclaration->to<IR::IAnnotated>();
auto table = p4Info->add_tables();
setPreamble(table->mutable_preamble(),
symbols.getId(P4RuntimeSymbolType::P4RT_TABLE(), name), name,
symbols.getAlias(name), annotations,
[this](cstring anno) { return archHandler->filterAnnotations(anno); });
table->set_size(tableSize);
auto id = symbols.getId(P4RuntimeSymbolType::P4RT_ACTION(),
defaultAction->action->controlPlaneName());
if (defaultAction->isConst) {
table->set_const_default_action_id(id);
}
table->mutable_initial_default_action()->set_action_id(id);
int parameterIndex = 0;
int parameterId = 1;
for (const auto *argument : *defaultAction->arguments) {
auto value = stringRepr(*typeMap, argument->expression);
if (!value.has_value()) {
continue;
}
auto *protoParam = table->mutable_initial_default_action()->mutable_arguments()->Add();
const auto *parameter =
defaultAction->action->parameters->parameters.at(parameterIndex++);
if (const auto *idAnnotation = parameter->getAnnotation("id"_cs)) {
protoParam->set_param_id(
idAnnotation->getExpr(0)->checkedTo<IR::Constant>()->asInt());
} else {
protoParam->set_param_id(parameterId);
}
parameterId++;
protoParam->set_value(*value);
}
for (const auto &action : actions) {
auto id = symbols.getId(P4RuntimeSymbolType::P4RT_ACTION(), action.name);
auto action_ref = table->add_action_refs();
action_ref->set_id(id);
addAnnotations(action_ref, action.annotations);
// set action ref scope
auto isTableOnly =
action.annotations->hasAnnotation(IR::Annotation::tableOnlyAnnotation);
auto isDefaultOnly =
action.annotations->hasAnnotation(IR::Annotation::defaultOnlyAnnotation);
if (isTableOnly && isDefaultOnly) {
::P4::error(ErrorType::ERR_INVALID,
"Table '%1%' has an action reference ('%2%') which is annotated "
"with both '@tableonly' and '@defaultonly'",
name, action.name);
}
if (isTableOnly)
action_ref->set_scope(p4configv1::ActionRef::TABLE_ONLY);
else if (isDefaultOnly)
action_ref->set_scope(p4configv1::ActionRef::DEFAULT_ONLY);
else
action_ref->set_scope(p4configv1::ActionRef::TABLE_AND_DEFAULT);
}
for (const auto &field : matchFields) {
auto match_field = table->add_match_fields();
match_field->set_id(field.id);
match_field->set_name(field.name);
addAnnotations(match_field, field.annotations);
addDocumentation(match_field, field.annotations);
match_field->set_bitwidth(field.bitwidth);
if (field.type != MatchField::MatchTypes::UNSPECIFIED)
match_field->set_match_type(field.type);
else
match_field->set_other_match_type(field.other_match_type);
if (field.type_name) {
auto namedType = match_field->mutable_type_name();
namedType->set_name(field.type_name);
}
}
if (isConstTable) {
table->set_is_const_table(true);
}
if (hasInitialEntries) {
table->set_has_initial_entries(true);
}
archHandler->addTableProperties(symbols, p4Info, table, tableBlock);
}
void addExtern(const IR::ExternBlock *externBlock) {
CHECK_NULL(externBlock);
archHandler->addExternInstance(symbols, p4Info, externBlock);
}
void analyzeControl(const IR::ControlBlock *controlBlock) {
CHECK_NULL(controlBlock);
auto control = controlBlock->container;
CHECK_NULL(control);
forAllMatching<IR::P4Action>(&control->controlLocals, [&](const IR::P4Action *action) {
// Generate P4Info for the action and, implicitly, its parameters.
addAction(action);
// Generate P4Info for any extern functions it may invoke.
forAllMatching<IR::MethodCallExpression>(
action->body, [&](const IR::MethodCallExpression *call) {
auto instance = MethodInstance::resolve(call, refMap, typeMap);
if (instance->is<P4::ExternFunction>()) {
archHandler->addExternFunction(symbols, p4Info,
instance->to<P4::ExternFunction>());
}
});
});
// Generate P4Info for any extern function invoked directly from control.
forAllMatching<IR::MethodCallExpression>(
control->body, [&](const IR::MethodCallExpression *call) {
auto instance = MethodInstance::resolve(call, refMap, typeMap);
if (instance->is<P4::ExternFunction>()) {
archHandler->addExternFunction(symbols, p4Info,
instance->to<P4::ExternFunction>());
}
});
}
void addValueSet(const IR::P4ValueSet *inst) {
// guaranteed by caller
CHECK_NULL(inst);
auto vs = p4Info->add_value_sets();
auto name = inst->controlPlaneName();
unsigned int size = 0;
auto sizeConstant = inst->size->to<IR::Constant>();
if (sizeConstant == nullptr || !sizeConstant->fitsInt()) {
::P4::error(ErrorType::ERR_INVALID, "@size should be an integer for declaration %1%",
inst);
return;
}
if (sizeConstant->value < 0) {
::P4::error(ErrorType::ERR_INVALID,
"@size should be a positive integer for declaration %1%", inst);
return;
}
size = static_cast<unsigned int>(sizeConstant->value);
auto id = symbols.getId(P4RuntimeSymbolType::P4RT_VALUE_SET(), name);
setPreamble(vs->mutable_preamble(), id, name, symbols.getAlias(name),
inst->to<IR::IAnnotated>(),
[this](cstring anno) { return archHandler->filterAnnotations(anno); });
vs->set_size(size);
/// Look for a @match annotation on the struct field and set the match
/// type of the match field appropriately.
auto setMatchType = [this](const IR::StructField *sf, p4configv1::MatchField *match) {
auto matchAnnotation = sf->getAnnotation(IR::Annotation::matchAnnotation);
// default is EXACT
if (!matchAnnotation) {
match->set_match_type(MatchField::MatchTypes::EXACT); // default match type
return;
}
auto matchPathExpr = matchAnnotation->getExpr(0)->to<IR::PathExpression>();
CHECK_NULL(matchPathExpr);
auto matchTypeName = getMatchTypeName(matchPathExpr, refMap);
auto matchType = getMatchType(matchTypeName);
if (matchType == std::nullopt) {
::P4::error(ErrorType::ERR_UNSUPPORTED,
"unsupported match type %1% for Value Set '@match' annotation",
matchAnnotation);
return;
}
if (matchType != MatchField::MatchTypes::UNSPECIFIED)
match->set_match_type(*matchType);
else
match->set_other_match_type(matchTypeName);
};
// TODO(antonin): handle new types
// as per the P4Runtime v1.0.0 specification
auto et = typeMap->getTypeType(inst->elementType, true);
if (et->is<IR::Type_Bits>()) {
auto *match = vs->add_match();
match->set_id(1);
match->set_bitwidth(et->width_bits());
match->set_match_type(MatchField::MatchTypes::EXACT);
} else if (et->is<IR::Type_Struct>()) {
auto fields = et->to<IR::Type_Struct>()->fields;
// Allocate ids for all match fields, taking into account
// user-provided @id annotations if any.
FieldIdAllocator<decltype(fields)::value_type> idAllocator(fields.begin(),
fields.end());
for (auto f : fields) {
auto fType = f->type;
if (!fType->is<IR::Type_Bits>()) {
::P4::error(ErrorType::ERR_UNSUPPORTED,
"Unsupported type argument for Value Set; "
"this version of P4Runtime requires that when the type parameter "
"of a Value Set is a struct, all the fields of the struct "
"must be of type bit<W>, but %1% is not",
f);
continue;
}
auto *match = vs->add_match();
auto fieldId = idAllocator.getId(f);
match->set_id(fieldId);
match->set_name(f->controlPlaneName());
match->set_bitwidth(fType->width_bits());
setMatchType(f, match);
// add annotations save for the @match one
addAnnotations(
match, f, [](cstring name) { return name == IR::Annotation::matchAnnotation; });
addDocumentation(match, f);
}
} else if (et->is<IR::Type_SerEnum>()) {
auto serEnum = et->to<IR::Type_SerEnum>();
auto fType = serEnum->type;
if (!fType->is<IR::Type_Bits>()) {
::P4::error(ErrorType::ERR_UNSUPPORTED,
"Unsupported type argument for Value Set; "
"this version of P4Runtime requires that when the type parameter "
"of a Value Set is a serializable enum, "
"it must be of type bit<W>, but %1% is not",
serEnum);
}
auto fields = serEnum->members;
p4rt_id_t index = 1;
for (auto f : fields) {
auto *match = vs->add_match();
match->set_id(index++);
match->set_name(f->controlPlaneName());
match->set_bitwidth(fType->width_bits());
match->set_match_type(MatchField::MatchTypes::EXACT);
}
} else if (et->is<IR::Type_BaseList>()) {
::P4::error(ErrorType::ERR_UNSUPPORTED,
"%1%: Unsupported type argument for Value Set; "
"this version of P4Runtime requires the type parameter of a Value Set "
"to be a bit<W>, a struct of bit<W> fields, or a serializable enum",
inst);
} else {
::P4::error(ErrorType::ERR_INVALID,
"%1%: invalid type parameter for Value Set; "
"it must be one of bit<W>, struct, tuple or serializable enum",
inst);
}
}
/// To be called after all objects have been added to P4Info. Calls the
/// architecture-specific postAdd method for post-processing.
void postAdd() const { archHandler->postAdd(symbols, p4Info); }
/// Sets the pkg_info field of the P4Info message, using the annotations on
/// the P4 program package.
void addPkgInfo(const IR::ToplevelBlock *evaluatedProgram, cstring arch) const {
auto *main = evaluatedProgram->getMain();
if (main == nullptr) {
::P4::warning(ErrorType::WARN_MISSING,
"Program does not contain a main module, "
"so P4Info's 'pkg_info' field will not be set");
return;
}
auto *decl = main->node->to<IR::Declaration_Instance>();
CHECK_NULL(decl);
auto *pkginfo = p4Info->mutable_pkg_info();
pkginfo->set_arch(arch);
std::set<cstring> keysVisited;
// @pkginfo annotation
if (const auto *annotation = decl->getAnnotation(IR::Annotation::pkginfoAnnotation)) {
for (auto *kv : annotation->getKV()) {
auto name = kv->name.name;
auto setStringField = [kv, pkginfo, &keysVisited](cstring fName) {
auto *v = kv->expression->to<IR::StringLiteral>();
if (v == nullptr) {
::P4::error(ErrorType::ERR_UNSUPPORTED,
"Value for '%1%' key in @pkginfo annotation is not a string",
kv);
return;
}
// kv annotations are represented with an IndexedVector in
// the IR, so a program with duplicate keys is actually
// rejected at parse time.
BUG_CHECK(!keysVisited.count(fName), "Duplicate keys in @pkginfo");
keysVisited.insert(fName);
// use Protobuf reflection library to minimize code
// duplication.
auto *descriptor = pkginfo->GetDescriptor();
auto *f = descriptor->FindFieldByName(static_cast<std::string>(fName));
pkginfo->GetReflection()->SetString(pkginfo, f,
static_cast<std::string>(v->value));
};
if (name == "name" || name == "version" || name == "organization" ||
name == "contact" || name == "url") {
setStringField(name);
} else if (name == "arch") {
::P4::warning(ErrorType::WARN_INVALID,
"The '%1%' field in PkgInfo should be set by the compiler, "
"not by the user",
kv);
// override the value set previously with the user-provided
// value.
setStringField(name);
} else {
::P4::warning(ErrorType::WARN_UNKNOWN,
"Unknown key name '%1%' in @pkginfo annotation", name);
}
}
}
// Parse `@platform_property` annotation into the PkgInfo.
if (const auto *annotation = decl->getAnnotation("platform_property"_cs)) {
auto *platform_properties = pkginfo->mutable_platform_properties();
for (auto *kv : annotation->getKV()) {
auto name = kv->name.name;
auto setInt32Field = [kv, &platform_properties](cstring fName) {
auto *v = kv->expression->to<IR::Constant>();
if (v == nullptr) {
::P4::error(
ErrorType::ERR_UNSUPPORTED,
"Value for '%1%' key in @platform_property annotation is not an "
"integer",
kv);
return;
}
// use Protobuf reflection library to minimize code duplication.