8000 [FIRRTL] DropConst pass by trilorez · Pull Request #5152 · llvm/circt · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

[FIRRTL] DropConst pass #5152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
May 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions include/circt/Dialect/FIRRTL/FIRRTLTypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,9 @@ class FIRRTLBaseType
/// Return a 'const' or non-'const' version of this type.
FIRRTLBaseType getConstType(bool isConst);

/// Return this type with a 'const' modifiers dropped
FIRRTLBaseType getAllConstDroppedType();

/// Return this type with all ground types replaced with UInt<1>. This is
/// used for `mem` operations.
FIRRTLBaseType getMaskType();
Expand Down
9 changes: 9 additions & 0 deletions include/circt/Dialect/FIRRTL/FIRRTLTypesImpl.td
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@ def FVectorImpl : BaseVectorTypeImpl<"FVector","::circt::firrtl::FIRRTLBaseType"
let firrtlExtraClassDeclaration = [{
/// Return this type with any flip types recursively removed from itself.
FIRRTLBaseType getPassiveType();

/// Return this type with a 'const' modifiers dropped
FVectorType getAllConstDroppedType();
}];
}

Expand Down Expand Up @@ -331,6 +334,9 @@ def BundleImpl : BaseBundleTypeImpl<"Bundle","::circt::firrtl::FIRRTLBaseType",
let firrtlExtraClassDeclaration = [{
/// Return this type with any flip types recursively removed from itself.
FIRRTLBaseType getPassiveType();

/// Return this type with a 'const' modifiers dropped
BundleType getAllConstDroppedType();
}];
}

