-
Notifications
You must be signed in to change notification settings - Fork 342
/
Copy pathLowerClasses.cpp
2175 lines (1832 loc) · 82.7 KB
/
LowerClasses.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
//===- LowerClasses.cpp - Lower to OM classes and objects -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the LowerClasses pass.
//
//===----------------------------------------------------------------------===//
#include "circt/Dialect/FIRRTL/FIRRTLAnnotationHelper.h"
#include "circt/Dialect/FIRRTL/FIRRTLAnnotations.h"
#include "circt/Dialect/FIRRTL/FIRRTLDialect.h"
#include "circt/Dialect/FIRRTL/FIRRTLTypes.h"
#include "circt/Dialect/FIRRTL/FIRRTLUtils.h"
#include "circt/Dialect/FIRRTL/OwningModuleCache.h"
#include "circt/Dialect/FIRRTL/Passes.h"
#include "circt/Dialect/HW/InnerSymbolNamespace.h"
#include "circt/Dialect/OM/OMAttributes.h"
#include "circt/Dialect/OM/OMOps.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/Threading.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/DialectConversion.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/STLExtras.h"
namespace circt {
namespace firrtl {
#define GEN_PASS_DEF_LOWERCLASSES
#include "circt/Dialect/FIRRTL/Passes.h.inc"
} // namespace firrtl
} // namespace circt
using namespace mlir;
using namespace circt;
using namespace circt::firrtl;
using namespace circt::om;
namespace {
static bool shouldCreateClassImpl(igraph::InstanceGraphNode *node) {
auto moduleLike = node->getModule<FModuleLike>();
if (!moduleLike)
return false;
if (isa<firrtl::ClassLike>(moduleLike.getOperation()))
return true;
// Always create a class for public modules.
if (moduleLike.isPublic())
return true;
// Create a class for modules with property ports.
bool hasClassPorts = llvm::any_of(moduleLike.getPorts(), [](PortInfo port) {
return isa<PropertyType>(port.type);
});
if (hasClassPorts)
return true;
// Create a class for modules that instantiate classes or modules with
// property ports.
for (auto *instance : *node) {
if (auto op = instance->getInstance<FInstanceLike>())
for (auto result : op->getResults())
if (type_isa<PropertyType>(result.getType()))
return true;
}
return false;
}
/// Helper class which holds a hierarchical path op reference and a pointer to
/// to the targeted operation.
struct PathInfo {
PathInfo() = default;
PathInfo(Location loc, bool canBeInstanceTarget, FlatSymbolRefAttr symRef,
StringAttr altBasePathModule)
: loc(loc), canBeInstanceTarget(canBeInstanceTarget), symRef(symRef),
altBasePathModule(altBasePathModule) {
assert(symRef && "symRef must not be null");
}
/// The Location of the hardware component targeted by this path.
std::optional<Location> loc = std::nullopt;
/// Flag to indicate if the hardware component can be targeted as an instance.
bool canBeInstanceTarget = false;
/// A reference to the hierarchical path targeting the op.
FlatSymbolRefAttr symRef = nullptr;
/// The module name of the root module from which we take an alternative base
/// path.
StringAttr altBasePathModule = nullptr;
};
/// Maps a FIRRTL path id to the lowered PathInfo.
struct PathInfoTable {
// Add an alternative base path root module. The default base path from this
// module will be passed through to where it is needed.
void addAltBasePathRoot(StringAttr rootModuleName) {
altBasePathRoots.insert(rootModuleName);
}
// Add a passthrough module for a given root module. The default base path
// from the root module will be passed through the passthrough module.
void addAltBasePathPassthrough(StringAttr passthroughModuleName,
StringAttr rootModuleName) {
auto &rootSequence = altBasePathsPassthroughs[passthroughModuleName];
rootSequence.push_back(rootModuleName);
}
// Get an iterator range over the alternative base path root module names.
llvm::iterator_range<SmallPtrSetImpl<StringAttr>::iterator>
getAltBasePathRoots() const {
return llvm::make_range(altBasePathRoots.begin(), altBasePathRoots.end());
}
// Get the number of alternative base paths passing through the given
// passthrough module.
size_t getNumAltBasePaths(StringAttr passthroughModuleName) const {
return altBasePathsPassthroughs.lookup(passthroughModuleName).size();
}
// Get the root modules that are passing an alternative base path through the
// given passthrough module.
llvm::iterator_range<const StringAttr *>
getRootsForPassthrough(StringAttr passthroughModuleName) const {
auto it = altBasePathsPassthroughs.find(passthroughModuleName);
assert(it != altBasePathsPassthroughs.end() &&
"expected passthrough module to already exist");
return llvm::make_range(it->second.begin(), it->second.end());
}
// Collect alternative base paths passing through `instance`, by looking up
// its associated `moduleNameAttr`. The results are collected in `result`.
void collectAltBasePaths(Operation *instance, StringAttr moduleNameAttr,
SmallVectorImpl<Value> &result) const {
auto altBasePaths = altBasePathsPassthroughs.lookup(moduleNameAttr);
auto parent = instance->getParentOfType<om::ClassOp>();
// Handle each alternative base path for instances of this module-like.
for (auto [i, altBasePath] : llvm::enumerate(altBasePaths)) {
if (parent.getName().starts_with(altBasePath)) {
// If we are passing down from the root, take the root base path.
result.push_back(instance->getBlock()->getArgument(0));
} else {
// Otherwise, pass through the appropriate base path from above.
// + 1 to skip default base path
auto basePath = instance->getBlock()->getArgument(1 + i);
assert(isa<om::BasePathType>(basePath.getType()) &&
"expected a passthrough base path");
result.push_back(basePath);
}
}
}
// The table mapping DistinctAttrs to PathInfo structs.
DenseMap<DistinctAttr, PathInfo> table;
private:
// Module name attributes indicating modules whose base path input should
// be used as alternate base paths.
SmallPtrSet<StringAttr, 16> altBasePathRoots;
// Module name attributes mapping from modules who pass through alternative
// base paths from their parents to a sequence of the parents' module names.
DenseMap<StringAttr, SmallVector<StringAttr>> altBasePathsPassthroughs;
};
/// The suffix to append to lowered module names.
static constexpr StringRef kClassNameSuffix = "_Class";
/// Helper class to capture details about a property.
struct Property {
size_t index;
StringRef name;
Type type;
Location loc;
};
/// Helper class to capture state about a Class being lowered.
struct ClassLoweringState {
FModuleLike moduleLike;
std::vector<hw::HierPathOp> paths;
};
struct LoweringState {
PathInfoTable pathInfoTable;
DenseMap<om::ClassLike, ClassLoweringState> classLoweringStateTable;
};
/// Helper struct to capture state about an object that needs RtlPorts added.
struct RtlPortsInfo {
firrtl::PathOp containingModuleRef;
Value basePath;
om::ObjectOp object;
};
struct LowerClassesPass
: public circt::firrtl::impl::LowerClassesBase<LowerClassesPass> {
void runOnOperation() override;
private:
LogicalResult processPaths(InstanceGraph &instanceGraph,
hw::InnerSymbolNamespaceCollection &namespaces,
HierPathCache &cache, PathInfoTable &pathInfoTable,
SymbolTable &symbolTable);
// Predicate to check if a module-like needs a Class to be created.
bool shouldCreateClass(StringAttr modName);
// Create an OM Class op from a FIRRTL Class op.
om::ClassLike createClass(FModuleLike moduleLike,
const PathInfoTable &pathInfoTable,
std::mutex &intraPassMutex);
// Lower the FIRRTL Class to OM Class.
void lowerClassLike(FModuleLike moduleLike, om::ClassLike classLike,
const PathInfoTable &pathInfoTable);
void lowerClass(om::ClassOp classOp, FModuleLike moduleLike,
const PathInfoTable &pathInfoTable);
void lowerClassExtern(ClassExternOp classExternOp, FModuleLike moduleLike);
// Update Object instantiations in a FIRRTL Module or OM Class.
LogicalResult updateInstances(Operation *op, InstanceGraph &instanceGraph,
const LoweringState &state,
const PathInfoTable &pathInfoTable,
std::mutex &intraPassMutex);
/// Create and add all 'ports' lists of RtlPort objects for each object.
void createAllRtlPorts(const PathInfoTable &pathInfoTable,
hw::InnerSymbolNamespaceCollection &namespaces,
HierPathCache &hierPathCache);
// Convert to OM ops and types in Classes or Modules.
LogicalResult dialectConversion(
Operation *op, const PathInfoTable &pathInfoTable,
const DenseMap<StringAttr, firrtl::ClassType> &classTypeTable);
// State to memoize repeated calls to shouldCreateClass.
DenseMap<StringAttr, bool> shouldCreateClassMemo;
// State used while creating the optional 'ports' list of RtlPort objects.
SmallVector<RtlPortsInfo> rtlPortsToCreate;
};
struct PathTracker {
// An entry point for parallely tracking paths in the circuit and apply
// changes to `pathInfoTable`.
static LogicalResult
run(CircuitOp circuit, InstanceGraph &instanceGraph,
hw::InnerSymbolNamespaceCollection &namespaces, HierPathCache &cache,
PathInfoTable &pathInfoTable, const SymbolTable &symbolTable,
const DenseMap<DistinctAttr, FModuleOp> &owningModules);
PathTracker(FModuleLike module,
hw::InnerSymbolNamespaceCollection &namespaces,
InstanceGraph &instanceGraph, const SymbolTable &symbolTable,
const DenseMap<DistinctAttr, FModuleOp> &owningModules)
: module(module), moduleNamespace(namespaces[module]),
namespaces(namespaces), instanceGraph(instanceGraph),
symbolTable(symbolTable), owningModules(owningModules) {}
private:
struct PathInfoTableEntry {
Operation *op;
DistinctAttr id;
StringAttr altBasePathModule;
// This is null if the path has no owning module.
ArrayAttr pathAttr;
};
// Run the main logic.
LogicalResult runOnModule();
// Return updated annotations for a given AnnoTarget if success.
FailureOr<AnnotationSet> processPathTrackers(const AnnoTarget &target);
LogicalResult updatePathInfoTable(PathInfoTable &pathInfoTable,
HierPathCache &cache) const;
// Determine it is necessary to use an alternative base path for `moduleName`
// and `owningModule`.
FailureOr<bool> getOrComputeNeedsAltBasePath(Location loc,
StringAttr moduleName,
FModuleOp owningModule,
bool isNonLocal);
FModuleLike module;
// Local data structures.
hw::InnerSymbolNamespace &moduleNamespace;
hw::InnerSymbolNamespaceCollection &namespaces;
DenseMap<std::pair<StringAttr, FModuleOp>, bool> needsAltBasePathCache;
// Thread-unsafe global data structure. Don't mutate.
InstanceGraph &instanceGraph;
const SymbolTable &symbolTable;
const DenseMap<DistinctAttr, FModuleOp> &owningModules;
// Result.
SmallVector<PathInfoTableEntry> entries;
SetVector<StringAttr> altBasePathRoots;
};
/// Constants and helpers for creating the RtlPorts on the fly.
static constexpr StringRef kContainingModuleName = "containingModule";
static constexpr StringRef kPortsName = "ports";
static constexpr StringRef kRtlPortClassName = "RtlPort";
static Type getRtlPortsType(MLIRContext *context) {
return om::ListType::get(om::ClassType::get(
context, FlatSymbolRefAttr::get(context, kRtlPortClassName)));
}
/// Create and add the 'ports' list of RtlPort objects for an object.
static void createRtlPorts(const RtlPortsInfo &rtlPortToCreate,
const PathInfoTable &pathInfoTable,
hw::InnerSymbolNamespaceCollection &namespaces,
HierPathCache &hierPathCache, OpBuilder &builder) {
firrtl::PathOp containingModuleRef = rtlPortToCreate.containingModuleRef;
Value basePath = rtlPortToCreate.basePath;
om::ObjectOp object = rtlPortToCreate.object;
// Set the builder to just before the object.
OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPoint(object);
// Look up the module from the containingModuleRef.
FlatSymbolRefAttr containingModulePathRef =
pathInfoTable.table.at(containingModuleRef.getTarget()).symRef;
const SymbolTable &symbolTable = hierPathCache.getSymbolTable();
hw::HierPathOp containingModulePath =
symbolTable.lookup<hw::HierPathOp>(containingModulePathRef.getAttr());
assert(containingModulePath.isModule() &&
"expected containing module path to target a module");
StringAttr moduleName = containingModulePath.leafMod();
FModuleLike mod = symbolTable.lookup<FModuleLike>(moduleName);
MLIRContext *ctx = mod.getContext();
Location loc = mod.getLoc();
// Create the per-port information.
auto portClassName = StringAttr::get(ctx, kRtlPortClassName);
auto portClassType =
om::ClassType::get(ctx, FlatSymbolRefAttr::get(portClassName));
SmallVector<Value> ports;
for (unsigned i = 0, e = mod.getNumPorts(); i < e; ++i) {
// Only process ports that are not zero-width.
auto portType = type_dyn_cast<FIRRTLBaseType>(mod.getPortType(i));
if (!portType || portType.getBitWidthOrSentinel() == 0)
continue;
// Get a path to the port. This may modify port attributes or the global
// namespace of hierpaths, so use the mutex around those operations.
auto portTarget = PortAnnoTarget(mod, i);
auto portSym =
getInnerRefTo({portTarget.getPortNo(), portTarget.getOp(), 0},
[&](FModuleLike m) -> hw::InnerSymbolNamespace & {
return namespaces[m];
});
FlatSymbolRefAttr portPathRef =
hierPathCache.getRefFor(ArrayAttr::get(ctx, {portSym}));
auto portPath = builder.create<om::PathCreateOp>(
loc, om::PathType::get(ctx),
om::TargetKindAttr::get(ctx, om::TargetKind::DontTouch), basePath,
portPathRef);
// Get a direction attribute.
StringRef portDirectionName =
mod.getPortDirection(i) == Direction::Out ? "Output" : "Input";
auto portDirection = builder.create<om::ConstantOp>(
loc, om::StringType::get(ctx),
StringAttr::get(portDirectionName, om::StringType::get(ctx)));
// Get a width attribute.
auto portWidth = builder.create<om::ConstantOp>(
loc, om::OMIntegerType::get(ctx),
om::IntegerAttr::get(
ctx, mlir::IntegerAttr::get(mlir::IntegerType::get(ctx, 64),
portType.getBitWidthOrSentinel())));
// Create an RtlPort object for this port, and add it to the list.
auto portObj = builder.create<om::ObjectOp>(
loc, portClassType, portClassName,
ArrayRef<Value>{portPath, portDirection, portWidth});
ports.push_back(portObj);
}
// Create a list of RtlPort objects to be included with the containingModule.
auto portsList = builder.create<om::ListCreateOp>(
UnknownLoc::get(builder.getContext()),
getRtlPortsType(builder.getContext()), ports);
object.getActualParamsMutable().append({portsList});
}
} // namespace
LogicalResult
PathTracker::run(CircuitOp circuit, InstanceGraph &instanceGraph,
hw::InnerSymbolNamespaceCollection &namespaces,
HierPathCache &cache, PathInfoTable &pathInfoTable,
const SymbolTable &symbolTable,
const DenseMap<DistinctAttr, FModuleOp> &owningModules) {
// First allocate module namespaces. Don't capture a namespace reference at
// this point since they could be invalidated when DenseMap grows.
for (auto *node : instanceGraph)
if (auto module = node->getModule<FModuleLike>())
(void)namespaces.get(module);
for (auto *node : instanceGraph)
if (auto module = node->getModule<FModuleLike>()) {
// Classes do not have path trackers on them.
if (isa<firrtl::ClassOp, firrtl::ExtClassOp>(module))
continue;
PathTracker tracker(module, namespaces, instanceGraph, symbolTable,
owningModules);
if (failed(tracker.runOnModule()))
return failure();
if (failed(tracker.updatePathInfoTable(pathInfoTable, cache)))
return failure();
}
return success();
}
LogicalResult PathTracker::runOnModule() {
auto processAndUpdateAnnoTarget = [&](AnnoTarget target) -> LogicalResult {
auto anno = processPathTrackers(target);
if (failed(anno))
return failure();
target.setAnnotations(*anno);
return success();
};
// Process the module annotations.
if (failed(processAndUpdateAnnoTarget(OpAnnoTarget(module))))
return failure();
// Process module port annotations.
SmallVector<Attribute> portAnnotations;
portAnnotations.reserve(module.getNumPorts());
for (unsigned i = 0, e = module.getNumPorts(); i < e; ++i) {
auto annos = processPathTrackers(PortAnnoTarget(module, i));
if (failed(annos))
return failure();
portAnnotations.push_back(annos->getArrayAttr());
}
// Batch update port annotations.
module.setPortAnnotationsAttr(
ArrayAttr::get(module.getContext(), portAnnotations));
// Process ops in the module body.
auto result = module.walk([&](hw::InnerSymbolOpInterface op) {
if (failed(processAndUpdateAnnoTarget(OpAnnoTarget(op))))
return WalkResult::interrupt();
return WalkResult::advance();
});
if (result.wasInterrupted())
return failure();
// Process paththrough.
return success();
}
FailureOr<bool>
PathTracker::getOrComputeNeedsAltBasePath(Location loc, StringAttr moduleName,
FModuleOp owningModule,
bool isNonLocal) {
auto it = needsAltBasePathCache.find({moduleName, owningModule});
if (it != needsAltBasePathCache.end())
return it->second;
bool needsAltBasePath = false;
auto *node = instanceGraph.lookup(moduleName);
while (true) {
// If the path is rooted at the owning module, we're done.
if (node->getModule() == owningModule)
break;
// If there are no more parents, then the path op lives in a different
// hierarchy than the HW object it references, which needs to handled
// specially. Flag this, so we know to create an alternative base path
// below.
if (node->noUses()) {
needsAltBasePath = true;
break;
}
// If there is more than one instance of this module, and the target is
// non-local, then the path operation is ambiguous, which is an error.
if (isNonLocal && !node->hasOneUse()) {
auto diag = mlir::emitError(loc)
<< "unable to uniquely resolve target due "
"to multiple instantiation";
for (auto *use : node->uses())
diag.attachNote(use->getInstance().getLoc()) << "instance here";
return diag;
}
node = (*node->usesBegin())->getParent();
}
needsAltBasePathCache[{moduleName, owningModule}] = needsAltBasePath;
return needsAltBasePath;
}
FailureOr<AnnotationSet>
PathTracker::processPathTrackers(const AnnoTarget &target) {
auto error = false;
auto annotations = target.getAnnotations();
auto *op = target.getOp();
annotations.removeAnnotations([&](Annotation anno) {
// If there has been an error, just skip this annotation.
if (error)
return false;
// We are looking for OMIR tracker annotations.
if (!anno.isClass("circt.tracker"))
return false;
// The token must have a valid ID.
auto id = anno.getMember<DistinctAttr>("id");
if (!id) {
op->emitError("circt.tracker annotation missing id field");
error = true;
return false;
}
// Get the fieldID. If there is none, it is assumed to be 0.
uint64_t fieldID = anno.getFieldID();
// Attach an inner sym to the operation.
Attribute targetSym;
if (auto portTarget = dyn_cast<PortAnnoTarget>(target)) {
targetSym =
getInnerRefTo({portTarget.getPortNo(), portTarget.getOp(), fieldID},
[&](FModuleLike module) -> hw::InnerSymbolNamespace & {
return moduleNamespace;
});
} else if (auto module = dyn_cast<FModuleLike>(op)) {
assert(!fieldID && "field not valid for modules");
targetSym = FlatSymbolRefAttr::get(module.getModuleNameAttr());
} else {
targetSym =
getInnerRefTo({target.getOp(), fieldID},
[&](FModuleLike module) -> hw::InnerSymbolNamespace & {
return moduleNamespace;
});
}
// Create the hierarchical path.
SmallVector<Attribute> path;
// Copy the trailing final target part of the path.
path.push_back(targetSym);
auto moduleName = target.getModule().getModuleNameAttr();
// Verify a nonlocal annotation refers to a HierPathOp.
hw::HierPathOp hierPathOp;
if (auto hierName = anno.getMember<FlatSymbolRefAttr>("circt.nonlocal")) {
hierPathOp =
dyn_cast<hw::HierPathOp>(symbolTable.lookup(hierName.getAttr()));
if (!hierPathOp) {
op->emitError("annotation does not point at a HierPathOp");
error = true;
return false;
}
}
// Get the owning module. If there is no owning module, then this
// declaration does not have a use, and we can return early.
auto owningModule = owningModules.lookup(id);
if (!owningModule) {
PathInfoTableEntry entry;
// This entry is used for checking id uniquness.
entry.op = op;
entry.id = id;
entries.push_back(entry);
return true;
}
// Copy the middle part from the annotation's NLA.
if (hierPathOp) {
// Get the original path.
auto oldPath = hierPathOp.getNamepath().getValue();
// Set the moduleName and path based on the hierarchical path. If the
// owningModule is in the hierarichal path, start the hierarchical path
// there. Otherwise use the top of the hierarchical path.
bool pathContainsOwningModule = false;
size_t owningModuleIndex = 0;
for (auto [idx, pathFramgent] : llvm::enumerate(oldPath)) {
if (auto innerRef = dyn_cast<hw::InnerRefAttr>(pathFramgent)) {
if (innerRef.getModule() == owningModule.getModuleNameAttr()) {
pathContainsOwningModule = true;
owningModuleIndex = idx;
}
} else if (auto symRef = dyn_cast<FlatSymbolRefAttr>(pathFramgent)) {
if (symRef.getAttr() == owningModule.getModuleNameAttr()) {
pathContainsOwningModule = true;
owningModuleIndex = idx;
}
}
}
if (pathContainsOwningModule) {
// Set the path root module name to the owning module.
moduleName = owningModule.getModuleNameAttr();
// Copy the old path, dropping the module name and the prefix to the
// owning module.
llvm::append_range(path, llvm::reverse(oldPath.drop_back().drop_front(
owningModuleIndex)));
} else {
// Set the path root module name to the start of the path.
moduleName = cast<hw::InnerRefAttr>(oldPath.front()).getModule();
// Copy the old path, dropping the module name.
llvm::append_range(path, llvm::reverse(oldPath.drop_back()));
}
}
// Check if we need an alternative base path.
auto needsAltBasePath = getOrComputeNeedsAltBasePath(
op->getLoc(), moduleName, owningModule, hierPathOp);
if (failed(needsAltBasePath)) {
error = true;
return false;
}
// Copy the leading part of the hierarchical path from the owning module
// to the start of the annotation's NLA.
InstanceGraphNode *node = instanceGraph.lookup(moduleName);
while (true) {
// If it's not a non-local target, we don't have to append anything,
// unless it needs an alternative base path, in which case we do need to
// make a hierarchical path.
if (!hierPathOp && !needsAltBasePath.value())
break;
// If we get to the owning module or the top, we're done.
if (node->getModule() == owningModule || node->noUses())
break;
// Append the next level of hierarchy to the path.
assert(node->hasOneUse() && "expected single instantiation");
InstanceRecord *inst = *node->usesBegin();
path.push_back(
OpAnnoTarget(inst->getInstance<InstanceOp>())
.getNLAReference(namespaces[inst->getParent()->getModule()]));
node = inst->getParent();
}
// Create the HierPathOp.
std::reverse(path.begin(), path.end());
auto pathAttr = ArrayAttr::get(op->getContext(), path);
// If we need an alternative base path, save the top module from the
// path. We will plumb in the basepath from this module.
StringAttr altBasePathModule;
if (*needsAltBasePath) {
altBasePathModule =
TypeSwitch<Attribute, StringAttr>(path.front())
.Case<FlatSymbolRefAttr>([](auto a) { return a.getAttr(); })
.Case<hw::InnerRefAttr>([](auto a) { return a.getModule(); });
altBasePathRoots.insert(altBasePathModule);
}
// Record the path operation associated with the path op.
entries.push_back({op, id, altBasePathModule, pathAttr});
// Remove this annotation from the operation.
return true;
});
if (error)
return {};
return annotations;
}
LogicalResult PathTracker::updatePathInfoTable(PathInfoTable &pathInfoTable,
HierPathCache &cache) const {
for (auto root : altBasePathRoots)
pathInfoTable.addAltBasePathRoot(root);
for (const auto &entry : entries) {
// Record the path operation associated with the path op.
auto [it, inserted] = pathInfoTable.table.try_emplace(entry.id);
auto &pathInfo = it->second;
if (!inserted) {
assert(pathInfo.loc.has_value() && "all PathInfo should have a Location");
auto diag = emitError(pathInfo.loc.value(),
"path identifier already found, paths must resolve "
"to a unique target");
diag.attachNote(entry.op->getLoc()) << "other path identifier here";
return failure();
}
// Check if the op is targetable by an instance target. The op pointer may
// be invalidated later, so this is the last time we want to access it here.
bool canBeInstanceTarget = isa<InstanceOp, FModuleLike>(entry.op);
if (entry.pathAttr) {
pathInfo = {entry.op->getLoc(), canBeInstanceTarget,
cache.getRefFor(entry.pathAttr), entry.altBasePathModule};
} else {
pathInfo.loc = entry.op->getLoc();
pathInfo.canBeInstanceTarget = canBeInstanceTarget;
}
}
return success();
}
/// This pass removes the OMIR tracker annotations from operations, and ensures
/// that each thing that was targeted has a hierarchical path targeting it. It
/// builds a table which maps the original OMIR tracker annotation IDs to the
/// corresponding hierarchical paths. We use this table to convert FIRRTL path
/// ops to OM. FIRRTL paths refer to their target using a target ID, while OM
/// paths refer to their target using hierarchical paths.
LogicalResult LowerClassesPass::processPaths(
InstanceGraph &instanceGraph,
hw::InnerSymbolNamespaceCollection &namespaces, HierPathCache &cache,
PathInfoTable &pathInfoTable, SymbolTable &symbolTable) {
auto circuit = getOperation();
// Collect the path declarations and owning modules.
OwningModuleCache owningModuleCache(instanceGraph);
DenseMap<DistinctAttr, FModuleOp> owningModules;
std::vector<Operation *> declarations;
auto result = circuit.walk([&](Operation *op) {
if (auto pathOp = dyn_cast<PathOp>(op)) {
// Find the owning module of this path reference.
auto owningModule = owningModuleCache.lookup(pathOp);
// If this reference does not have a single owning module, it is an error.
if (!owningModule) {
pathOp->emitError("path does not have a single owning module");
return WalkResult::interrupt();
}
auto target = pathOp.getTargetAttr();
auto [it, inserted] = owningModules.try_emplace(target, owningModule);
// If this declaration already has a reference, both references must have
// the same owning module.
if (!inserted && it->second != owningModule) {
pathOp->emitError()
<< "path reference " << target << " has conflicting owning modules "
<< it->second.getModuleNameAttr() << " and "
<< owningModule.getModuleNameAttr();
return WalkResult::interrupt();
}
}
return WalkResult::advance();
});
if (result.wasInterrupted())
return failure();
if (failed(PathTracker::run(circuit, instanceGraph, namespaces, cache,
pathInfoTable, symbolTable, owningModules)))
return failure();
// For each module that will be passing through a base path, compute its
// descendants that need this base path passed through.
for (auto rootModule : pathInfoTable.getAltBasePathRoots()) {
InstanceGraphNode *node = instanceGraph.lookup(rootModule);
// Do a depth first traversal of the instance graph from rootModule,
// looking for descendants that need to be passed through.
auto start = llvm::df_begin(node);
auto end = llvm::df_end(node);
auto it = start;
while (it != end) {
// Nothing to do for the root module.
if (it == start) {
++it;
continue;
}
// If we aren't creating a class for this child, skip this hierarchy.
if (!shouldCreateClass(
it->getModule<FModuleLike>().getModuleNameAttr())) {
it = it.skipChildren();
continue;
}
// If we are at a leaf, nothing to do.
if (it->begin() == it->end()) {
++it;
continue;
}
// Track state for this passthrough.
StringAttr passthroughModule = it->getModule().getModuleNameAttr();
pathInfoTable.addAltBasePathPassthrough(passthroughModule, rootModule);
++it;
}
}
return success();
}
/// Lower FIRRTL Class and Object ops to OM Class and Object ops
void LowerClassesPass::runOnOperation() {
MLIRContext *ctx = &getContext();
auto intraPassMutex = std::mutex();
// Get the CircuitOp.
CircuitOp circuit = getOperation();
// Get the InstanceGraph and SymbolTable.
InstanceGraph &instanceGraph = getAnalysis<InstanceGraph>();
SymbolTable &symbolTable = getAnalysis<SymbolTable>();
hw::InnerSymbolNamespaceCollection namespaces;
HierPathCache cache(circuit, symbolTable);
// Fill `shouldCreateClassMemo`.
for (auto *node : instanceGraph)
if (auto moduleLike = node->getModule<firrtl::FModuleLike>())
shouldCreateClassMemo.insert({moduleLike.getModuleNameAttr(), false});
parallelForEach(circuit.getContext(), instanceGraph,
[&](igraph::InstanceGraphNode *node) {
if (auto moduleLike = node->getModule<FModuleLike>())
shouldCreateClassMemo[moduleLike.getModuleNameAttr()] =
shouldCreateClassImpl(node);
});
// Rewrite all path annotations into inner symbol targets.
PathInfoTable pathInfoTable;
if (failed(processPaths(instanceGraph, namespaces, cache, pathInfoTable,
symbolTable))) {
signalPassFailure();
return;
}
LoweringState loweringState;
// Create new OM Class ops serially.
DenseMap<StringAttr, firrtl::ClassType> classTypeTable;
for (auto *node : instanceGraph) {
auto moduleLike = node->getModule<firrtl::FModuleLike>();
if (!moduleLike)
continue;
if (shouldCreateClass(moduleLike.getModuleNameAttr())) {
auto omClass = createClass(moduleLike, pathInfoTable, intraPassMutex);
auto &classLoweringState = loweringState.classLoweringStateTable[omClass];
classLoweringState.moduleLike = moduleLike;
// Find the module instances under the current module with metadata. These
// ops will be converted to om objects by this pass. Create a hierarchical
// path for each of these instances, which will be used to rebase path
// operations. Hierarchical paths must be created serially to ensure their
// order in the circuit is deterministc.
for (auto *instance : *node) {
auto inst = instance->getInstance<firrtl::InstanceOp>();
if (!inst)
continue;
// Get the referenced module.
auto module = instance->getTarget()->getModule<FModuleLike>();
if (module && shouldCreateClass(module.getModuleNameAttr())) {
auto targetSym = getInnerRefTo(
{inst, 0}, [&](FModuleLike module) -> hw::InnerSymbolNamespace & {
return namespaces[module];
});
SmallVector<Attribute> path = {targetSym};
auto pathAttr = ArrayAttr::get(ctx, path);
auto hierPath = cache.getOpFor(pathAttr);
classLoweringState.paths.push_back(hierPath);
}
}
if (auto classLike =
dyn_cast<firrtl::ClassLike>(moduleLike.getOperation()))
classTypeTable[classLike.getNameAttr()] = classLike.getInstanceType();
}
}
// Move ops from FIRRTL Class to OM Class in parallel.
mlir::parallelForEach(ctx, loweringState.classLoweringStateTable,
[this, &pathInfoTable](auto &entry) {
const auto &[classLike, state] = entry;
lowerClassLike(state.moduleLike, classLike,
pathInfoTable);
});
// Completely erase Class module-likes, and remove from the InstanceGraph.
for (auto &[omClass, state] : loweringState.classLoweringStateTable) {
if (isa<firrtl::ClassLike>(state.moduleLike.getOperation())) {
InstanceGraphNode *node = instanceGraph.lookup(state.moduleLike);
for (auto *use : llvm::make_early_inc_range(node->uses()))
use->erase();
instanceGraph.erase(node);
state.moduleLike.erase();
}
}
// Collect ops where Objects can be instantiated.
SmallVector<Operation *> objectContainers;
for (auto &op : circuit.getOps())
if (isa<FModuleOp, om::ClassLike>(op))
objectContainers.push_back(&op);
// Update Object creation ops in Classes or Modules in parallel.
if (failed(
mlir::failableParallelForEach(ctx, objectContainers, [&](auto *op) {
return updateInstances(op, instanceGraph, loweringState,
pathInfoTable, intraPassMutex);
})))
return signalPassFailure();
// If needed, create and add 'ports' lists of RtlPort objects.
if (!rtlPortsToCreate.empty())
createAllRtlPorts(pathInfoTable, namespaces, cache);
// Convert to OM ops and types in Classes or Modules in parallel.
if (failed(
mlir::failableParallelForEach(ctx, objectContainers, [&](auto *op) {
return dialectConversion(op, pathInfoTable, classTypeTable);
})))
return signalPassFailure();
// We keep the instance graph up to date, so mark that analysis preserved.
markAnalysesPreserved<InstanceGraph>();
// Reset pass state.
rtlPortsToCreate.clear();
}
std::unique_ptr<mlir::Pass> circt::firrtl::createLowerClassesPass() {
return std::make_unique<LowerClassesPass>();
}
// Predicate to check if a module-like needs a Class to be created.
bool LowerClassesPass::shouldCreateClass(StringAttr modName) {
// Return a memoized result.
return shouldCreateClassMemo.at(modName);
}
void checkAddContainingModulePorts(bool hasContainingModule, OpBuilder builder,
SmallVector<Attribute> &fieldNames,
SmallVector<NamedAttribute> &fieldTypes) {
if (hasContainingModule) {
auto name = builder.getStringAttr(kPortsName);
fieldNames.push_back(name);
fieldTypes.push_back(NamedAttribute(
name, TypeAttr::get(getRtlPortsType(builder.getContext()))));
}
}
static om::ClassLike convertExtClass(FModuleLike moduleLike, OpBuilder builder,
Twine name,
ArrayRef<StringRef> formalParamNames,
bool hasContainingModule) {
SmallVector<Attribute> fieldNames;
SmallVector<NamedAttribute> fieldTypes;
for (unsigned i = 0, e = moduleLike.getNumPorts(); i < e; ++i) {
auto type = moduleLike.getPortType(i);
if (!isa<PropertyType>(type))
continue;
auto direction = moduleLike.getPortDirection(i);
if (direction != Direction::In) {
auto name = moduleLike.getPortNameAttr(i);
fieldNames.push_back(name);
fieldTypes.push_back(NamedAttribute(name, TypeAttr::get(type)));
}
}
checkAddContainingModulePorts(hasContainingModule, builder, fieldNames,
fieldTypes);
return builder.create<om::ClassExternOp>(
moduleLike.getLoc(), name, formalParamNames, fieldNames, fieldTypes);