21#include "mlir/IR/Iterators.h"
22#include "mlir/IR/Threading.h"
23#include "mlir/Pass/Pass.h"
24#include "llvm/ADT/APSInt.h"
25#include "llvm/ADT/TinyPtrVector.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ScopedPrinter.h"
31#define GEN_PASS_DEF_IMCONSTPROP
32#include "circt/Dialect/FIRRTL/Passes.h.inc"
37using namespace firrtl;
39#define DEBUG_TYPE "IMCP"
43 return isa<WireOp, RegResetOp, RegOp>(op);
48 return isa<SubindexOp, SubaccessOp, SubfieldOp, OpenSubfieldOp,
49 OpenSubindexOp, RefSubOp>(op);
55 return isa<NodeOp, RefResolveOp, RefSendOp>(op);
64 if (type_isa<RefType>(op->getResult(0).getType()))
98 LatticeValue() : valueAndTag(nullptr, Kind::Unknown) {}
100 LatticeValue(IntegerAttr attr)
101 : valueAndTag(attr, Kind::Constant) {}
102 LatticeValue(StringAttr attr)
103 : valueAndTag(attr, Kind::Constant) {}
105 static LatticeValue getOverdefined() {
107 result.markOverdefined();
111 bool isUnknown()
const {
return valueAndTag.getInt() == Kind::Unknown; }
112 bool isConstant()
const {
return valueAndTag.getInt() == Kind::Constant; }
113 bool isOverdefined()
const {
114 return valueAndTag.getInt() == Kind::Overdefined;
118 void markOverdefined() {
119 valueAndTag.setPointerAndInt(
nullptr, Kind::Overdefined);
123 void markConstant(IntegerAttr value) {
124 valueAndTag.setPointerAndInt(value, Kind::Constant);
129 Attribute getValue()
const {
return valueAndTag.getPointer(); }
139 bool mergeIn(LatticeValue rhs) {
141 if (isOverdefined() || rhs.isUnknown())
146 valueAndTag = rhs.valueAndTag;
153 if (valueAndTag != rhs.valueAndTag) {
160 bool operator==(
const LatticeValue &other)
const {
161 return valueAndTag == other.valueAndTag;
163 bool operator!=(
const LatticeValue &other)
const {
164 return valueAndTag != other.valueAndTag;
170 llvm::PointerIntPair<Attribute, 2, Kind> valueAndTag;
176 const LatticeValue &lattice) {
177 if (lattice.isUnknown())
178 return os <<
"<Unknown>";
179 if (lattice.isOverdefined())
180 return os <<
"<Overdefined>";
181 return os <<
"<" << lattice.getConstant() <<
">";
185struct IMConstPropPass
186 :
public circt::firrtl::impl::IMConstPropBase<IMConstPropPass> {
188 void runOnOperation()
override;
189 void rewriteModuleBody(FModuleOp module);
192 bool isBlockExecutable(Block *block)
const {
193 return executableBlocks.count(block);
196 bool isOverdefined(
FieldRef value)
const {
197 auto it = latticeValues.find(value);
198 return it != latticeValues.end() && it->second.isOverdefined();
203 void markOverdefined(Value value) {
204 FieldRef fieldRef = getOrCacheFieldRefFromValue(value);
205 auto firrtlType = type_dyn_cast<FIRRTLType>(value.getType());
206 if (!firrtlType || type_isa<PropertyType, DomainType>(firrtlType)) {
207 markOverdefined(fieldRef);
218 void markOverdefined(
FieldRef value) {
219 auto &entry = latticeValues[value];
220 if (!entry.isOverdefined()) {
223 <<
"Setting overdefined : (" <<
getFieldName(value).first <<
")\n";
225 entry.markOverdefined();
226 changedLatticeValueWorklist.push_back(value);
233 void mergeLatticeValue(
FieldRef value, LatticeValue &valueEntry,
234 LatticeValue source) {
235 if (valueEntry.mergeIn(source)) {
238 <<
"Changed to " << valueEntry <<
" : (" << value <<
")\n";
240 changedLatticeValueWorklist.push_back(value);
244 void mergeLatticeValue(
FieldRef value, LatticeValue source) {
246 if (source.isUnknown())
248 mergeLatticeValue(value, latticeValues[value], source);
254 auto it = latticeValues.find(from);
255 if (it == latticeValues.end())
257 mergeLatticeValue(result, it->second);
260 void mergeLatticeValue(Value result, Value from) {
261 FieldRef fieldRefFrom = getOrCacheFieldRefFromValue(from);
262 FieldRef fieldRefResult = getOrCacheFieldRefFromValue(result);
263 if (!type_isa<FIRRTLType>(result.getType()))
264 return mergeLatticeValue(fieldRefResult, fieldRefFrom);
266 if (type_isa<PropertyType, DomainType>(result.getType()))
267 return mergeLatticeValue(fieldRefResult, fieldRefFrom);
269 [&](uint64_t fieldID,
auto,
auto) {
270 mergeLatticeValue(fieldRefResult.getSubField(fieldID),
271 fieldRefFrom.getSubField(fieldID));
280 void setLatticeValue(
FieldRef value, LatticeValue source) {
282 if (source.isUnknown())
286 auto &valueEntry = latticeValues[value];
287 if (valueEntry != source) {
288 changedLatticeValueWorklist.push_back(value);
296 FieldRef getOrCacheFieldRefFromValue(Value value) {
297 if (!value.getDefiningOp() || !
isAggregate(value.getDefiningOp()))
299 auto &fieldRef = valueToFieldRef[value];
309 bool allowTruncation =
false);
312 void markBlockExecutable(Block *block);
313 void markWireOp(WireOp wireOrReg);
314 void markMemOp(MemOp mem);
315 void markDPICallIntrinsicOp(DPICallIntrinsicOp dpi);
317 void markInvalidValueOp(InvalidValueOp invalid);
318 void markAggregateConstantOp(AggregateConstantOp constant);
319 void markInstanceLike(FInstanceLike instance);
320 void markInstanceTarget(FInstanceLike instance, Operation *op);
321 void markObjectOp(ObjectOp
object);
322 template <
typename OpTy>
323 void markConstantValueOp(OpTy op);
325 void visitConnectLike(FConnectLike connect,
FieldRef changedFieldRef);
326 void visitRefSend(RefSendOp send,
FieldRef changedFieldRef);
328 void mergeOnlyChangedLatticeValue(Value dest, Value src,
330 void visitNode(NodeOp node,
FieldRef changedFieldRef);
331 void visitOperation(Operation *op,
FieldRef changedFieldRef);
338 DenseMap<FieldRef, LatticeValue> latticeValues;
341 SmallPtrSet<Block *, 16> executableBlocks;
345 SmallVector<FieldRef, 64> changedLatticeValueWorklist;
348 DenseMap<FieldRef, llvm::TinyPtrVector<Operation *>> fieldRefToUsers;
352 llvm::DenseMap<Value, FieldRef> valueToFieldRef;
356 DenseMap<BlockArgument, llvm::TinyPtrVector<Value>>
357 resultPortToInstanceResultMapping;
361 llvm::ScopedPrinter logger{llvm::dbgs()};
367void IMConstPropPass::runOnOperation() {
368 auto circuit = getOperation();
370 { logger.startLine() <<
"IMConstProp : " << circuit.getName() <<
"\n"; });
372 instanceGraph = &getAnalysis<InstanceGraph>();
375 for (
auto &op : circuit.getOps()) {
377 if (
auto module = dyn_cast<FModuleOp>(op)) {
378 if (module.isPublic()) {
379 markBlockExecutable(module.getBodyBlock());
381 markOverdefined(port);
388 if (isa<hw::HierPathOp>(op))
395 auto symbolUses = SymbolTable::getSymbolUses(&op);
398 for (
const auto &use : *symbolUses) {
399 if (
auto symRef = dyn_cast<FlatSymbolRefAttr>(use.getSymbolRef())) {
400 if (
auto *igNode = instanceGraph->lookupOrNull(symRef.getAttr())) {
401 if (
auto module = dyn_cast<FModuleOp>(*igNode->getModule())) {
402 LLVM_DEBUG(llvm::dbgs()
403 <<
"Unknown use of " << module.getModuleNameAttr()
404 <<
" in " << op.getName()
405 <<
", marking inputs as overdefined\n");
406 markBlockExecutable(module.getBodyBlock());
408 markOverdefined(port);
416 while (!changedLatticeValueWorklist.empty()) {
417 FieldRef changedFieldRef = changedLatticeValueWorklist.pop_back_val();
418 for (Operation *user : fieldRefToUsers[changedFieldRef]) {
419 if (isBlockExecutable(user->getBlock()))
420 visitOperation(user, changedFieldRef);
425 mlir::parallelForEach(circuit.getContext(),
426 circuit.getBodyBlock()->getOps<FModuleOp>(),
427 [&](
auto op) { rewriteModuleBody(op); });
430 instanceGraph =
nullptr;
431 latticeValues.clear();
432 executableBlocks.clear();
433 assert(changedLatticeValueWorklist.empty());
434 fieldRefToUsers.clear();
435 valueToFieldRef.clear();
436 resultPortToInstanceResultMapping.clear();
442LatticeValue IMConstPropPass::getExtendedLatticeValue(
FieldRef value,
444 bool allowTruncation) {
446 auto it = latticeValues.find(value);
447 if (it == latticeValues.end())
448 return LatticeValue();
450 auto result = it->second;
452 if (result.isUnknown() || result.isOverdefined())
456 if (isa<PropertyType, DomainType>(destType))
459 auto constant = result.getConstant();
462 auto intAttr = dyn_cast<IntegerAttr>(constant);
463 assert(intAttr &&
"unsupported lattice attribute kind");
468 if (
auto boolAttr = dyn_cast<BoolAttr>(intAttr))
474 return LatticeValue::getOverdefined();
477 auto resultConstant = intAttr.getAPSInt();
478 auto destWidth = baseType.getBitWidthOrSentinel();
480 return LatticeValue::getOverdefined();
481 if (resultConstant.getBitWidth() == (
unsigned)destWidth)
486 return LatticeValue(IntegerAttr::get(destType.getContext(), resultConstant));
493void IMConstPropPass::markBlockExecutable(Block *block) {
494 if (!executableBlocks.insert(block).second)
499 for (
auto ba : block->getArguments())
503 for (
auto &op : *block) {
505 TypeSwitch<Operation *>(&op)
506 .Case<RegOp, RegResetOp>(
507 [&](
auto reg) { markOverdefined(op.getResult(0)); })
508 .Case<WireOp>([&](
auto wire) { markWireOp(wire); })
509 .Case<ConstantOp, SpecialConstantOp, StringConstantOp,
510 FIntegerConstantOp, BoolConstantOp>(
511 [&](
auto constOp) { markConstantValueOp(constOp); })
512 .Case<AggregateConstantOp>(
513 [&](
auto aggConstOp) { markAggregateConstantOp(aggConstOp); })
514 .Case<InvalidValueOp>(
515 [&](
auto invalid) { markInvalidValueOp(invalid); })
516 .Case<FInstanceLike>([&](
auto instance) { markInstanceLike(instance); })
517 .Case<ObjectOp>([&](
auto obj) { markObjectOp(obj); })
518 .Case<MemOp>([&](
auto mem) { markMemOp(mem); })
520 [&](
auto layer) { markBlockExecutable(layer.getBody(0)); })
521 .Case<DPICallIntrinsicOp>(
522 [&](
auto dpi) { markDPICallIntrinsicOp(dpi); })
523 .Default([&](
auto _) {
524 if (isa<mlir::UnrealizedConversionCastOp, VerbatimExprOp,
525 VerbatimWireOp, SubaccessOp>(op) ||
526 op.getNumOperands() == 0) {
530 for (
auto result : op.getResults())
531 markOverdefined(result);
543 bool hasAggregateOperand =
544 llvm::any_of(op.getOperandTypes(), [](Type type) {
545 return type_isa<FVectorType, BundleType>(type);
548 for (
auto result : op.getResults())
549 if (hasAggregateOperand ||
550 type_isa<FVectorType, BundleType>(result.getType()))
551 markOverdefined(result);
558 for (
auto operand : op.getOperands()) {
559 auto fieldRef = getOrCacheFieldRefFromValue(operand);
560 auto firrtlType = type_dyn_cast<FIRRTLType>(operand.getType());
564 if (type_isa<PropertyType, DomainType>(firrtlType)) {
565 fieldRefToUsers[fieldRef].push_back(&op);
569 fieldRefToUsers[fieldRef.
getSubField(fieldID)].push_back(&op);
577void IMConstPropPass::markWireOp(WireOp wire) {
578 auto type = type_dyn_cast<FIRRTLType>(wire.getResult().getType());
579 if (!type ||
hasDontTouch(wire.getResult()) || wire.isForceable()) {
580 for (
auto result : wire.getResults())
581 markOverdefined(result);
588void IMConstPropPass::markMemOp(MemOp mem) {
589 for (
auto result : mem.getResults())
590 markOverdefined(result);
593void IMConstPropPass::markDPICallIntrinsicOp(DPICallIntrinsicOp dpi) {
594 if (
auto result = dpi.getResult())
595 markOverdefined(result);
598template <
typename OpTy>
599void IMConstPropPass::markConstantValueOp(OpTy op) {
600 mergeLatticeValue(getOrCacheFieldRefFromValue(op),
601 LatticeValue(op.getValueAttr()));
604void IMConstPropPass::markAggregateConstantOp(AggregateConstantOp constant) {
605 walkGroundTypes(constant.getType(), [&](uint64_t fieldID,
auto,
auto) {
606 mergeLatticeValue(FieldRef(constant, fieldID),
607 LatticeValue(cast<IntegerAttr>(
608 constant.getAttributeFromFieldID(fieldID))));
612void IMConstPropPass::markInvalidValueOp(InvalidValueOp invalid) {
613 markOverdefined(invalid.getResult());
618void IMConstPropPass::markInstanceLike(FInstanceLike instance) {
619 for (
auto moduleName :
620 instance.getReferencedModuleNamesAttr().getAsRange<StringAttr>()) {
621 auto *node = instanceGraph->lookup(moduleName);
622 Operation *op = node->getModule().getOperation();
623 markInstanceTarget(instance, op);
629void IMConstPropPass::markInstanceTarget(FInstanceLike instance,
633 if (!isa<FModuleOp>(op)) {
634 auto module = dyn_cast<FModuleLike>(op);
635 for (
size_t resultNo = 0, e = instance.getNumPorts(); resultNo != e;
637 auto portVal = instance->getResult(resultNo);
639 if (module.getPortDirection(resultNo) == Direction::In)
643 markOverdefined(portVal);
648 auto fModule = cast<FModuleOp>(op);
649 markBlockExecutable(fModule.getBodyBlock());
653 for (
size_t resultNo = 0, e = instance.getNumPorts(); resultNo != e;
655 auto instancePortVal = instance->getResult(resultNo);
658 if (fModule.getPortDirection(resultNo) == Direction::In)
663 BlockArgument modulePortVal = fModule.getArgument(resultNo);
665 resultPortToInstanceResultMapping[modulePortVal].push_back(instancePortVal);
669 mergeLatticeValue(instancePortVal, modulePortVal);
673void IMConstPropPass::markObjectOp(ObjectOp obj) {
675 markOverdefined(obj);
678static std::optional<uint64_t>
681 assert(!type_isa<RefType>(connectionType));
692void IMConstPropPass::mergeOnlyChangedLatticeValue(Value dest, Value src,
696 auto destType = dest.getType();
697 if (
auto refType = type_dyn_cast<RefType>(destType))
698 destType = refType.getType();
700 if (!isa<FIRRTLType>(destType)) {
703 markOverdefined(src);
704 return markOverdefined(dest);
707 auto fieldRefSrc = getOrCacheFieldRefFromValue(src);
708 auto fieldRefDest = getOrCacheFieldRefFromValue(dest);
712 if (
auto srcOffset =
getFieldIDOffset(changedFieldRef, destType, fieldRefSrc))
713 mergeLatticeValue(fieldRefDest.getSubField(*srcOffset),
714 fieldRefSrc.getSubField(*srcOffset));
718 if (
auto destOffset =
720 mergeLatticeValue(fieldRefDest.getSubField(*destOffset),
721 fieldRefSrc.getSubField(*destOffset));
724void IMConstPropPass::visitConnectLike(FConnectLike connect,
727 auto destType =
connect.getDest().getType();
728 if (
auto refType = type_dyn_cast<RefType>(destType))
729 destType = refType.getType();
732 if (!isa<FIRRTLType>(destType)) {
733 markOverdefined(
connect.getSrc());
734 return markOverdefined(
connect.getDest());
737 auto fieldRefSrc = getOrCacheFieldRefFromValue(
connect.getSrc());
738 auto fieldRefDest = getOrCacheFieldRefFromValue(
connect.getDest());
739 if (
auto subaccess = fieldRefDest.getValue().getDefiningOp<SubaccessOp>()) {
743 Value parent = subaccess.getInput();
744 while (parent.getDefiningOp() &&
745 parent.getDefiningOp()->getNumOperands() > 0)
746 parent = parent.getDefiningOp()->getOperand(0);
747 return markOverdefined(parent);
750 auto propagateElementLattice = [&](uint64_t fieldID,
FIRRTLType destType) {
751 auto fieldRefDestConnected = fieldRefDest.getSubField(fieldID);
752 assert(!firrtl::type_isa<FIRRTLBaseType>(destType) ||
753 firrtl::type_cast<FIRRTLBaseType>(destType).isGround());
757 getExtendedLatticeValue(fieldRefSrc.getSubField(fieldID), destType);
758 if (srcValue.isUnknown())
763 if (
auto blockArg = dyn_cast<BlockArgument>(fieldRefDest.getValue())) {
764 for (
auto userOfResultPort : resultPortToInstanceResultMapping[blockArg])
769 return mergeLatticeValue(fieldRefDestConnected, srcValue);
772 auto dest = cast<mlir::OpResult>(fieldRefDest.getValue());
777 return mergeLatticeValue(fieldRefDestConnected, srcValue);
781 if (
auto instance = dest.getDefiningOp<FInstanceLike>()) {
783 mergeLatticeValue(fieldRefDestConnected, srcValue);
785 for (
auto moduleName :
786 instance.getReferencedModuleNamesAttr().getAsRange<StringAttr>()) {
787 auto *node = instanceGraph->lookup(moduleName);
788 auto mod = dyn_cast<FModuleOp>(node->getModule().getOperation());
792 BlockArgument modulePortVal = mod.getArgument(dest.getResultNumber());
794 FieldRef(modulePortVal, fieldRefDestConnected.getFieldID()),
801 if (isa_and_nonnull<MemOp, ObjectSubfieldOp>(dest.getDefiningOp()))
804 connect.emitError(
"connectlike operation unhandled by IMConstProp")
805 .attachNote(
connect.getDest().getLoc())
806 <<
"connect destination is here";
809 if (
auto srcOffset =
getFieldIDOffset(changedFieldRef, destType, fieldRefSrc))
810 propagateElementLattice(
812 firrtl::type_cast<FIRRTLType>(
815 if (
auto relativeDest =
817 propagateElementLattice(
819 firrtl::type_cast<FIRRTLType>(
823void IMConstPropPass::visitRefSend(RefSendOp send,
FieldRef changedFieldRef) {
825 return mergeOnlyChangedLatticeValue(send.getResult(), send.getBase(),
829void IMConstPropPass::visitRefResolve(RefResolveOp
resolve,
833 return mergeOnlyChangedLatticeValue(
resolve.getResult(),
resolve.getRef(),
837void IMConstPropPass::visitNode(NodeOp node,
FieldRef changedFieldRef) {
838 if (
hasDontTouch(node.getResult()) || node.isForceable()) {
839 for (
auto result : node.getResults())
840 markOverdefined(result);
844 return mergeOnlyChangedLatticeValue(node.getResult(), node.getInput(),
854void IMConstPropPass::visitOperation(Operation *op,
FieldRef changedField) {
856 if (
auto connectLikeOp = dyn_cast<FConnectLike>(op))
857 return visitConnectLike(connectLikeOp, changedField);
858 if (
auto sendOp = dyn_cast<RefSendOp>(op))
859 return visitRefSend(sendOp, changedField);
860 if (
auto resolveOp = dyn_cast<RefResolveOp>(op))
861 return visitRefResolve(resolveOp, changedField);
862 if (
auto nodeOp = dyn_cast<NodeOp>(op))
863 return visitNode(nodeOp, changedField);
874 auto isOverdefinedFn = [&](Value value) {
875 return isOverdefined(getOrCacheFieldRefFromValue(value));
877 if (llvm::all_of(op->getResults(), isOverdefinedFn))
882 if (op->getNumOperands() > 128) {
883 for (
auto value : op->getResults())
884 markOverdefined(value);
890 SmallVector<Attribute, 8> operandConstants;
891 operandConstants.reserve(op->getNumOperands());
892 bool hasUnknown =
false;
893 for (Value operand : op->getOperands()) {
895 auto &operandLattice = latticeValues[getOrCacheFieldRefFromValue(operand)];
900 if (operandLattice.isUnknown())
905 if (operandLattice.isConstant())
906 operandConstants.push_back(operandLattice.getValue());
908 operandConstants.push_back({});
913 SmallVector<OpFoldResult, 8> foldResults;
914 foldResults.reserve(op->getNumResults());
915 if (failed(op->fold(operandConstants, foldResults))) {
917 logger.startLine() <<
"Folding Failed operation : '" << op->getName()
923 for (
auto value : op->getResults())
924 markOverdefined(value);
929 logger.getOStream() <<
"\n";
930 logger.startLine() <<
"Folding operation : '" << op->getName() <<
"\n";
932 logger.getOStream() <<
"( ";
933 for (
auto cst : operandConstants)
935 logger.getOStream() <<
"{} ";
937 logger.getOStream() << cst <<
" ";
939 logger.getOStream() <<
") -> { ";
941 for (
auto &r : foldResults) {
942 logger.getOStream() << r <<
" ";
945 logger.getOStream() <<
"}\n";
952 if (foldResults.empty())
953 return visitOperation(op, changedField);
956 assert(foldResults.size() == op->getNumResults() &&
"invalid result size");
957 for (
unsigned i = 0, e = foldResults.size(); i != e; ++i) {
959 LatticeValue resultLattice;
960 OpFoldResult foldResult = foldResults[i];
961 if (Attribute foldAttr = dyn_cast<Attribute>(foldResult)) {
962 if (
auto intAttr = dyn_cast<IntegerAttr>(foldAttr))
963 resultLattice = LatticeValue(intAttr);
964 else if (
auto strAttr = dyn_cast<StringAttr>(foldAttr))
965 resultLattice = LatticeValue(strAttr);
967 resultLattice = LatticeValue::getOverdefined();
970 latticeValues[getOrCacheFieldRefFromValue(cast<Value>(foldResult))];
973 mergeLatticeValue(getOrCacheFieldRefFromValue(op->getResult(i)),
978void IMConstPropPass::rewriteModuleBody(FModuleOp module) {
979 auto *body =
module.getBodyBlock();
981 if (!executableBlocks.count(body))
984 auto builder = OpBuilder::atBlockBegin(body);
988 auto cursor = firrtl::ConstantOp::create(builder, module.getLoc(), APSInt(1));
989 builder.setInsertionPoint(cursor);
992 DenseMap<std::pair<Attribute, Type>, Operation *> constPool;
994 std::function<Value(Attribute, Type, Location)> getConst =
995 [&](Attribute constantValue, Type type, Location loc) -> Value {
996 auto constIt = constPool.find({constantValue, type});
997 if (constIt != constPool.end()) {
998 auto *cst = constIt->second;
1000 cst->setLoc(builder.getFusedLoc({cst->getLoc(), loc}));
1001 return cst->getResult(0);
1003 OpBuilder::InsertionGuard x(builder);
1004 builder.setInsertionPoint(cursor);
1009 if (
auto refType = type_dyn_cast<RefType>(type)) {
1010 assert(!type_cast<RefType>(type).getForceable() &&
1011 "Attempting to materialize rwprobe of constant, shouldn't happen");
1012 auto inner = getConst(constantValue, refType.getType(), loc);
1014 cst = RefSendOp::create(builder, loc, inner);
1016 cst =
module->getDialect()->materializeConstant(builder, constantValue,
1018 assert(cst &&
"all FIRRTL constants can be materialized");
1019 constPool.insert({{constantValue, type}, cst});
1020 return cst->getResult(0);
1025 auto replaceValueIfPossible = [&](Value value) ->
bool {
1029 auto replaceIfNotConnect = [&value](Value replacement) {
1030 value.replaceUsesWithIf(replacement, [](OpOperand &operand) {
1031 return !isa<FConnectLike>(operand.getOwner()) ||
1032 operand.getOperandNumber() != 0;
1038 if (it == latticeValues.end() || it->second.isOverdefined() ||
1039 it->second.isUnknown())
1045 if (!type_isa<FIRRTLBaseType, RefType, FIntegerType, StringType, BoolType>(
1050 getConst(it->second.getValue(), value.getType(), value.
getLoc());
1052 replaceIfNotConnect(cstValue);
1057 for (
auto &port : body->getArguments())
1058 replaceValueIfPossible(port);
1066 bool aboveCursor =
false;
1067 module.walk<mlir::WalkOrder::PostOrder, mlir::ReverseIterator>(
1068 [&](Operation *op) {
1069 auto dropIfDead = [&](Operation *op, const Twine &debugPrefix) {
1070 if (op->use_empty() &&
1071 (wouldOpBeTriviallyDead(op) || isDeletableWireOrRegOrNode(op))) {
1073 logger.getOStream() << debugPrefix << " : " << *op << "\n";
1084 dropIfDead(op,
"Trivially dead materialized constant");
1085 return WalkResult::advance();
1091 return WalkResult::advance();
1095 if (
auto connect = dyn_cast<FConnectLike>(op)) {
1096 if (
auto *destOp =
connect.getDest().getDefiningOp()) {
1097 auto fieldRef = getOrCacheFieldRefFromValue(
connect.getDest());
1103 auto type = type_dyn_cast<FIRRTLType>(
connect.getDest().getType());
1105 return WalkResult::advance();
1106 auto baseType = type_dyn_cast<FIRRTLBaseType>(type);
1107 if (baseType && !baseType.isGround())
1108 return WalkResult::advance();
1110 !isOverdefined(fieldRef)) {
1115 return WalkResult::advance();
1120 if (op->getNumResults() != 1 && !isa<InstanceOp>(op))
1121 return WalkResult::advance();
1124 if (dropIfDead(op,
"Trivially dead"))
1125 return WalkResult::advance();
1129 if (op->hasTrait<mlir::OpTrait::ConstantLike>())
1130 return WalkResult::advance();
1133 builder.setInsertionPoint(op);
1134 bool foldedAny =
false;
1135 for (
auto result : op->getResults())
1136 foldedAny |= replaceValueIfPossible(result);
1142 if (foldedAny && dropIfDead(op,
"Made dead"))
1143 return WalkResult::advance();
1145 return WalkResult::advance();
assert(baseType &&"element must be base type")
static mlir::Operation * resolve(Context &context, mlir::SymbolRefAttr sym)
static std::optional< APSInt > getConstant(Attribute operand)
Determine the value of a constant operand for the sake of constant folding.
static bool isNodeLike(Operation *op)
static bool isWireOrReg(Operation *op)
Return true if this is a wire or register.
static bool isAggregate(Operation *op)
Return true if this is an aggregate indexer.
static std::optional< uint64_t > getFieldIDOffset(FieldRef changedFieldRef, Type connectionType, FieldRef connectedValueFieldRef)
static bool isDeletableWireOrRegOrNode(Operation *op)
Return true if this is a wire or register we're allowed to delete.
static unsigned getFieldID(BundleType type, unsigned index)
static Block * getBodyBlock(FModuleLike mod)
This class represents a reference to a specific field or element of an aggregate value.
FieldRef getSubField(unsigned subFieldID) const
Get a reference to a subfield.
unsigned getFieldID() const
Get the field ID of this FieldRef, which is a unique identifier mapped to a specific field in a bundl...
Value getValue() const
Get the Value which created this location.
Location getLoc() const
Get the location associated with the value of this field ref.
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
This graph tracks modules and where they are instantiated.
connect(destination, source)
FIRRTLBaseType getBaseType(Type type)
If it is a base type, return it as is.
FieldRef getFieldRefFromValue(Value value, bool lookThroughCasts=false)
Get the FieldRef from a value.
void walkGroundTypes(FIRRTLType firrtlType, llvm::function_ref< void(uint64_t, FIRRTLBaseType, bool)> fn)
Walk leaf ground types in the firrtlType and apply the function fn.
bool isConstant(Operation *op)
Return true if the specified operation has a constant value.
bool hasDontTouch(Value value)
Check whether a block argument ("port") or the operation defining a value has a DontTouch annotation,...
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const InstanceInfo::LatticeValue &value)
bool hasDroppableName(Operation *op)
Return true if the name is droppable.
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
::mlir::Type getFinalTypeByFieldID(Type type, uint64_t fieldID)
uint64_t getMaxFieldID(Type)
static bool operator==(const ModulePort &a, const ModulePort &b)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
APSInt extOrTruncZeroWidth(APSInt value, unsigned width)
A safe version of APSInt::extOrTrunc that will NOT assert on zero-width signed APSInts.
bool operator!=(uint64_t a, const FVInt &b)
reg(value, clock, reset=None, reset_value=None, name=None, sym_name=None)