Expand Down Expand Up @@ -372,6 +378,9 @@ def FEnumImpl : FIRRTLImplType<"FEnum", [FieldIDTypeInterface]> {

FEnumType getConstType(bool isConst);

/// Return this type with a 'const' modifiers dropped
FEnumType getAllConstDroppedType();

/// Look up an element's index by name. This returns None on failure.
std::optional<unsigned> getElementIndex(StringAttr name);
std::optional<unsigned> getElementIndex(StringRef name);
Expand Down
3 changes: 2 additions & 1 deletion include/circt/Dialect/FIRRTL/FIRRTLVisitors.h
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class ExprVisitor {
TailPrimOp, VerbatimExprOp, HWStructCastOp, BitCastOp, RefSendOp,
RefResolveOp, RefSubOp,
// Casts to deal with weird stuff
UninferredResetCastOp, UninferredWidthCastOp,
UninferredResetCastOp, UninferredWidthCastOp, ConstCastOp,
mlir::UnrealizedConversionCastOp>([&](auto expr) -> ResultType {
return thisCast->visitExpr(expr, args...);
})
Expand Down Expand Up @@ -174,6 +174,7 @@ class ExprVisitor {
HANDLE(HWStructCastOp, Unhandled);
HANDLE(UninferredResetCastOp, Unhandled);
HANDLE(UninferredWidthCastOp, Unhandled);
HANDLE(ConstCastOp, Unhandled);
HANDLE(mlir::UnrealizedConversionCastOp, Unhandled);
HANDLE(BitCastOp, Unhandled);
#undef HANDLE
Expand Down
2 changes: 2 additions & 0 deletions include/circt/Dialect/FIRRTL/Passes.h
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ std::unique_ptr<mlir::Pass> createVectorizationPass();

std::unique_ptr<mlir::Pass> createInjectDUTHierarchyPass();

std::unique_ptr<mlir::Pass> createDropConstPass();

/// Configure which values will be explicitly preserved by the DropNames pass.
namespace PreserveValues {
enum PreserveMode {
Expand Down
12 changes: 12 additions & 0 deletions include/circt/Dialect/FIRRTL/Passes.td
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,18 @@ def VBToBV : Pass<"firrtl-vb-to-bv", "firrtl::CircuitOp"> {
let constructor = "circt::firrtl::createVBToBVPass()";
}

def DropConst : InterfacePass<"firrtl-drop-const", "firrtl::FModuleLike"> {
let summary = "Drop 'const' modifier from types";
let description = [{
This pass drops the 'const' modifier from all types and removes all
const-cast ops.

This simplifies downstream passes and folds so that they do not need to
take 'const' into account.
}];
let constructor = "circt::firrtl::createDropConstPass()";
}

def FinalizeIR : Pass<"firrtl-finalize-ir", "mlir::ModuleOp"> {
let summary = "Perform final IR mutations after ExportVerilog";
let description = [{
Expand Down
134 changes: 129 additions & 5 deletions lib/Dialect/FIRRTL/FIRRTLOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2331,6 +2331,124 @@ static LogicalResult checkConnectFlow(Operation *connect) {
return success();
}

// NOLINTBEGIN(misc-no-recursion)
/// Checks if the type has any 'const' leaf elements . If `isFlip` is `true`,
/// the `const` leaf is not considered to be driven.
static bool isConstFieldDriven(FIRRTLBaseType type, bool isFlip = false,
bool outerTypeIsConst = false) {
auto typeIsConst = outerTypeIsConst || type.isConst();

if (typeIsConst && type.isPassive())
return !isFlip;

if (auto bundleType = dyn_cast<BundleType>(type))
return llvm::any_of(bundleType.getElements(), [&](auto &element) {
return isConstFieldDriven(element.type, isFlip ^ element.isFlip,
typeIsCons AE96 t);
});

if (auto vectorType = type.dyn_cast<FVectorType>())
return isConstFieldDriven(vectorType.getElementType(), isFlip, typeIsConst);

if (typeIsConst)
return !isFlip;
return false;
}
// NOLINTEND(misc-no-recursion)

/// Checks that connections to 'const' destinations are not dependent on
/// non-'const' conditions in when blocks.
static LogicalResult checkConnectConditionality(FConnectLike connect) {
auto dest = connect.getDest();
auto destType = dest.getType().dyn_cast<FIRRTLBaseType>();
auto src = connect.getSrc();
auto srcType = src.getType().dyn_cast<FIRRTLBaseType>();
if (!destType || !srcType)
return success();

auto destRefinedType = destType;
auto srcRefinedType = srcType;

/// Looks up the value's defining op until the defining op is null or a
/// declaration of the value. If a SubAccessOp is encountered with a 'const'
/// input, `originalFieldType` is made 'const'.
auto findFieldDeclarationRefiningFieldType =
[](Value value, FIRRTLBaseType &originalFieldType) -> Value {
while (auto *definingOp = value.getDefiningOp()) {
bool shouldContinue = true;
TypeSwitch<Operation *>(definingOp)
.Case<SubfieldOp, SubindexOp>([&](auto op) { value = op.getInput(); })
.Case<SubaccessOp>([&](SubaccessOp op) {
if (op.getInput()
.getType()
.getElementTypePreservingConst()
.isConst())
originalFieldType = originalFieldType.getConstType(true);
value = op.getInput();
})
.Default([&](Operation *) { shouldContinue = false; });
if (!shouldContinue)
break;
}
return value;
};

auto destDeclaration =
findFieldDeclarationRefiningFieldType(dest, destRefinedType);
auto srcDeclaration =
findFieldDeclarationRefiningFieldType(src, srcRefinedType);

auto checkConstConditionality = [&](Value value, FIRRTLBaseType type,
Value declaration) -> LogicalResult {
auto *declarationBlock = declaration.getParentBlock();
auto *block = connect->getBlock();
while (block && block != declarationBlock) {
auto *parentOp = block->getParentOp();

if (auto whenOp = dyn_cast<WhenOp>(parentOp);
whenOp && !whenOp.getCondition().getType().isConst()) {
if (type.isConst())
return connect.emitOpError()
<< "assignment to 'const' type " << type
<< " is dependent on a non-'const' condition";
return connect->emitOpError()
<< "assignment to nested 'const' member of type " << type
<< " is dependent on a non-'const' condition";
}

block = parentOp->getBlock();
}
return success();
};

auto emitSubaccessError = [&] {
return connect.emitError(
"assignment to non-'const' subaccess of 'const' type is disallowed");
};

// Check destination if it contains 'const' leaves
if (destRefinedType.containsConst() && isConstFieldDriven(destRefinedType)) {
// Disallow assignment to non-'const' subaccesses of 'const' types
if (destType != destRefinedType)
return emitSubaccessError();

if (failed(checkConstConditionality(dest, destType, destDeclaration)))
return failure();
}

// Check source if it contains 'const' 'flip' leaves
if (srcRefinedType.containsConst() &&
isConstFieldDriven(srcRefinedType, /*isFlip=*/true)) {
// Disallow assignment to non-'const' subaccesses of 'const' types
if (srcType != srcRefinedType)
return emitSubaccessError();
if (failed(checkConstConditionality(src, srcType, srcDeclaration)))
return failure();
}

return success();
}

LogicalResult ConnectOp::verify() {
auto dstType = getDest().getType();
auto srcType = getSrc().getType();
Expand Down Expand Up @@ -2360,6 +2478,9 @@ LogicalResult ConnectOp::verify() {
if (failed(checkConnectFlow(*this)))
return failure();

if (failed(checkConnectConditionality(*this)))
return failure();

return success();
}

Expand All @@ -2376,6 +2497,9 @@ LogicalResult StrictConnectOp::verify() {
if (failed(checkConnectFlow(*this)))
return failure();

if (failed(checkConnectConditionality(*this)))
return failure();

return success();
}

Expand Down Expand Up @@ -2680,8 +2804,8 @@ ParseResult ConstantOp::parse(OpAsmParser &parser, OperationState &result) {
// top bits if it is a positive number.
value = value.sext(width);
} else if (width < value.getBitWidth()) {
// The parser can return an unnecessarily wide result with leading zeros.
// This isn't a problem, but truncating off bits is bad.
// The parser can return an unnecessarily wide result with leading
// zeros. This isn't a problem, but truncating off bits is bad.
if (value.getNumSignBits() < value.getBitWidth() - width)
return parser.emitError(loc, "constant too large for result type ")
<< resultType;
Expand Down Expand Up @@ -3313,9 +3437,9 @@ FIRRTLType SubaccessOp::inferReturnType(ValueRange operands,
indexType);

if (auto vectorType = inType.dyn_cast<FVectorType>()) {
auto elementType = vectorType.getElementType();
return elementType.getConstType(
(elementType.isConst() || vectorType.isConst()) && isConst(indexType));
if (isConst(indexType))
return vectorType.getElementTypePreservingConst();
return vectorType.getElementType().getAllConstDroppedType();
}

return emitInferRetTypeError(loc, "subaccess requires vector operand, not ",
Expand Down
44 changes: 44 additions & 0 deletions lib/Dialect/FIRRTL/FIRRTLTypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,19 @@ FIRRTLBaseType FIRRTLBaseType::getConstType(bool isConst) {
});
}

/// Return this type with a 'const' modifiers dropped
FIRRTLBaseType FIRRTLBaseType::getAllConstDroppedType() {
return TypeSwitch<FIRRTLBaseType, FIRRTLBaseType>(*this)
.Case<ClockType, ResetType, AsyncResetType, AnalogType, SIntType,
UIntType>([&](auto type) { return type.getConstType(false); })
.Case<BundleType, FVectorType, FEnumType>(
[&](auto type) { return type.getAllConstDroppedType(); })
.Default([](Type) {
llvm_unreachable("unknown FIRRTL type");
return FIRRTLBaseType();
});
}

/// Return this type with all ground types replaced with UInt<1>. This is
/// used for `mem` operations.
FIRRTLBaseType FIRRTLBaseType::getMaskType() {
Expand Down Expand Up @@ -1220,6 +1233,18 @@ BundleType BundleType::getConstType(bool isConst) {
return get(getContext(), getElements(), isConst);
}

BundleType BundleType::getAllConstDroppedType() {
if (!containsConst())
return *this;

SmallVector<BundleElement> constDroppedElements(
llvm::map_range(getElements(), [](BundleElement element) {
element.type = element.type.getAllConstDroppedType();
return element;
}));
return get(getContext(), constDroppedElements, false);
}

std::optional<unsigned> BundleType::getElementIndex(StringAttr name) {
for (const auto &it : llvm::enumerate(getElements())) {
auto element = it.value();
Expand Down Expand Up @@ -1614,6 +1639,13 @@ FVectorType FVectorType::getConstType(bool isConst) {
return get(getElementType(), getNumElements(), isConst);
}

FVectorType FVectorType::getAllConstDroppedType() {
if (!containsConst())
return *this;
return get(getElementType().getAllConstDroppedType(), getNumElements(),
false);
}

uint64_t FVectorType::getFieldID(uint64_t index) {
return 1 + index * (getElementType().getMaxFieldID() + 1);
}
Expand Down Expand Up @@ -1845,6 +1877,18 @@ FEnumType FEnumType::getConstType(bool isConst) {
return get(getContext(), getElements(), isConst);
}

FEnumType FEnumType::getAllConstDroppedType() {
if (!containsConst())
return *this;

SmallVector<EnumElement> constDroppedElements(
llvm::map_range(getElements(), [](EnumElement element) {
element.type = element.type.getAllConstDroppedType();
return element;
}));
return get(getContext(), constDroppedElements, false);
}

/// Return a pair with the 'isPassive' and 'containsAnalog' bits.
RecursiveTypeProperties FEnumType::getRecursiveTypeProperties() const {
return getImpl()->recProps;
Expand Down
1 change: 1 addition & 0 deletions lib/Dialect/FIRRTL/Transforms/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ add_circt_dialect_library(CIRCTFIRRTLTransforms
CheckCombLoops.cpp
CreateSiFiveMetadata.cpp
Dedup.cpp
DropConst.cpp
DropName.cpp
EmitOMIR.cpp
ExpandWhens.cpp
Expand Down
Loading
0