46#include <mlir/IR/BuiltinOps.h>
47#include <mlir/IR/PatternMatch.h>
49#include <llvm/ADT/DenseMap.h>
50#include <llvm/ADT/DenseSet.h>
51#include <llvm/ADT/SmallVector.h>
52#include <llvm/ADT/StringMap.h>
53#include <llvm/Support/raw_ostream.h>
60#define GEN_PASS_DEF_TYPEVARINFERENCEPASS
66#define DEBUG_TYPE "llzk-infer-tvar"
97using SpecializedCallableCloneCache = DenseMap<Operation *, llvm::StringMap<SymbolRefAttr>>;
98using SpecializedTemplateCloneCache = DenseMap<Operation *, llvm::StringMap<StringAttr>>;
105static SmallVector<StringAttr> getStringPieces(SymbolRefAttr ref) {
106 return llvm::to_vector(llvm::map_range(
getPieces(ref), [](FlatSymbolRefAttr piece) {
107 return piece.getAttr();
112static StringAttr getFlatSymbolName(Attribute attr) {
113 auto symRef = llvm::dyn_cast_if_present<SymbolRefAttr>(attr);
114 if (!symRef || !symRef.getNestedReferences().empty()) {
117 return symRef.getRootReference();
128 std::optional<Type> declaredTy = op.
getTypeOpt();
132 auto tvarTy = llvm::dyn_cast<TypeVarType>(*declaredTy);
133 return tvarTy && tvarTy.getRefName() == op.getName();
142static bool isCurrentTemplateTypeVarParamSymbol(StringAttr symbolName, Operation *op) {
148 return paramOp && isTypeVarParam(paramOp);
152template <
typename ConverterT>
154convertTypeRange(TypeRange oldTypes, SmallVectorImpl<Type> &newTypes, ConverterT &converter) {
155 bool changed =
false;
156 newTypes.reserve(oldTypes.size());
157 for (Type oldTy : oldTypes) {
158 Type newTy = converter.convertType(oldTy);
159 newTypes.push_back(newTy);
160 changed |= newTy != oldTy;
166template <
typename ConverterT>
167static Type convertPodType(
PodType podTy, MLIRContext *ctx, ConverterT &converter) {
168 SmallVector<RecordAttr> newRecords;
169 bool changed =
false;
170 for (RecordAttr record : podTy.
getRecords()) {
171 Type newRecordTy = converter.convertType(record.getType());
172 newRecords.push_back(RecordAttr::get(ctx, record.getName(), newRecordTy));
173 changed |= newRecordTy != record.getType();
179template <
typename ConvertElementFn>
180static Type convertArrayElementType(
ArrayType arrTy, ConvertElementFn convertElement) {
189template <
typename ConverterT>
190static Type convertFunctionType(FunctionType funcTy, ConverterT &converter) {
191 SmallVector<Type> newInputs;
192 SmallVector<Type> newResults;
193 bool changed = convertTypeRange(funcTy.getInputs(), newInputs, converter);
194 changed |= convertTypeRange(funcTy.getResults(), newResults, converter);
195 return changed ? FunctionType::get(funcTy.getContext(), newInputs, newResults) : funcTy;
199template <
typename ConvertTypeFn,
typename ConvertNestedAttrFn>
200static Attribute convertTypeOrArrayAttr(
201 Attribute attr, MLIRContext *ctx, ConvertTypeFn convertType,
202 ConvertNestedAttrFn convertNestedAttr
207 if (
auto tyAttr = llvm::dyn_cast<TypeAttr>(attr)) {
208 Type newTy = convertType(tyAttr.getValue());
209 return newTy == tyAttr.getValue() ? attr : TypeAttr::get(newTy);
211 if (
auto arrAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
212 SmallVector<Attribute> newAttrs;
213 bool changed =
false;
214 for (Attribute nested : arrAttr.getValue()) {
215 Attribute newNested = convertNestedAttr(nested);
216 newAttrs.push_back(newNested);
217 changed |= newNested != nested;
219 return changed ? ArrayAttr::get(ctx, newAttrs) : attr;
226static bool templateArgUnifiesWithType(Attribute attr, Type expectedTy) {
227 Attribute expectedAttr = TypeAttr::get(expectedTy);
228 return typeParamsUnify(ArrayRef<Attribute> {attr}, ArrayRef<Attribute> {expectedAttr});
238class TypeVarReplacementConverter {
242 SmallVector<StringAttr> templatePath_;
244 SmallVector<StringAttr> oldParamOrder_;
246 DenseSet<StringAttr> removedParams_;
248 DenseMap<StringAttr, Type> replacements_;
250 bool trimResolvedParams_;
258 TypeVarReplacementConverter(
259 MLIRContext *c, ArrayRef<StringAttr> templatePath, ArrayRef<StringAttr> oldParamOrder,
260 const DenseMap<StringAttr, Type> &replacements,
bool trimResolvedParams =
true
262 : ctx_(c), templatePath_(templatePath), oldParamOrder_(oldParamOrder),
263 replacements_(replacements), trimResolvedParams_(trimResolvedParams) {
264 for (
const auto &entry : replacements_) {
265 removedParams_.insert(entry.first);
273 Type convertType(Type ty)
const {
274 DenseSet<StringAttr> resolvingParams;
275 return convertType(ty, resolvingParams);
280 Type convertType(Type ty, DenseSet<StringAttr> &resolvingParams)
const {
284 if (
auto tvarTy = llvm::dyn_cast<TypeVarType>(ty)) {
285 StringAttr paramName = tvarTy.getNameRef().getAttr();
286 auto it = replacements_.find(paramName);
287 if (it == replacements_.end()) {
290 if (!resolvingParams.insert(paramName).second) {
293 Type replacement = convertType(it->second, resolvingParams);
294 resolvingParams.erase(paramName);
297 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
298 return convertArrayElementType(arrTy, [
this, &resolvingParams](Type elemTy) {
299 return convertType(elemTy, resolvingParams);
302 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
303 return convertStructType(structTy, resolvingParams);
305 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
306 return convertPodType(podTy, ctx_, *
this);
308 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
309 return convertFunctionType(funcTy, *
this);
320 Attribute convertAttr(Attribute attr)
const {
321 DenseSet<StringAttr> resolvingParams;
322 return convertAttr(attr, resolvingParams);
327 LogicalResult validateOperation(Operation *op)
const {
328 if (
auto createOp = llvm::dyn_cast<CreateArrayOp>(op)) {
329 if (failed(validateCreateArrayOp(createOp))) {
333 if (
auto func = llvm::dyn_cast<FuncDefOp>(op)) {
334 if (failed(validateType(func.getFunctionType(), op))) {
338 for (Region ®ion : op->getRegions()) {
339 for (Block &block : region.getBlocks()) {
340 for (Type argTy : block.getArgumentTypes()) {
341 if (failed(validateType(argTy, op))) {
347 for (Type resultTy : op->getResultTypes()) {
348 if (failed(validateType(resultTy, op))) {
352 for (NamedAttribute attr : op->getAttrs()) {
353 if (failed(validateAttr(attr.getValue(), op))) {
369 LogicalResult validateCreateArrayOp(CreateArrayOp createOp)
const {
374 ArrayType oldResultTy = createOp.getType();
375 auto newResultTy = llvm::dyn_cast<ArrayType>(convertType(oldResultTy));
376 auto newElemTy = llvm::dyn_cast<ArrayType>(convertType(oldResultTy.
getElementType()));
377 if (!newResultTy || !newElemTy || newResultTy == oldResultTy || oldResultTy.hasStaticShape()) {
381 return createOp.emitError()
382 <<
"cannot rewrite initialized array.new with non-static initializer shape "
387 LogicalResult validateType(Type ty, Operation *diagnosticOp)
const {
391 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
394 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
395 return validateStructType(structTy, diagnosticOp);
397 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
398 for (RecordAttr record : podTy.
getRecords()) {
399 if (failed(validateType(record.getType(), diagnosticOp))) {
405 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
406 for (Type inputTy : funcTy.getInputs()) {
407 if (failed(validateType(inputTy, diagnosticOp))) {
411 for (Type resultTy : funcTy.getResults()) {
412 if (failed(validateType(resultTy, diagnosticOp))) {
421 LogicalResult validateAttr(Attribute attr, Operation *diagnosticOp)
const {
425 if (
auto tyAttr = llvm::dyn_cast<TypeAttr>(attr)) {
426 return validateType(tyAttr.getValue(), diagnosticOp);
428 if (
auto arrAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
429 for (Attribute nested : arrAttr.getValue()) {
430 if (failed(validateAttr(nested, diagnosticOp))) {
439 Attribute convertAttr(Attribute attr, DenseSet<StringAttr> &resolvingParams)
const {
440 return convertTypeOrArrayAttr(attr, ctx_, [
this, &resolvingParams](Type ty) {
441 return convertType(ty, resolvingParams);
442 }, [
this, &resolvingParams](Attribute nested) {
443 return convertTemplateArgAttr(nested, resolvingParams);
455 FailureOr<ArrayAttr> convertTemplateParams(
456 ArrayAttr params, Operation *diagnosticOp,
bool resolveTemplateSymbolArgs =
true,
457 bool allowCurrentTemplateTypeVarSymbols =
false
462 if (params.size() != oldParamOrder_.size()) {
465 SmallVector<Attribute> kept;
466 for (
auto [paramName, attr] : llvm::zip_equal(oldParamOrder_, params.getValue())) {
467 if (removedParams_.contains(paramName)) {
468 if (failed(checkRemovedTemplateParam(
469 paramName, attr, diagnosticOp, resolveTemplateSymbolArgs,
470 allowCurrentTemplateTypeVarSymbols
476 kept.push_back(resolveTemplateSymbolArgs ? convertTemplateArgAttr(attr) : attr);
478 return kept.empty() ? ArrayAttr() : ArrayAttr::get(ctx_, kept);
483 bool hasWildcardForRemovedParam(ArrayAttr params)
const {
484 if (!params || params.size() != oldParamOrder_.size()) {
487 for (
auto [paramName, attr] : llvm::zip_equal(oldParamOrder_, params.getValue())) {
488 if (!removedParams_.contains(paramName)) {
491 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>(attr); intAttr &&
isDynamic(intAttr)) {
500 Attribute convertTemplateArgAttr(Attribute attr)
const {
501 DenseSet<StringAttr> resolvingParams;
502 return convertTemplateArgAttr(attr, resolvingParams);
511 Attribute convertTemplateArgAttr(Attribute attr, DenseSet<StringAttr> &resolvingParams)
const {
512 if (StringAttr symbolName = getFlatSymbolName(attr)) {
513 auto it = replacements_.find(symbolName);
514 if (it != replacements_.end()) {
515 if (!resolvingParams.insert(symbolName).second) {
518 Type replacement = convertType(it->second, resolvingParams);
519 resolvingParams.erase(symbolName);
520 return TypeAttr::get(replacement);
523 return convertAttr(attr, resolvingParams);
527 LogicalResult checkRemovedTemplateParam(
528 StringAttr paramName, Attribute attr, Operation *diagnosticOp,
bool resolveTemplateSymbolArgs,
529 bool allowCurrentTemplateTypeVarSymbols =
false
531 auto replacementIt = replacements_.find(paramName);
532 assert(replacementIt != replacements_.end() &&
"removed parameter must have a replacement");
533 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>(attr); intAttr &&
isDynamic(intAttr)) {
536 Attribute convertedAttr = resolveTemplateSymbolArgs ? convertTemplateArgAttr(attr) : attr;
537 if (StringAttr symbolName = getFlatSymbolName(convertedAttr)) {
538 if (allowCurrentTemplateTypeVarSymbols &&
539 isCurrentTemplateTypeVarParamSymbol(symbolName, diagnosticOp)) {
542 return emitRemovedTemplateParamMismatch(paramName, attr, replacementIt->second, diagnosticOp);
544 if (templateArgUnifiesWithType(convertedAttr, convertType(replacementIt->second))) {
548 return emitRemovedTemplateParamMismatch(paramName, attr, replacementIt->second, diagnosticOp);
552 LogicalResult emitRemovedTemplateParamMismatch(
553 StringAttr paramName, Attribute attr, Type replacementTy, Operation *diagnosticOp
555 InFlightDiagnostic diag = diagnosticOp->emitError()
556 <<
"explicit template argument for inferred parameter @"
557 << paramName.getValue() <<
" must match inferred type "
558 << replacementTy <<
", but found ";
559 if (
auto typeAttr = llvm::dyn_cast<TypeAttr>(attr)) {
560 diag << typeAttr.getValue();
573 bool isOwnedStructType(StructType structTy)
const {
574 SmallVector<StringAttr> structPath = getStringPieces(structTy.
getNameRef());
575 return structPath.size() > templatePath_.size() &&
576 std::equal(templatePath_.begin(), templatePath_.end(), structPath.begin());
584 StructType convertStructType(StructType structTy, DenseSet<StringAttr> &resolvingParams)
const {
590 SmallVector<Attribute> newParams;
591 bool changed =
false;
592 bool removeOwnedParams = isOwnedStructType(structTy) && params.size() == oldParamOrder_.size();
593 for (
auto [index, attr] : llvm::enumerate(params.getValue())) {
594 if (trimResolvedParams_ && removeOwnedParams &&
595 removedParams_.contains(oldParamOrder_[index])) {
599 Attribute newAttr = convertTemplateArgAttr(attr, resolvingParams);
600 newParams.push_back(newAttr);
601 changed |= newAttr != attr;
607 LogicalResult validateStructType(StructType structTy, Operation *diagnosticOp)
const {
612 bool removeOwnedParams = isOwnedStructType(structTy) && params.size() == oldParamOrder_.size();
613 for (
auto indexedAttr : llvm::enumerate(params.getValue())) {
614 unsigned index = indexedAttr.index();
615 Attribute attr = indexedAttr.value();
616 if (trimResolvedParams_ && removeOwnedParams &&
617 removedParams_.contains(oldParamOrder_[index])) {
618 if (failed(checkRemovedTemplateParam(
619 oldParamOrder_[index], attr, diagnosticOp,
true,
626 if (failed(validateAttr(attr, diagnosticOp))) {
635template <
typename ConverterT,
typename SetSignatureFn>
636static void updateCallableSignature(
637 FunctionType oldFuncTy, Region &body, ConverterT &converter, SetSignatureFn setSignature
639 Type converted = converter.convertType(oldFuncTy);
640 auto newFuncTy = llvm::cast<FunctionType>(converted);
641 if (oldFuncTy == newFuncTy) {
645 setSignature(newFuncTy);
650 Block &entryBlock = body.front();
651 assert(entryBlock.getNumArguments() == newFuncTy.getNumInputs());
652 for (
auto [arg, newTy] : llvm::zip_equal(entryBlock.getArguments(), newFuncTy.getInputs())) {
662template <
typename ConverterT>
663static void updateFuncSignature(
FuncDefOp func, ConverterT &converter) {
664 updateCallableSignature(
666 [func](FunctionType newFuncTy)
mutable { func.setType(newFuncTy); }
671template <
typename ConverterT>
672static void updateContractSignature(
verif::ContractOp contract, ConverterT &converter) {
673 updateCallableSignature(
675 [contract](FunctionType newFuncTy)
mutable { contract.setFunctionType(newFuncTy); }
681template <
typename ConverterT>
static bool convertCallCallee(
CallOp callOp, ConverterT &converter) {
682 if constexpr (
requires { converter.convertCallCallee(callOp); }) {
684 SymbolRefAttr newCallee = converter.convertCallCallee(callOp);
685 if (newCallee != oldCallee) {
695template <
typename ConverterT>
696static bool convertContractTarget(
verif::ContractOp contract, ConverterT &converter) {
697 if constexpr (
requires { converter.convertContractTarget(contract); }) {
699 SymbolRefAttr newTarget = converter.convertContractTarget(contract);
700 if (newTarget != oldTarget) {
709template <
typename ConverterT>
static bool converterFailed(ConverterT &converter) {
710 if constexpr (
requires { converter.hadFailure(); }) {
711 return converter.hadFailure();
717template <
typename ConverterT>
718static void startConverterOperation(ConverterT &converter, Operation *op) {
719 if constexpr (
requires { converter.startOperation(op); }) {
720 converter.startOperation(op);
729template <
typename ConverterT>
730static FailureOr<bool> convertOperationTypes(Operation *op, ConverterT &converter) {
731 if (
auto createOp = llvm::dyn_cast<CreateArrayOp>(op)) {
732 ArrayType oldResultTy = createOp.getType();
733 auto newResultTy = llvm::dyn_cast<ArrayType>(converter.convertType(oldResultTy));
734 auto newElemTy = llvm::dyn_cast<ArrayType>(converter.convertType(oldResultTy.
getElementType()));
735 if (converterFailed(converter)) {
738 if (newResultTy && newElemTy && newResultTy != oldResultTy && !createOp.
getElements().empty() &&
739 oldResultTy.hasStaticShape()) {
742 SmallVector<Type> newElementValueTypes;
743 newElementValueTypes.reserve(createOp.
getElements().size());
744 for (
auto [index, element] : llvm::enumerate(createOp.
getElements())) {
745 Type newElementValueTy = converter.convertType(element.getType());
746 if (converterFailed(converter)) {
749 if (newElementValueTy != newElemTy) {
750 createOp.emitError() <<
"cannot rewrite initialized array.new: initializer " << index
751 <<
" converts to " << newElementValueTy <<
", but expected "
755 newElementValueTypes.push_back(newElementValueTy);
758 OpBuilder builder(createOp);
759 Location loc = createOp.getLoc();
762 for (
auto [index, element] : llvm::enumerate(createOp.
getElements())) {
763 Type newElementValueTy = newElementValueTypes[index];
764 if (element.getType() != newElementValueTy) {
765 element.setType(newElementValueTy);
767 std::optional<SmallVector<Value>> indices =
769 assert(indices &&
"static array initializer index should delinearize");
778 if (
auto readOp = llvm::dyn_cast<ReadArrayOp>(op)) {
779 Type newResultTy = converter.convertType(readOp.getResult().getType());
780 if (converterFailed(converter)) {
783 if (
auto newArrayTy = llvm::dyn_cast<ArrayType>(newResultTy)) {
784 OpBuilder builder(readOp);
786 readOp.getLoc(), newArrayTy, readOp.getArrRef(), readOp.getIndices()
788 readOp.getResult().replaceAllUsesWith(extractOp.getResult());
794 if (
auto writeOp = llvm::dyn_cast<WriteArrayOp>(op)) {
795 Type newRvalueTy = converter.convertType(writeOp.getRvalue().getType());
796 if (converterFailed(converter)) {
799 if (llvm::isa<ArrayType>(newRvalueTy)) {
800 OpBuilder builder(writeOp);
802 writeOp.getLoc(), writeOp.getArrRef(), writeOp.getIndices(), writeOp.getRvalue()
809 bool changed =
false;
811 if (
auto func = llvm::dyn_cast<FuncDefOp>(op)) {
812 FunctionType oldFuncTy = func.getFunctionType();
813 updateFuncSignature(func, converter);
814 if (converterFailed(converter)) {
817 changed |= oldFuncTy != func.getFunctionType();
819 if (
auto contract = llvm::dyn_cast<verif::ContractOp>(op)) {
821 updateContractSignature(contract, converter);
822 if (converterFailed(converter)) {
826 changed |= convertContractTarget(contract, converter);
827 if (converterFailed(converter)) {
832 for (Region ®ion : op->getRegions()) {
833 for (Block &block : region.getBlocks()) {
834 for (BlockArgument arg : block.getArguments()) {
835 Type newTy = converter.convertType(arg.getType());
836 if (converterFailed(converter)) {
839 if (newTy != arg.getType()) {
847 for (Value result : op->getResults()) {
848 Type newTy = converter.convertType(result.getType());
849 if (converterFailed(converter)) {
852 if (newTy != result.getType()) {
853 result.setType(newTy);
858 if (
auto callOp = llvm::dyn_cast<CallOp>(op)) {
859 changed |= convertCallCallee(callOp, converter);
860 if (converterFailed(converter)) {
865 SmallVector<NamedAttribute> newAttrs;
866 bool attrsChanged =
false;
867 newAttrs.reserve(op->getAttrs().size());
868 for (NamedAttribute attr : op->getAttrs()) {
869 Attribute newAttr = converter.convertAttr(attr.getValue());
870 if (converterFailed(converter)) {
873 newAttrs.emplace_back(attr.getName(), newAttr);
874 attrsChanged |= newAttr != attr.getValue();
877 op->setAttrs(DictionaryAttr::get(op->getContext(), newAttrs));
885template <
typename ConverterT>
886static FailureOr<bool> convertOperationTypesInAndTrack(Operation *root, ConverterT &converter) {
887 bool changed =
false;
888 WalkResult res = root->walk([&converter, &changed](Operation *op) {
889 startConverterOperation(converter, op);
890 FailureOr<bool> opChanged = convertOperationTypes(op, converter);
891 if (failed(opChanged)) {
892 return WalkResult::interrupt();
894 changed |= *opChanged;
895 return WalkResult::advance();
897 if (res.wasInterrupted()) {
904template <
typename ConverterT>
905static LogicalResult convertOperationTypesIn(Operation *root, ConverterT &converter) {
906 return failure(failed(convertOperationTypesInAndTrack(root, converter)));
915static void removeIdentityCasts(Operation *root) {
917 if (castOp.getInput().getType() != castOp.getResult().getType()) {
920 castOp.getResult().replaceAllUsesWith(castOp.getInput());
926template <
typename ConverterT>
927static LogicalResult convertTemplateExprTypesIn(
TemplateOp templateOp, ConverterT &converter) {
929 if (failed(convertOperationTypesIn(expr.getOperation(), converter))) {
932 removeIdentityCasts(expr.getOperation());
942static std::string buildSpecializedTemplateCloneCacheKey(
943 StringRef templateName, ArrayRef<StringAttr> oldParamOrder,
944 const DenseMap<Attribute, Attribute> ¶mNameToConcrete
947 llvm::raw_string_ostream os(key);
948 os << templateName.size() <<
':' << templateName;
949 for (StringAttr paramName : oldParamOrder) {
951 os << paramName.getValue().size() <<
':' << paramName.getValue() <<
'=';
952 auto concreteIt = paramNameToConcrete.find(FlatSymbolRefAttr::get(paramName));
953 if (concreteIt == paramNameToConcrete.end()) {
958 std::string attrText;
959 llvm::raw_string_ostream attrOs(attrText);
960 concreteIt->second.print(attrOs);
961 os << attrText.size() <<
':' << attrText;
967static bool canCopyTemplateExprToSpecialization(
974 return WalkResult::interrupt();
976 return WalkResult::advance();
985static void copyPreservedTemplateExprs(
986 TemplateOp parentTemplate, Block &newTemplateBody, ArrayRef<Attribute> remainingNames
988 DenseSet<StringAttr> availableNames;
989 for (Attribute name : remainingNames) {
990 FlatSymbolRefAttr nameSym = llvm::cast<FlatSymbolRefAttr>(name);
991 availableNames.insert(nameSym.getAttr());
995 if (canCopyTemplateExprToSpecialization(expr, availableNames)) {
996 newTemplateBody.push_back(expr->clone());
1002static FailureOr<TemplateOp> getOrCreateSpecializedTemplateClone(
1003 TemplateOp parentTemplate, ArrayRef<StringAttr> oldParamOrder,
1004 const DenseMap<Attribute, Attribute> ¶mNameToConcrete, ArrayAttr callParams,
1005 SymbolTableCollection &tables, llvm::StringMap<StringAttr> &templateClones,
1008 FailureOr<InstantiationLayout> layoutResult =
1010 if (failed(layoutResult)) {
1013 layout = std::move(*layoutResult);
1014 std::string cacheKey = buildSpecializedTemplateCloneCacheKey(
1015 parentTemplate.
getSymName(), oldParamOrder, paramNameToConcrete
1019 if (!parentModule) {
1022 SymbolTable &moduleSymbols = tables.getSymbolTable(parentModule);
1024 auto cachedName = templateClones.find(cacheKey);
1025 if (cachedName != templateClones.end()) {
1026 Operation *existing = moduleSymbols.lookup(cachedName->second);
1027 if (
auto existingTemplate = llvm::dyn_cast_or_null<TemplateOp>(existing)) {
1028 return existingTemplate;
1033 TemplateOp newTemplate = parentTemplate.cloneWithoutRegions();
1038 assert(newTemplate->getNumRegions() > 0 &&
"region exists");
1040 Block &newTemplateBody = newTemplate.
getBodyRegion().front();
1041 SymbolTable &parentTemplateSymbols = tables.getSymbolTable(parentTemplate);
1043 FlatSymbolRefAttr nameSym = llvm::cast<FlatSymbolRefAttr>(name);
1044 Operation *paramOp = parentTemplateSymbols.lookup(nameSym.getAttr());
1045 assert(paramOp &&
"symbol must exist");
1046 newTemplateBody.push_back(paramOp->clone());
1048 copyPreservedTemplateExprs(parentTemplate, newTemplateBody, layout.
remainingNames);
1050 moduleSymbols.insert(newTemplate, Block::iterator(parentTemplate));
1051 templateClones.try_emplace(cacheKey, newTemplate.
getSymNameAttr());
1061class ConcreteStructInstantiationConverter {
1063 struct StructInstantiationTypes {
1065 StructType localType;
1067 StructType remoteType;
1075 SymbolTableCollection &tables_;
1077 DenseMap<StructType, StructInstantiationTypes> instantiations_;
1079 SpecializedTemplateCloneCache templateClones_;
1081 DenseSet<SymbolRefAttr> instantiatedCloneNames_;
1083 DenseMap<StructType, StructType> activeLocalStructReplacements_;
1085 DenseMap<StringAttr, Type> activeTypeReplacements_;
1087 bool hasFailure =
false;
1091 ConcreteStructInstantiationConverter(MLIRContext *c, ModuleOp m, SymbolTableCollection &t)
1092 : ctx_(c), module_(m), tables_(t) {}
1095 bool hadFailure()
const {
return hasFailure; }
1098 Type convertType(Type ty) {
1099 if (!ty || hasFailure) {
1102 if (
auto tvarTy = llvm::dyn_cast<TypeVarType>(ty)) {
1103 auto it = activeTypeReplacements_.find(tvarTy.getNameRef().getAttr());
1104 return it == activeTypeReplacements_.end() ? ty : it->second;
1106 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
1107 return convertArrayElementType(arrTy, [
this](Type elemTy) {
return convertType(elemTy); });
1109 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
1110 return convertPodType(podTy, ctx_, *
this);
1112 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
1113 return convertFunctionType(funcTy, *
this);
1115 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
1116 return convertStructType(structTy);
1122 Attribute convertAttr(Attribute attr) {
1126 return convertTypeOrArrayAttr(attr, ctx_, [
this](Type ty) {
1127 return convertType(ty);
1128 }, [
this](Attribute nested) {
return convertTemplateArgAttr(nested); });
1132 SymbolRefAttr convertCallCallee(CallOp callOp) {
1134 if (!callee || callee.getNestedReferences().empty()) {
1138 StructType targetStructTy = getStructFunctionTargetType(callOp);
1139 if (!targetStructTy) {
1142 auto convertedStructTy = llvm::dyn_cast<StructType>(convertType(targetStructTy));
1143 if (!convertedStructTy) {
1147 SymbolRefAttr convertedStructName = convertedStructTy.getNameRef();
1151 SmallVector<FlatSymbolRefAttr> pieces =
getPieces(convertedStructName);
1152 pieces.push_back(FlatSymbolRefAttr::get(callee.getLeafReference()));
1157 SymbolRefAttr convertContractTarget(verif::ContractOp contract) {
1164 if (contractTy.getNumInputs() == 0) {
1167 auto selfTy = llvm::dyn_cast<StructType>(contractTy.getInput(0));
1168 if (!selfTy || selfTy.getNameRef() == target) {
1171 return instantiatedCloneNames_.contains(selfTy.getNameRef()) ? selfTy.getNameRef() : target;
1176 static StructType getStructFunctionTargetType(CallOp callOp) {
1177 StringAttr calleeLeaf = callOp.
getCallee().getLeafReference();
1188 Attribute convertTemplateArgAttr(Attribute attr) {
1189 if (StringAttr symbolName = getFlatSymbolName(attr)) {
1190 auto it = activeTypeReplacements_.find(symbolName);
1191 if (it != activeTypeReplacements_.end()) {
1192 return TypeAttr::get(it->second);
1195 return convertAttr(attr);
1199 StructType convertStructType(StructType structTy) {
1200 ArrayAttr params = structTy.
getParams();
1205 SmallVector<Attribute> newParams;
1206 bool changed =
false;
1207 for (Attribute attr : params.getValue()) {
1208 Attribute newAttr = convertTemplateArgAttr(attr);
1209 newParams.push_back(newAttr);
1210 changed |= newAttr != attr;
1212 StructType convertedTy =
1216 if (
auto it = activeLocalStructReplacements_.find(convertedTy);
1217 it != activeLocalStructReplacements_.end()) {
1220 if (instantiatedCloneNames_.contains(convertedTy.
getNameRef())) {
1224 if (llvm::any_of(newParams, [](Attribute attr) {
1230 FailureOr<StructType> cloneTy = getOrCreateStructClone(convertedTy, newParams);
1231 if (failed(cloneTy)) {
1239 FailureOr<StructType>
1240 getOrCreateStructClone(StructType concreteStructTy, ArrayRef<Attribute> concreteParams) {
1241 if (
auto it = instantiations_.find(concreteStructTy); it != instantiations_.end()) {
1242 return it->second.remoteType;
1245 FailureOr<SymbolLookupResult<StructDefOp>> lookup =
1247 if (failed(lookup)) {
1251 StructDefOp origStruct = lookup->get();
1253 if (!parentTemplate) {
1256 StructType typeAtDef = origStruct.
getType();
1257 ArrayAttr paramNames = typeAtDef.
getParams();
1258 if (!paramNames || paramNames.size() != concreteParams.size()) {
1262 DenseMap<StringAttr, Type> typeReplacements;
1263 DenseMap<Attribute, Attribute> paramNameToConcrete;
1264 SmallVector<StringAttr> oldParamOrder;
1265 oldParamOrder.reserve(paramNames.size());
1266 SmallVector<Attribute> convertedSourceParams;
1267 convertedSourceParams.reserve(concreteParams.size());
1268 for (
auto [paramName, concreteAttr] : llvm::zip_equal(paramNames.getValue(), concreteParams)) {
1269 auto paramSym = llvm::dyn_cast<FlatSymbolRefAttr>(paramName);
1273 oldParamOrder.push_back(paramSym.getAttr());
1274 auto concreteType = llvm::dyn_cast<TypeAttr>(concreteAttr);
1276 paramNameToConcrete.try_emplace(FlatSymbolRefAttr::get(paramSym.getAttr()), concreteAttr);
1277 typeReplacements.try_emplace(paramSym.getAttr(), concreteType.getValue());
1278 convertedSourceParams.push_back(concreteType);
1280 convertedSourceParams.push_back(paramName);
1283 if (paramNameToConcrete.empty()) {
1284 return concreteStructTy;
1287 InstantiationLayout layout;
1288 ArrayAttr concreteParamArray = ArrayAttr::get(ctx_, concreteParams);
1289 FailureOr<TemplateOp> newTemplate = getOrCreateSpecializedTemplateClone(
1290 parentTemplate, oldParamOrder, paramNameToConcrete, concreteParamArray, tables_,
1291 templateClones_[parentTemplate.getOperation()], layout
1293 if (failed(newTemplate)) {
1297 SymbolTable &templateSymbols = tables_.getSymbolTable(*newTemplate);
1298 StructDefOp clone = origStruct.clone();
1299 templateSymbols.insert(clone);
1300 StructType localTy =
1302 StructType remoteTy =
1304 instantiations_.try_emplace(concreteStructTy, StructInstantiationTypes {localTy, remoteTy});
1307 DenseMap<StringAttr, Type> previousReplacements = std::move(activeTypeReplacements_);
1308 DenseMap<StructType, StructType> previousLocalStructReplacements =
1309 std::move(activeLocalStructReplacements_);
1310 activeTypeReplacements_ = std::move(typeReplacements);
1311 activeLocalStructReplacements_.clear();
1312 activeLocalStructReplacements_.try_emplace(concreteStructTy, localTy);
1313 activeLocalStructReplacements_.try_emplace(
1317 activeLocalStructReplacements_.try_emplace(
1320 activeLocalStructReplacements_.try_emplace(
1324 if (failed(convertTemplateExprTypesIn(*newTemplate, *
this))) {
1325 activeLocalStructReplacements_ = std::move(previousLocalStructReplacements);
1326 activeTypeReplacements_ = std::move(previousReplacements);
1327 instantiations_.erase(concreteStructTy);
1328 instantiatedCloneNames_.erase(cloneNameRef);
1332 if (failed(convertOperationTypesIn(clone.getOperation(), *
this))) {
1333 activeLocalStructReplacements_ = std::move(previousLocalStructReplacements);
1334 activeTypeReplacements_ = std::move(previousReplacements);
1335 instantiations_.erase(concreteStructTy);
1336 instantiatedCloneNames_.erase(cloneNameRef);
1340 removeIdentityCasts(clone.getOperation());
1341 activeLocalStructReplacements_ = std::move(previousLocalStructReplacements);
1342 activeTypeReplacements_ = std::move(previousReplacements);
1348struct TemplateInferenceInfo {
1350 TemplateOp templateOp;
1352 SmallVector<StringAttr> templatePath;
1354 SmallVector<StringAttr> oldParamOrder;
1356 DenseMap<StringAttr, TemplateParamOp> typeVarParams;
1358 DenseMap<StringAttr, InferredType> replacements;
1360 DenseMap<StringAttr, InferredType> templateScopeReplacements;
1362 DenseMap<Operation *, DenseMap<StringAttr, InferredType>> functionReplacements;
1366static DenseMap<Attribute, Attribute>
1367buildParamNameToCallArg(ArrayAttr callParams, ArrayRef<StringAttr> oldParamOrder) {
1368 DenseMap<Attribute, Attribute> paramNameToCallArg;
1369 if (!callParams || callParams.size() != oldParamOrder.size()) {
1370 return paramNameToCallArg;
1372 for (
auto [paramName, attr] : llvm::zip_equal(oldParamOrder, callParams.getValue())) {
1373 paramNameToCallArg.try_emplace(FlatSymbolRefAttr::get(paramName), attr);
1375 return paramNameToCallArg;
1385substituteExplicitCallTypeArgs(Type ty, ArrayAttr callParams, ArrayRef<StringAttr> oldParamOrder) {
1386 if (!callParams || callParams.size() != oldParamOrder.size()) {
1390 DenseMap<StringAttr, Type> callTypeArgs;
1391 for (
auto [paramName, attr] : llvm::zip_equal(oldParamOrder, callParams.getValue())) {
1392 if (
auto tyAttr = llvm::dyn_cast<TypeAttr>(attr)) {
1393 callTypeArgs.try_emplace(paramName, tyAttr.getValue());
1396 TypeVarReplacementConverter converter(
1397 ty.getContext(), ArrayRef<StringAttr> {}, oldParamOrder, callTypeArgs,
1400 return converter.convertType(ty);
1404class ExplicitCallTemplateParamSubstituter {
1406 const DenseMap<Attribute, Attribute> ¶mNameToCallArg_;
1408 DenseSet<Attribute> resolvingParams_;
1411 explicit ExplicitCallTemplateParamSubstituter(
1412 const DenseMap<Attribute, Attribute> ¶mNameToCallArg
1414 : paramNameToCallArg_(paramNameToCallArg) {}
1416 Type substituteType(Type ty);
1417 Attribute substituteAttr(Attribute attr);
1421Attribute ExplicitCallTemplateParamSubstituter::substituteAttr(Attribute attr) {
1425 auto it = paramNameToCallArg_.find(attr);
1426 if (it != paramNameToCallArg_.end()) {
1429 if (
auto tyAttr = llvm::dyn_cast<TypeAttr>(attr)) {
1430 Type newTy = substituteType(tyAttr.getValue());
1431 return newTy == tyAttr.getValue() ? attr : TypeAttr::get(newTy);
1433 if (
auto arrAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
1434 SmallVector<Attribute> newAttrs;
1435 bool changed =
false;
1436 for (Attribute nested : arrAttr.getValue()) {
1437 Attribute newNested = substituteAttr(nested);
1438 newAttrs.push_back(newNested);
1439 changed |= newNested != nested;
1441 return changed ? ArrayAttr::get(attr.getContext(), newAttrs) : attr;
1453Type ExplicitCallTemplateParamSubstituter::substituteType(Type ty) {
1457 if (
auto tvarTy = llvm::dyn_cast<TypeVarType>(ty)) {
1458 Attribute paramRef = tvarTy.getNameRef();
1459 auto it = paramNameToCallArg_.find(paramRef);
1460 if (it == paramNameToCallArg_.end()) {
1463 auto tyAttr = llvm::dyn_cast<TypeAttr>(it->second);
1464 if (!tyAttr || tyAttr.getValue() == ty) {
1467 if (!resolvingParams_.insert(paramRef).second) {
1470 Type replacement = substituteType(tyAttr.getValue());
1471 resolvingParams_.erase(paramRef);
1474 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
1475 SmallVector<Attribute> newDims;
1476 bool changed =
false;
1478 Attribute newDim = substituteAttr(dim);
1479 newDims.push_back(newDim);
1480 changed |= newDim != dim;
1490 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
1491 ArrayAttr params = structTy.
getParams();
1495 SmallVector<Attribute> newParams;
1496 bool changed =
false;
1497 for (Attribute param : params.getValue()) {
1498 Attribute newParam = substituteAttr(param);
1499 newParams.push_back(newParam);
1500 changed |= newParam != param;
1505 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
1506 SmallVector<RecordAttr> newRecords;
1507 bool changed =
false;
1508 for (RecordAttr record : podTy.
getRecords()) {
1509 Type newRecordTy = substituteType(record.getType());
1510 newRecords.push_back(RecordAttr::get(ty.getContext(), record.getName(), newRecordTy));
1511 changed |= newRecordTy != record.getType();
1513 return changed ?
PodType::get(ty.getContext(), newRecords) : podTy;
1515 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
1516 SmallVector<Type> newInputs;
1517 SmallVector<Type> newResults;
1518 bool changed =
false;
1519 newInputs.reserve(funcTy.getNumInputs());
1520 newResults.reserve(funcTy.getNumResults());
1521 for (Type inputTy : funcTy.getInputs()) {
1522 Type newInputTy = substituteType(inputTy);
1523 newInputs.push_back(newInputTy);
1524 changed |= newInputTy != inputTy;
1526 for (Type resultTy : funcTy.getResults()) {
1527 Type newResultTy = substituteType(resultTy);
1528 newResults.push_back(newResultTy);
1529 changed |= newResultTy != resultTy;
1531 return changed ? FunctionType::get(ty.getContext(), newInputs, newResults) : funcTy;
1537static Type substituteExplicitCallTemplateParams(
1538 Type ty, ArrayAttr callParams, ArrayRef<StringAttr> oldParamOrder
1540 auto paramNameToCallArg = buildParamNameToCallArg(callParams, oldParamOrder);
1541 ExplicitCallTemplateParamSubstituter substituter(paramNameToCallArg);
1542 return substituter.substituteType(ty);
1546static bool symbolMatchesParam(SymbolRefAttr symRef, StringAttr paramName) {
1547 return symRef && symRef.getNestedReferences().empty() && symRef.getRootReference() == paramName;
1551class ParamMentionChecker {
1552 StringAttr paramName_;
1555 explicit ParamMentionChecker(StringAttr paramName) : paramName_(paramName) {}
1558 bool typeMentions(Type ty)
const {
1562 if (
auto tvarTy = llvm::dyn_cast<TypeVarType>(ty)) {
1563 return tvarTy.getNameRef().getAttr() == paramName_;
1565 if (
auto arrayTy = llvm::dyn_cast<ArrayType>(ty)) {
1566 return typeMentions(arrayTy.getElementType()) ||
1567 llvm::any_of(arrayTy.getDimensionSizes(), [
this](Attribute dim) {
1568 return attrMentions(dim, true);
1571 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
1572 ArrayAttr params = structTy.
getParams();
1573 return params && attrMentions(params,
true);
1575 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
1576 return llvm::any_of(podTy.
getRecords(), [
this](RecordAttr record) {
1577 return typeMentions(record.getType());
1580 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
1581 return llvm::any_of(funcTy.getInputs(), [
this](Type input) {
1582 return typeMentions(input);
1583 }) || llvm::any_of(funcTy.getResults(), [
this](Type result) { return typeMentions(result); });
1593 bool attrMentions(Attribute attr,
bool allowSymbolRefs)
const {
1597 if (
auto typeAttr = llvm::dyn_cast<TypeAttr>(attr)) {
1598 return typeMentions(typeAttr.getValue());
1600 if (
auto arrayAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
1601 return llvm::any_of(arrayAttr, [
this](Attribute nested) {
1602 return attrMentions(nested,
true);
1605 return allowSymbolRefs && symbolMatchesParam(llvm::dyn_cast<SymbolRefAttr>(attr), paramName_);
1610static bool operationMentionsParam(Operation *op, StringAttr paramName) {
1611 ParamMentionChecker mentions(paramName);
1612 if (llvm::any_of(op->getResultTypes(), [&mentions](Type ty) {
1613 return mentions.typeMentions(ty);
1617 for (Region ®ion : op->getRegions()) {
1618 for (Block &block : region.getBlocks()) {
1619 if (llvm::any_of(block.getArgumentTypes(), [&mentions](Type ty) {
1620 return mentions.typeMentions(ty);
1626 return llvm::any_of(op->getAttrs(), [&mentions](NamedAttribute attr) {
1627 return mentions.attrMentions(attr.getValue(), false);
1632static SmallVector<StringAttr> getMentionedTypeVarParams(
1633 Attribute attr,
const DenseMap<StringAttr, TemplateParamOp> &typeVarParams
1635 SmallVector<StringAttr> mentionedParams;
1636 for (
const auto &entry : typeVarParams) {
1637 if (ParamMentionChecker(entry.first).attrMentions(attr,
true)) {
1638 mentionedParams.push_back(entry.first);
1641 return mentionedParams;
1645static inline bool attrMentionsAnyTypeVarParam(
1646 Attribute attr,
const DenseMap<StringAttr, TemplateParamOp> &typeVarParams
1648 return !getMentionedTypeVarParams(attr, typeVarParams).empty();
1652static bool funcMentionsParam(FuncDefOp func, StringAttr paramName) {
1653 if (operationMentionsParam(func.getOperation(), paramName)) {
1656 return walkContains<Operation *>(func, [paramName](Operation *op) {
1657 return operationMentionsParam(op, paramName);
1662static bool contractMentionsParam(verif::ContractOp contract, StringAttr paramName) {
1663 if (operationMentionsParam(contract.getOperation(), paramName)) {
1666 return walkContains<Operation *>(contract, [paramName](Operation *op) {
1667 return operationMentionsParam(op, paramName);
1672static inline bool targetMentionsParam(FuncDefOp func, StringAttr paramName) {
1673 return funcMentionsParam(func, paramName);
1677static inline bool targetMentionsParam(verif::ContractOp contract, StringAttr paramName) {
1678 return contractMentionsParam(contract, paramName);
1682static inline bool exprMentionsParam(TemplateExprOp expr, StringAttr paramName) {
1683 return walkContains<Operation *>(expr, [paramName](Operation *op) {
1684 return operationMentionsParam(op, paramName);
1690static bool structUseCoveredByFunctionProof(
1691 StructDefOp structOp, StringAttr paramName, Type replacementType,
1692 const DenseMap<Operation *, DenseMap<StringAttr, InferredType>> &functionReplacements
1694 bool sawMention =
false;
1695 bool missingProof =
false;
1696 structOp.walk([&](FuncDefOp func) {
1697 if (func->getParentOfType<StructDefOp>() != structOp || !funcMentionsParam(func, paramName)) {
1701 auto funcIt = functionReplacements.find(func.getOperation());
1702 if (funcIt == functionReplacements.end()) {
1703 missingProof =
true;
1706 auto replacementIt = funcIt->second.find(paramName);
1707 if (replacementIt == funcIt->second.end() || replacementIt->second.type != replacementType) {
1708 missingProof =
true;
1711 return sawMention && !missingProof;
1721static bool hasUncoveredNonFunctionMention(
1722 TemplateOp templateOp, StringAttr paramName, Type replacementType,
1723 const DenseMap<Operation *, DenseMap<StringAttr, InferredType>> &functionReplacements
1726 templateOp.walk([paramName, replacementType, &functionReplacements](Operation *op) {
1727 if (llvm::isa<FuncDefOp, TemplateExprOp, TemplateParamOp, verif::ContractOp>(op) ||
1729 return WalkResult::advance();
1731 if (!operationMentionsParam(op, paramName)) {
1732 return WalkResult::advance();
1734 if (StructDefOp structOp = op->getParentOfType<StructDefOp>()) {
1735 if (structUseCoveredByFunctionProof(
1736 structOp, paramName, replacementType, functionReplacements
1738 return WalkResult::advance();
1741 return WalkResult::interrupt();
1743 return result.wasInterrupted();
1752class TypeVarInferenceCollector {
1754 TemplateInferenceInfo &inferenceInfo;
1756 DenseMap<StringAttr, InferredType> &replacements;
1758 DenseMap<Value, InferredType> byValue;
1760 DenseMap<StringAttr, DenseSet<StringAttr>> paramRelations;
1762 bool changedInIteration =
false;
1766 TypeVarInferenceCollector(
1767 TemplateInferenceInfo &info, DenseMap<StringAttr, InferredType> &scopeReplacements
1769 : inferenceInfo(info), replacements(scopeReplacements) {}
1772 LogicalResult collect(Operation *root) {
1774 changedInIteration =
false;
1775 auto result = root->walk([
this](UnifiableCastOp castOp) -> WalkResult {
1776 return collectTypePairInferences(
1781 if (result.wasInterrupted()) {
1784 }
while (changedInIteration);
1789 LogicalResult collectTypeInferences(Type lhs, Type rhs, Location loc) {
1791 changedInIteration =
false;
1792 if (failed(collectTypePairInferences(lhs, rhs, Value(), Value(), loc))) {
1795 }
while (changedInIteration);
1807 LogicalResult collectStructTemplateParamInferences(
1808 Operation *root, ModuleOp module, DenseMap<Operation *, TemplateInferenceInfo *> &infos,
1809 SymbolTableCollection &tables
1811 auto result = root->walk([&](Operation *op) -> WalkResult {
1812 return collectOperationStructTemplateParamInferences(op, module, infos, tables);
1814 return failure(result.wasInterrupted());
1818 LogicalResult collectOperationStructTemplateParamInferences(
1819 Operation *op, ModuleOp module, DenseMap<Operation *, TemplateInferenceInfo *> &infos,
1820 SymbolTableCollection &tables
1822 Location loc = op->getLoc();
1824 if (
auto func = llvm::dyn_cast<FuncDefOp>(op)) {
1825 if (failed(collectStructTemplateParamInferences(
1832 for (Region ®ion : op->getRegions()) {
1833 for (Block &block : region.getBlocks()) {
1834 for (Type argTy : block.getArgumentTypes()) {
1835 if (failed(collectStructTemplateParamInferences(argTy, loc, module, infos, tables))) {
1842 for (Type resultTy : op->getResultTypes()) {
1843 if (failed(collectStructTemplateParamInferences(resultTy, loc, module, infos, tables))) {
1848 if (
auto callOp = llvm::dyn_cast<CallOp>(op)) {
1849 if (failed(collectCallableTemplateParamInferences(callOp, infos, tables))) {
1853 if (
auto includeOp = llvm::dyn_cast<verif::IncludeOp>(op)) {
1854 if (failed(collectIncludeTemplateParamInferences(includeOp, infos, tables))) {
1859 for (NamedAttribute attr : op->getAttrs()) {
1861 collectStructTemplateParamInferences(attr.getValue(), loc, module, infos, tables)
1875 LogicalResult collectStructTemplateParamInferences(
1876 Attribute attr, Location loc, ModuleOp module,
1877 DenseMap<Operation *, TemplateInferenceInfo *> &infos, SymbolTableCollection &tables
1882 if (
auto tyAttr = llvm::dyn_cast<TypeAttr>(attr)) {
1883 return collectStructTemplateParamInferences(tyAttr.getValue(), loc, module, infos, tables);
1885 if (
auto arrAttr = llvm::dyn_cast<ArrayAttr>(attr)) {
1886 for (Attribute nested : arrAttr.getValue()) {
1887 if (failed(collectStructTemplateParamInferences(nested, loc, module, infos, tables))) {
1903 LogicalResult collectStructTemplateParamInferences(
1904 Type ty, Location loc, ModuleOp module, DenseMap<Operation *, TemplateInferenceInfo *> &infos,
1905 SymbolTableCollection &tables
1910 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
1911 return collectStructTemplateParamInferences(
1915 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
1916 for (RecordAttr record : podTy.
getRecords()) {
1918 collectStructTemplateParamInferences(record.getType(), loc, module, infos, tables)
1925 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
1926 for (Type inputTy : funcTy.getInputs()) {
1927 if (failed(collectStructTemplateParamInferences(inputTy, loc, module, infos, tables))) {
1931 for (Type resultTy : funcTy.getResults()) {
1932 if (failed(collectStructTemplateParamInferences(resultTy, loc, module, infos, tables))) {
1938 auto structTy = llvm::dyn_cast<StructType>(ty);
1943 ArrayAttr params = structTy.
getParams();
1947 for (Attribute attr : params.getValue()) {
1948 if (failed(collectStructTemplateParamInferences(attr, loc, module, infos, tables))) {
1953 FailureOr<SymbolLookupResult<StructDefOp>> lookup =
1955 if (failed(lookup)) {
1959 if (!parentTemplate) {
1962 TemplateInferenceInfo *targetInfo = infos.lookup(parentTemplate.getOperation());
1963 if (!targetInfo || targetInfo->replacements.empty() ||
1964 params.size() != targetInfo->oldParamOrder.size()) {
1968 for (
auto [paramName, attr] : llvm::zip_equal(targetInfo->oldParamOrder, params.getValue())) {
1969 auto replacementIt = targetInfo->replacements.find(paramName);
1970 if (replacementIt == targetInfo->replacements.end()) {
1973 Type expectedTy = substituteExplicitCallTemplateParams(
1974 replacementIt->second.type, params, targetInfo->oldParamOrder
1976 Attribute expectedAttr = TypeAttr::get(expectedTy);
1977 if (failed(collectTemplateArgInferences(attr, expectedAttr, loc))) {
1990 SmallVector<Attribute>
1991 getInferredOmittedTemplateArgs(
const UnificationMap &unifyResult, StringAttr targetParamName) {
1992 SmallVector<Attribute> inferredAttrs;
1993 auto targetRef = FlatSymbolRefAttr::get(targetParamName);
1994 auto inferredIt = unifyResult.find({targetRef, Side::RHS});
1995 if (inferredIt != unifyResult.end()) {
1996 inferredAttrs.push_back(inferredIt->second);
1998 for (
const auto &entry : unifyResult) {
1999 if (entry.first.second == Side::LHS && entry.second == targetRef) {
2000 inferredAttrs.push_back(entry.first.first);
2003 return inferredAttrs;
2007 template <
typename TargetOp>
2008 TemplateInferenceInfo *
2009 getTargetTemplateInfo(TargetOp targetOp, DenseMap<Operation *, TemplateInferenceInfo *> &infos) {
2011 if (!parentTemplate) {
2014 TemplateInferenceInfo *targetInfo = infos.lookup(parentTemplate.getOperation());
2015 if (!targetInfo || targetInfo->replacements.empty()) {
2028 template <
typename CallableOp>
2029 LogicalResult collectCallableUseTemplateParamInferences(
2030 CallableOp callableOp, FunctionType targetSignature, TemplateInferenceInfo &targetInfo
2032 ArrayAttr params = callableOp.getTemplateParamsAttr();
2034 if (params.size() != targetInfo.oldParamOrder.size()) {
2037 struct DeferredExplicitArgInference {
2039 Attribute expectedAttr;
2040 SmallVector<StringAttr> mentionedParams;
2042 SmallVector<DeferredExplicitArgInference> deferredExplicitArgInferences;
2043 bool deferredToSignature =
false;
2044 for (
auto [paramName, attr] : llvm::zip_equal(targetInfo.oldParamOrder, params)) {
2045 auto replacementIt = targetInfo.replacements.find(paramName);
2046 if (replacementIt == targetInfo.replacements.end()) {
2049 Type expectedTy = substituteExplicitCallTemplateParams(
2050 replacementIt->second.type, params, targetInfo.oldParamOrder
2052 Attribute expectedAttr = TypeAttr::get(expectedTy);
2053 if (attrMentionsAnyTypeVarParam(attr, inferenceInfo.typeVarParams)) {
2054 deferredToSignature =
true;
2055 SmallVector<StringAttr> mentionedParams =
2056 getMentionedTypeVarParams(attr, inferenceInfo.typeVarParams);
2057 if (!ParamMentionChecker(paramName).typeMentions(targetSignature)) {
2058 if (failed(collectTemplateArgInferences(attr, expectedAttr, callableOp.getLoc()))) {
2062 deferredExplicitArgInferences.push_back(
2063 {attr, expectedAttr, std::move(mentionedParams)}
2068 if (failed(collectTemplateArgInferences(attr, expectedAttr, callableOp.getLoc()))) {
2072 if (deferredToSignature) {
2073 DenseMap<StringAttr, Type> targetReplacements;
2074 for (
const auto &entry : targetInfo.replacements) {
2075 targetReplacements.try_emplace(entry.first, entry.second.type);
2077 TypeVarReplacementConverter converter(
2078 callableOp.getContext(), targetInfo.templatePath, targetInfo.oldParamOrder,
2079 targetReplacements,
false
2081 Type rewrittenTy = substituteExplicitCallTemplateParams(
2082 converter.convertType(targetSignature), params, targetInfo.oldParamOrder
2084 if (failed(collectTypeInferences(
2085 callableOp.getTypeSignature(), llvm::cast<FunctionType>(rewrittenTy),
2091 for (
const DeferredExplicitArgInference &deferred : deferredExplicitArgInferences) {
2092 bool signatureCanInferAllParams =
2093 llvm::all_of(deferred.mentionedParams, [&](StringAttr mentionedParam) {
2094 return ParamMentionChecker(mentionedParam).typeMentions(callableOp.getTypeSignature());
2096 bool signatureHasInferredAllParams =
2097 llvm::all_of(deferred.mentionedParams, [&](StringAttr mentionedParam) {
2098 return replacements.contains(mentionedParam);
2100 if (signatureCanInferAllParams && signatureHasInferredAllParams) {
2103 if (failed(collectTemplateArgInferences(
2104 deferred.attr, deferred.expectedAttr, callableOp.getLoc()
2113 FailureOr<UnificationMap> unifyResult = callableOp.unifyTypeSignature(targetSignature);
2114 if (failed(unifyResult)) {
2118 for (StringAttr paramName : targetInfo.oldParamOrder) {
2119 auto replacementIt = targetInfo.replacements.find(paramName);
2120 if (replacementIt == targetInfo.replacements.end()) {
2123 SmallVector<Attribute> inferredAttrs =
2124 getInferredOmittedTemplateArgs(*unifyResult, paramName);
2125 if (inferredAttrs.empty()) {
2129 Attribute expectedAttr = TypeAttr::get(replacementIt->second.type);
2130 for (Attribute inferredAttr : inferredAttrs) {
2131 if (!inferredAttr || !
typeParamsUnify({inferredAttr}, {expectedAttr})) {
2132 InFlightDiagnostic diag = callableOp.emitError()
2133 <<
"implicit template argument for inferred parameter @"
2134 << paramName.getValue() <<
" must match inferred type "
2135 << replacementIt->second.type <<
", but found ";
2136 if (
auto typeAttr = llvm::dyn_cast_if_present<TypeAttr>(inferredAttr)) {
2137 diag << typeAttr.getValue();
2139 diag << inferredAttr;
2143 if (failed(collectTemplateArgInferences(inferredAttr, expectedAttr, callableOp.getLoc()))) {
2160 LogicalResult collectCallableTemplateParamInferences(
2161 CallOp callOp, DenseMap<Operation *, TemplateInferenceInfo *> &infos,
2162 SymbolTableCollection &tables
2164 FailureOr<SymbolLookupResult<FuncDefOp>> target = callOp.
getCalleeTarget(tables);
2165 if (failed(target)) {
2168 FuncDefOp targetFunc = target->get();
2169 TemplateInferenceInfo *targetInfo = getTargetTemplateInfo(targetFunc, infos);
2173 return collectCallableUseTemplateParamInferences(
2184 LogicalResult collectIncludeTemplateParamInferences(
2185 verif::IncludeOp includeOp, DenseMap<Operation *, TemplateInferenceInfo *> &infos,
2186 SymbolTableCollection &tables
2188 FailureOr<SymbolLookupResult<verif::ContractOp>> target = includeOp.
getCalleeTarget(tables);
2189 if (failed(target)) {
2192 verif::ContractOp targetContract = target->get();
2193 TemplateInferenceInfo *targetInfo = getTargetTemplateInfo(targetContract, infos);
2197 return collectCallableUseTemplateParamInferences(
2215 LogicalResult recordInference(StringAttr paramName, Type inferredTy, Value value, Location loc) {
2216 if (!inferenceInfo.typeVarParams.contains(paramName)) {
2219 if (
auto inferredTvar = llvm::dyn_cast<TypeVarType>(inferredTy)) {
2220 return recordParamRelation(paramName, inferredTvar.getNameRef().getAttr(), loc);
2226 auto reportConflict = [&](StringRef kind, Location originalLoc, Type originalTy) {
2227 InFlightDiagnostic diag = emitError(loc) <<
"conflicting inferred type for " << kind <<
" @"
2228 << paramName.getValue() <<
": " << originalTy
2229 <<
" vs " << inferredTy;
2230 diag.attachNote(originalLoc) <<
"previous inference here";
2234 auto byParamIt = replacements.find(paramName);
2235 bool learnedParamInference =
false;
2236 if (byParamIt == replacements.end()) {
2237 replacements.try_emplace(paramName, InferredType {inferredTy, loc});
2238 changedInIteration =
true;
2239 learnedParamInference =
true;
2240 }
else if (byParamIt->second.type != inferredTy) {
2241 return reportConflict(
"template parameter", byParamIt->second.loc, byParamIt->second.type);
2245 auto byValueIt = byValue.find(value);
2246 if (byValueIt == byValue.end()) {
2247 byValue.try_emplace(value, InferredType {inferredTy, loc});
2248 changedInIteration =
true;
2249 }
else if (byValueIt->second.type != inferredTy) {
2250 return reportConflict(
"SSA value using", byValueIt->second.loc, byValueIt->second.type);
2254 if (learnedParamInference) {
2255 auto relatedIt = paramRelations.find(paramName);
2256 if (relatedIt != paramRelations.end()) {
2257 for (StringAttr relatedParam : relatedIt->second) {
2258 if (failed(recordInference(relatedParam, inferredTy, Value(), loc))) {
2268 LogicalResult recordParamRelation(StringAttr lhsParam, StringAttr rhsParam, Location loc) {
2269 if (lhsParam == rhsParam || !inferenceInfo.typeVarParams.contains(rhsParam)) {
2273 bool inserted = paramRelations[lhsParam].insert(rhsParam).second;
2274 inserted |= paramRelations[rhsParam].insert(lhsParam).second;
2279 changedInIteration =
true;
2281 auto lhsIt = replacements.find(lhsParam);
2282 if (lhsIt != replacements.end() &&
2283 failed(recordInference(rhsParam, lhsIt->second.type, Value(), loc))) {
2286 auto rhsIt = replacements.find(rhsParam);
2287 if (rhsIt != replacements.end() &&
2288 failed(recordInference(lhsParam, rhsIt->second.type, Value(), loc))) {
2302 collectTypePairInferences(Type lhs, Type rhs, Value lhsValue, Value rhsValue, Location loc) {
2303 if (
auto lhsTvar = llvm::dyn_cast<TypeVarType>(lhs)) {
2304 if (failed(recordInference(lhsTvar.getNameRef().getAttr(), rhs, lhsValue, loc))) {
2308 auto rhsValueIt = byValue.find(rhsValue);
2309 if (rhsValueIt != byValue.end() &&
2310 failed(recordInference(
2311 lhsTvar.getNameRef().getAttr(), rhsValueIt->second.type, lhsValue, loc
2317 if (
auto rhsTvar = llvm::dyn_cast<TypeVarType>(rhs)) {
2318 if (failed(recordInference(rhsTvar.getNameRef().getAttr(), lhs, rhsValue, loc))) {
2322 auto lhsValueIt = byValue.find(lhsValue);
2323 if (lhsValueIt != byValue.end() &&
2324 failed(recordInference(
2325 rhsTvar.getNameRef().getAttr(), lhsValueIt->second.type, rhsValue, loc
2332 if (
auto lhsArr = llvm::dyn_cast<ArrayType>(lhs)) {
2333 if (
auto rhsArr = llvm::dyn_cast<ArrayType>(rhs)) {
2334 return collectTypePairInferences(
2335 lhsArr.getElementType(), rhsArr.getElementType(), Value(), Value(), loc
2340 if (
auto lhsStruct = llvm::dyn_cast<StructType>(lhs)) {
2341 if (
auto rhsStruct = llvm::dyn_cast<StructType>(rhs)) {
2342 ArrayRef<Attribute> lhsParams =
2343 lhsStruct.getParams() ? lhsStruct.getParams().getValue() : ArrayRef<Attribute> {};
2344 ArrayRef<Attribute> rhsParams =
2345 rhsStruct.getParams() ? rhsStruct.getParams().getValue() : ArrayRef<Attribute> {};
2346 if (lhsParams.size() != rhsParams.size()) {
2349 for (
auto [lhsAttr, rhsAttr] : llvm::zip_equal(lhsParams, rhsParams)) {
2350 if (failed(collectTemplateArgInferences(lhsAttr, rhsAttr, loc))) {
2357 if (
auto lhsPod = llvm::dyn_cast<PodType>(lhs)) {
2358 if (
auto rhsPod = llvm::dyn_cast<PodType>(rhs)) {
2359 ArrayRef<RecordAttr> lhsRecords = lhsPod.getRecords();
2360 ArrayRef<RecordAttr> rhsRecords = rhsPod.getRecords();
2361 if (lhsRecords.size() != rhsRecords.size()) {
2364 for (
auto [lhsRecord, rhsRecord] : llvm::zip_equal(lhsRecords, rhsRecords)) {
2365 if (lhsRecord.getName() != rhsRecord.getName()) {
2368 if (failed(collectTypePairInferences(
2369 lhsRecord.getType(), rhsRecord.getType(), Value(), Value(), loc
2377 if (
auto lhsFunc = llvm::dyn_cast<FunctionType>(lhs)) {
2378 if (
auto rhsFunc = llvm::dyn_cast<FunctionType>(rhs)) {
2379 if (lhsFunc.getNumInputs() != rhsFunc.getNumInputs() ||
2380 lhsFunc.getNumResults() != rhsFunc.getNumResults()) {
2383 for (
auto [lhsInput, rhsInput] :
2384 llvm::zip_equal(lhsFunc.getInputs(), rhsFunc.getInputs())) {
2385 if (failed(collectTypePairInferences(lhsInput, rhsInput, Value(), Value(), loc))) {
2389 for (
auto [lhsResult, rhsResult] :
2390 llvm::zip_equal(lhsFunc.getResults(), rhsFunc.getResults())) {
2391 if (failed(collectTypePairInferences(lhsResult, rhsResult, Value(), Value(), loc))) {
2408 LogicalResult collectTemplateArgInferences(Attribute lhsAttr, Attribute rhsAttr, Location loc) {
2409 auto lhsTyAttr = llvm::dyn_cast<TypeAttr>(lhsAttr);
2410 auto rhsTyAttr = llvm::dyn_cast<TypeAttr>(rhsAttr);
2411 if (lhsTyAttr && rhsTyAttr) {
2412 return collectTypePairInferences(
2413 lhsTyAttr.getValue(), rhsTyAttr.getValue(), Value(), Value(), loc
2417 if (StringAttr lhsSymbolName = getFlatSymbolName(lhsAttr)) {
2418 if (StringAttr rhsSymbolName = getFlatSymbolName(rhsAttr)) {
2419 return recordParamRelation(lhsSymbolName, rhsSymbolName, loc);
2421 if (rhsTyAttr && failed(recordInference(lhsSymbolName, rhsTyAttr.getValue(), Value(), loc))) {
2425 if (StringAttr rhsSymbolName = getFlatSymbolName(rhsAttr)) {
2426 if (lhsTyAttr && failed(recordInference(rhsSymbolName, lhsTyAttr.getValue(), Value(), loc))) {
2435static DenseMap<StringAttr, Type>
2436getFunctionProofReplacements(
const TemplateInferenceInfo &info, FuncDefOp func) {
2437 DenseMap<StringAttr, Type> replacements;
2438 auto funcIt = info.functionReplacements.find(func.getOperation());
2439 if (funcIt == info.functionReplacements.end()) {
2440 return replacements;
2442 for (
const auto &entry : funcIt->second) {
2443 replacements.try_emplace(entry.first, entry.second.type);
2445 return replacements;
2449static std::optional<unsigned>
2450getParamIndex(ArrayRef<StringAttr> paramOrder, StringAttr paramName) {
2451 for (
auto indexedParam : llvm::enumerate(paramOrder)) {
2452 if (indexedParam.value() == paramName) {
2453 return indexedParam.index();
2456 return std::nullopt;
2461static DenseMap<Attribute, Attribute>
2462buildParamNameToConcrete(
const DenseMap<StringAttr, Type> &replacements) {
2463 DenseMap<Attribute, Attribute> paramNameToConcrete;
2464 for (
const auto &entry : replacements) {
2465 paramNameToConcrete.try_emplace(
2466 FlatSymbolRefAttr::get(entry.first), TypeAttr::get(entry.second)
2469 return paramNameToConcrete;
2475static bool callParamsMatchReplacements(
2476 ArrayAttr callParams, ArrayRef<StringAttr> oldParamOrder,
2477 const DenseMap<StringAttr, Type> &replacements,
2478 const DenseMap<StringAttr, InferredType> *wildcardAllowedReplacements =
nullptr
2480 if (!callParams || callParams.size() != oldParamOrder.size()) {
2483 for (
const auto &entry : replacements) {
2484 std::optional<unsigned> index = getParamIndex(oldParamOrder, entry.first);
2488 Type expectedTy = substituteExplicitCallTypeArgs(entry.second, callParams, oldParamOrder);
2489 Attribute attr = callParams[*index];
2490 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>(attr);
2491 intAttr &&
isDynamic(intAttr) && wildcardAllowedReplacements &&
2492 wildcardAllowedReplacements->contains(entry.first)) {
2495 if (!templateArgUnifiesWithType(attr, expectedTy)) {
2508static LogicalResult diagnoseCallParamsMismatch(
2509 Operation *callableOp, ArrayAttr callParams, ArrayRef<StringAttr> oldParamOrder,
2510 const DenseMap<StringAttr, Type> &replacements,
2511 const DenseMap<StringAttr, InferredType> *wildcardAllowedReplacements,
bool explicitCallParams
2513 if (callParamsMatchReplacements(
2514 callParams, oldParamOrder, replacements, wildcardAllowedReplacements
2518 for (
const auto &entry : replacements) {
2519 std::optional<unsigned> index = getParamIndex(oldParamOrder, entry.first);
2520 if (!index || !callParams || *index >= callParams.size()) {
2523 Attribute attr = callParams[*index];
2524 Type expectedTy = substituteExplicitCallTypeArgs(entry.second, callParams, oldParamOrder);
2525 if (
auto intAttr = llvm::dyn_cast<IntegerAttr>(attr);
2526 intAttr &&
isDynamic(intAttr) && wildcardAllowedReplacements &&
2527 wildcardAllowedReplacements->contains(entry.first)) {
2530 if (templateArgUnifiesWithType(attr, expectedTy)) {
2534 InFlightDiagnostic diag = callableOp->emitError()
2535 << (explicitCallParams ?
"explicit" :
"implicit")
2536 <<
" template argument for inferred parameter @"
2537 << entry.first.getValue() <<
" must match inferred type "
2538 << expectedTy <<
", but found ";
2539 if (
auto typeAttr = llvm::dyn_cast<TypeAttr>(attr)) {
2540 diag << typeAttr.getValue();
2546 return callableOp->emitError() << (explicitCallParams ?
"explicit" :
"implicit")
2547 <<
" template arguments do not match inferred callee types";
2553static ArrayAttr expandCurrentTemplateParamsToOriginalOrder(
2554 ArrayAttr callParams,
const TemplateInferenceInfo &info
2556 if (!callParams || callParams.size() == info.oldParamOrder.size()) {
2560 unsigned currentParamCount = llvm::count_if(info.oldParamOrder, [&info](StringAttr paramName) {
2561 return !info.replacements.contains(paramName);
2563 if (callParams.size() != currentParamCount) {
2567 SmallVector<Attribute> expandedParams;
2568 expandedParams.reserve(info.oldParamOrder.size());
2569 unsigned currentIndex = 0;
2570 for (StringAttr paramName : info.oldParamOrder) {
2571 auto replacementIt = info.replacements.find(paramName);
2572 if (replacementIt != info.replacements.end()) {
2573 expandedParams.push_back(TypeAttr::get(replacementIt->second.type));
2576 expandedParams.push_back(callParams[currentIndex++]);
2578 return ArrayAttr::get(callParams.getContext(), expandedParams);
2587template <
typename TargetOp>
2588static DenseMap<StringAttr, Type> getConcreteCallSiteReplacements(
2589 ArrayAttr callParams,
const TemplateInferenceInfo &info, TargetOp targetOp
2591 DenseMap<StringAttr, Type> replacements;
2592 if (!callParams || callParams.size() != info.oldParamOrder.size()) {
2593 return replacements;
2596 bool sawResidualReplacement =
false;
2597 for (
const auto &entry : info.typeVarParams) {
2598 StringAttr paramName = entry.first;
2599 if (info.replacements.contains(paramName)) {
2602 if (!targetMentionsParam(targetOp, paramName)) {
2605 std::optional<unsigned> index = getParamIndex(info.oldParamOrder, paramName);
2606 assert(index &&
"eligible type-variable parameter must appear in parameter order");
2607 Attribute attr = callParams[*index];
2608 auto tyAttr = llvm::dyn_cast<TypeAttr>(attr);
2610 return DenseMap<StringAttr, Type>();
2612 replacements.try_emplace(paramName, tyAttr.getValue());
2613 sawResidualReplacement =
true;
2615 if (!sawResidualReplacement) {
2616 return DenseMap<StringAttr, Type>();
2619 for (
const auto &entry : info.replacements) {
2620 replacements.try_emplace(entry.first, entry.second.type);
2623 TypeVarReplacementConverter converter(
2624 info.templatePath.front().getContext(), info.templatePath, info.oldParamOrder, replacements,
2627 for (
const auto &entry : replacements) {
2629 return DenseMap<StringAttr, Type>();
2632 return replacements;
2636static bool isWildcardTemplateArg(Attribute attr) {
2637 auto intAttr = llvm::dyn_cast_if_present<IntegerAttr>(attr);
2642static void appendUniqueType(SmallVectorImpl<Type> &types, Type ty) {
2643 if (!llvm::any_of(types, [ty](Type existing) {
return existing == ty; })) {
2644 types.push_back(ty);
2649static void collectRhsTypeVarCandidates(
2650 Type lhsTy, Type rhsTy, SymbolRefAttr targetRef, SmallVectorImpl<Type> &candidates
2654static void collectRhsTypeVarCandidates(
2655 ArrayRef<Attribute> lhsAttrs, ArrayRef<Attribute> rhsAttrs, SymbolRefAttr targetRef,
2656 SmallVectorImpl<Type> &candidates
2658 if (lhsAttrs.size() != rhsAttrs.size()) {
2661 for (
auto [lhsAttr, rhsAttr] : llvm::zip_equal(lhsAttrs, rhsAttrs)) {
2662 collectRhsTypeVarCandidates(lhsAttr, rhsAttr, targetRef, candidates);
2667static void collectRhsTypeVarCandidates(
2668 Attribute lhsAttr, Attribute rhsAttr, SymbolRefAttr targetRef, SmallVectorImpl<Type> &candidates
2670 if (
auto rhsTypeAttr = llvm::dyn_cast_if_present<TypeAttr>(rhsAttr)) {
2671 if (
auto lhsTypeAttr = llvm::dyn_cast_if_present<TypeAttr>(lhsAttr)) {
2672 collectRhsTypeVarCandidates(
2673 lhsTypeAttr.getValue(), rhsTypeAttr.getValue(), targetRef, candidates
2679 auto lhsArray = llvm::dyn_cast_if_present<ArrayAttr>(lhsAttr);
2680 auto rhsArray = llvm::dyn_cast_if_present<ArrayAttr>(rhsAttr);
2681 if (!lhsArray || !rhsArray || lhsArray.size() != rhsArray.size()) {
2684 collectRhsTypeVarCandidates(lhsArray.getValue(), rhsArray.getValue(), targetRef, candidates);
2692static void collectRhsTypeVarCandidates(
2693 Type lhsTy, Type rhsTy, SymbolRefAttr targetRef, SmallVectorImpl<Type> &candidates
2695 if (
auto rhsTvar = llvm::dyn_cast<TypeVarType>(rhsTy);
2696 rhsTvar && rhsTvar.getNameRef() == targetRef) {
2697 appendUniqueType(candidates, lhsTy);
2701 if (
auto lhsArray = llvm::dyn_cast<ArrayType>(lhsTy)) {
2702 if (
auto rhsArray = llvm::dyn_cast<ArrayType>(rhsTy)) {
2703 collectRhsTypeVarCandidates(
2704 lhsArray.getElementType(), rhsArray.getElementType(), targetRef, candidates
2706 collectRhsTypeVarCandidates(
2707 lhsArray.getDimensionSizes(), rhsArray.getDimensionSizes(), targetRef, candidates
2713 if (
auto lhsStruct = llvm::dyn_cast<StructType>(lhsTy)) {
2714 if (
auto rhsStruct = llvm::dyn_cast<StructType>(rhsTy)) {
2715 collectRhsTypeVarCandidates(
2716 lhsStruct.getParams(), rhsStruct.getParams(), targetRef, candidates
2722 if (
auto lhsPod = llvm::dyn_cast<PodType>(lhsTy)) {
2723 if (
auto rhsPod = llvm::dyn_cast<PodType>(rhsTy);
2724 rhsPod && lhsPod.getRecords().size() == rhsPod.getRecords().size()) {
2725 for (
auto [lhsRecord, rhsRecord] :
2726 llvm::zip_equal(lhsPod.getRecords(), rhsPod.getRecords())) {
2727 collectRhsTypeVarCandidates(
2728 lhsRecord.getType(), rhsRecord.getType(), targetRef, candidates
2735 if (
auto lhsFunc = llvm::dyn_cast<FunctionType>(lhsTy)) {
2736 if (
auto rhsFunc = llvm::dyn_cast<FunctionType>(rhsTy)) {
2737 for (
auto [lhsInput, rhsInput] : llvm::zip_equal(lhsFunc.getInputs(), rhsFunc.getInputs())) {
2738 collectRhsTypeVarCandidates(lhsInput, rhsInput, targetRef, candidates);
2740 for (
auto [lhsResult, rhsResult] :
2741 llvm::zip_equal(lhsFunc.getResults(), rhsFunc.getResults())) {
2742 collectRhsTypeVarCandidates(lhsResult, rhsResult, targetRef, candidates);
2749static SmallVector<Type>
2750getConflictingRhsTypeVarCandidates(FunctionType lhs, FunctionType rhs, SymbolRefAttr targetRef) {
2751 SmallVector<Type> candidates;
2752 if (lhs.getNumInputs() != rhs.getNumInputs() || lhs.getNumResults() != rhs.getNumResults()) {
2755 for (
auto [lhsInput, rhsInput] : llvm::zip_equal(lhs.getInputs(), rhs.getInputs())) {
2756 collectRhsTypeVarCandidates(lhsInput, rhsInput, targetRef, candidates);
2758 for (
auto [lhsResult, rhsResult] : llvm::zip_equal(lhs.getResults(), rhs.getResults())) {
2759 collectRhsTypeVarCandidates(lhsResult, rhsResult, targetRef, candidates);
2765template <
typename CallableOp,
typename TargetOp>
2767emitConflictingInferredTypes(CallableOp callableOp, TargetOp targetOp, StringAttr paramName) {
2768 InFlightDiagnostic diag = callableOp.emitError()
2769 <<
"conflicting inferred types for @" << paramName.getValue();
2770 SmallVector<Type> candidates = getConflictingRhsTypeVarCandidates(
2771 callableOp.getTypeSignature(), targetOp.getFunctionType(), FlatSymbolRefAttr::get(paramName)
2773 if (candidates.size() >= 2) {
2774 diag <<
": " << candidates.front();
2775 for (Type candidate : llvm::drop_begin(candidates)) {
2776 diag <<
" vs " << candidate;
2783template <
typename CallableOp,
typename TargetOp>
2784static FailureOr<Attribute> getInferredRhsTemplateArg(
2785 CallableOp callableOp, TargetOp targetOp,
const UnificationMap &unifyResult,
2786 StringAttr paramName, StringRef argKind
2788 auto inferredIt = unifyResult.find({FlatSymbolRefAttr::get(paramName), Side::RHS});
2789 if (inferredIt == unifyResult.end()) {
2790 return callableOp.emitError() <<
"could not infer " << argKind
2791 <<
" template argument for parameter @" << paramName.getValue()
2792 <<
" from callee signature";
2794 if (!inferredIt->second) {
2795 return emitConflictingInferredTypes(callableOp, targetOp, paramName);
2797 return inferredIt->second;
2801template <
typename CallableOp,
typename TargetOp>
2802static FailureOr<ArrayAttr> getCallSignatureTemplateParams(
2803 CallableOp callableOp,
const TemplateInferenceInfo &info, TargetOp targetOp
2805 FailureOr<UnificationMap> unifyResult = callableOp.unifyTypeSignature(targetOp.getFunctionType());
2806 if (failed(unifyResult)) {
2807 return callableOp.emitError()
2808 <<
"could not infer omitted template arguments from callee signature";
2811 SmallVector<Attribute> params;
2812 params.reserve(info.oldParamOrder.size());
2813 for (StringAttr paramName : info.oldParamOrder) {
2814 auto replacementIt = info.replacements.find(paramName);
2815 if (replacementIt != info.replacements.end()) {
2816 params.push_back(TypeAttr::get(replacementIt->second.type));
2819 FailureOr<Attribute> inferredAttr =
2820 getInferredRhsTemplateArg(callableOp, targetOp, *unifyResult, paramName,
"omitted");
2821 if (failed(inferredAttr)) {
2824 params.push_back(*inferredAttr);
2826 return ArrayAttr::get(callableOp.getContext(), params);
2831template <
typename TargetOp>
2832static bool hasResidualFunctionTvarWildcard(
2833 ArrayAttr callParams,
const TemplateInferenceInfo &info, TargetOp targetOp
2835 if (!callParams || callParams.size() != info.oldParamOrder.size()) {
2838 for (
const auto &entry : info.typeVarParams) {
2839 StringAttr paramName = entry.first;
2840 if (info.replacements.contains(paramName)) {
2843 if (!targetMentionsParam(targetOp, paramName)) {
2846 std::optional<unsigned> index = getParamIndex(info.oldParamOrder, paramName);
2847 assert(index &&
"eligible type-variable parameter must appear in parameter order");
2848 if (isWildcardTemplateArg(callParams[*index])) {
2857template <
typename CallableOp,
typename TargetOp>
2858static FailureOr<ArrayAttr> materializeResidualFunctionTvarWildcards(
2859 CallableOp callableOp, ArrayAttr callParams,
const TemplateInferenceInfo &info,
2862 FailureOr<UnificationMap> unifyResult = callableOp.unifyTypeSignature(targetOp.getFunctionType());
2863 if (failed(unifyResult)) {
2864 return callableOp.emitError()
2865 <<
"could not infer wildcard template arguments from callee signature";
2868 SmallVector<Attribute> params(callParams.begin(), callParams.end());
2869 for (
const auto &entry : info.typeVarParams) {
2870 StringAttr paramName = entry.first;
2871 if (info.replacements.contains(paramName)) {
2874 if (!targetMentionsParam(targetOp, paramName)) {
2877 std::optional<unsigned> index = getParamIndex(info.oldParamOrder, paramName);
2878 assert(index &&
"eligible type-variable parameter must appear in parameter order");
2879 if (!isWildcardTemplateArg(params[*index])) {
2883 auto inferredIt = unifyResult->find({FlatSymbolRefAttr::get(paramName), Side::RHS});
2884 if (inferredIt == unifyResult->end()) {
2885 auto proofIt = info.functionReplacements.find(targetOp.getOperation());
2886 if (proofIt == info.functionReplacements.end()) {
2889 auto replacementIt = proofIt->second.find(paramName);
2890 if (replacementIt == proofIt->second.end()) {
2893 params[*index] = TypeAttr::get(replacementIt->second.type);
2896 if (!inferredIt->second) {
2897 return emitConflictingInferredTypes(callableOp, targetOp, paramName);
2899 params[*index] = inferredIt->second;
2901 return ArrayAttr::get(callableOp.getContext(), params);
2909template <
typename TargetOp>
2910static bool hasResidualFunctionTvar(
const TemplateInferenceInfo &info, TargetOp targetOp) {
2911 return llvm::any_of(info.typeVarParams, [&](
const auto &entry) {
2912 return !info.replacements.contains(entry.first) && targetMentionsParam(targetOp, entry.first);
2917struct CallableSpecializationInputs {
2919 bool explicitParams =
false;
2920 bool paramsChanged =
false;
2921 DenseMap<StringAttr, Type> replacements;
2925template <
typename CallableOp,
typename TargetOp>
2926static LogicalResult prepareCallableSpecialization(
2927 CallableOp callableOp,
const TemplateInferenceInfo &info, TargetOp targetOp,
2928 CallableSpecializationInputs &inputs,
bool &shouldSpecialize
2930 shouldSpecialize =
false;
2932 inputs.explicitParams =
false;
2933 inputs.paramsChanged =
false;
2934 inputs.replacements.clear();
2935 inputs.params = callableOp.getTemplateParamsAttr();
2938 FailureOr<ArrayAttr> inferredParams =
2939 getCallSignatureTemplateParams(callableOp, info, targetOp);
2940 if (failed(inferredParams)) {
2943 inputs.params = *inferredParams;
2944 inputs.paramsChanged =
true;
2946 inputs.params = expandCurrentTemplateParamsToOriginalOrder(inputs.params, info);
2947 if (hasResidualFunctionTvarWildcard(inputs.params, info, targetOp)) {
2948 FailureOr<ArrayAttr> materializedParams =
2949 materializeResidualFunctionTvarWildcards(callableOp, inputs.params, info, targetOp);
2950 if (failed(materializedParams)) {
2953 inputs.params = *materializedParams;
2954 inputs.paramsChanged =
true;
2958 inputs.replacements = getConcreteCallSiteReplacements(inputs.params, info, targetOp);
2959 shouldSpecialize = !inputs.replacements.empty();
2969static std::string buildTemplateLocalFunctionCloneCacheKey(
2970 StringRef functionName, ArrayRef<StringAttr> oldParamOrder,
2971 const DenseMap<StringAttr, Type> &replacements
2974 llvm::raw_string_ostream os(key);
2975 os << functionName.size() <<
':' << functionName;
2976 for (StringAttr paramName : oldParamOrder) {
2978 os << paramName.getValue().size() <<
':' << paramName.getValue() <<
'=';
2979 auto replacementIt = replacements.find(paramName);
2980 if (replacementIt == replacements.end()) {
2985 std::string typeText;
2986 llvm::raw_string_ostream typeOs(typeText);
2987 replacementIt->second.print(typeOs);
2988 os << typeText.size() <<
':' << typeText;
2994static SymbolRefAttr getSpecializedFunctionCloneCallee(
2995 SymbolRefAttr originalCallee, StringAttr templateName, StringAttr cloneName
2997 SmallVector<FlatSymbolRefAttr> pieces =
getPieces(originalCallee);
2998 assert(pieces.size() >= 2 &&
"callee must include at least template and function names");
3001 pieces.push_back(FlatSymbolRefAttr::get(templateName));
3002 pieces.push_back(FlatSymbolRefAttr::get(cloneName));
3007template <
typename CallableOp,
typename ConfigureCloneFn>
3008static FailureOr<SymbolRefAttr> getOrCreateSpecializedCallableClone(
3009 TemplateOp templateOp, CallableOp callable, SymbolRefAttr originalCallee,
3010 const TemplateInferenceInfo &info,
const DenseMap<StringAttr, Type> &replacements,
3011 SymbolTableCollection &tables, llvm::StringMap<SymbolRefAttr> &cloneCallees,
3012 llvm::StringMap<StringAttr> &templateClones, InstantiationLayout &layout, ArrayAttr callParams,
3013 ConfigureCloneFn configureClone
3015 DenseMap<Attribute, Attribute> paramNameToConcrete = buildParamNameToConcrete(replacements);
3016 FailureOr<TemplateOp> newTemplate = getOrCreateSpecializedTemplateClone(
3017 templateOp, info.oldParamOrder, paramNameToConcrete, callParams, tables, templateClones,
3020 if (failed(newTemplate)) {
3024 std::string cacheKey = buildTemplateLocalFunctionCloneCacheKey(
3025 callable.getSymName(), info.oldParamOrder, replacements
3027 auto cachedCallee = cloneCallees.find(cacheKey);
3028 if (cachedCallee != cloneCallees.end()) {
3029 return cachedCallee->second;
3032 SymbolTable &templateSymbols = tables.getSymbolTable(*newTemplate);
3034 auto clone = llvm::cast<CallableOp>(callable.getOperation()->clone());
3035 configureClone(clone);
3036 templateSymbols.insert(clone);
3038 TypeVarReplacementConverter converter(
3039 templateOp.getContext(), info.templatePath, info.oldParamOrder, replacements,
3042 if (failed(convertTemplateExprTypesIn(*newTemplate, converter))) {
3046 if (failed(convertOperationTypesIn(clone.getOperation(), converter))) {
3050 removeIdentityCasts(clone.getOperation());
3051 SymbolRefAttr cloneCallee = getSpecializedFunctionCloneCallee(
3052 originalCallee, newTemplate->getSymNameAttr(), clone.
getSymNameAttr()
3054 cloneCallees.try_emplace(cacheKey, cloneCallee);
3059static FailureOr<SymbolRefAttr> getOrCreateSpecializedFunctionClone(
3060 TemplateOp templateOp, FuncDefOp func, SymbolRefAttr originalCallee,
3061 const TemplateInferenceInfo &info,
const DenseMap<StringAttr, Type> &replacements,
3062 SymbolTableCollection &tables, llvm::StringMap<SymbolRefAttr> &cloneCallees,
3063 llvm::StringMap<StringAttr> &templateClones, InstantiationLayout &layout, ArrayAttr callParams
3065 return getOrCreateSpecializedCallableClone(
3066 templateOp, func, originalCallee, info, replacements, tables, cloneCallees, templateClones,
3067 layout, callParams, [](FuncDefOp) {}
3072static FailureOr<SymbolRefAttr> getOrCreateSpecializedContractClone(
3073 TemplateOp templateOp, verif::ContractOp contract, SymbolRefAttr originalCallee,
3074 SymbolRefAttr specializedTarget,
const TemplateInferenceInfo &info,
3075 const DenseMap<StringAttr, Type> &replacements, SymbolTableCollection &tables,
3076 llvm::StringMap<SymbolRefAttr> &cloneCallees, llvm::StringMap<StringAttr> &templateClones,
3077 InstantiationLayout &layout, ArrayAttr callParams
3079 return getOrCreateSpecializedCallableClone(
3080 templateOp, contract, originalCallee, info, replacements, tables, cloneCallees,
3081 templateClones, layout, callParams,
3082 [specializedTarget](verif::ContractOp clone) { clone.
setTargetAttr(specializedTarget); }
3091static LogicalResult removeResolvedParams(TemplateInferenceInfo &info) {
3092 if (info.replacements.empty()) {
3096 DenseMap<StringAttr, Type> replacements;
3097 for (
const auto &entry : info.replacements) {
3098 replacements.try_emplace(entry.first, entry.second.type);
3100 DenseMap<Attribute, Attribute> paramNameToConcrete = buildParamNameToConcrete(replacements);
3101 FailureOr<InstantiationLayout> layout =
3103 if (failed(layout)) {
3108 for (
auto paramOp : llvm::make_early_inc_range(info.templateOp.
getConstOps<TemplateParamOp>())) {
3109 auto name = paramOp.getSymNameAttr();
3110 if (info.replacements.contains(name)) {
3115 info.templateOp, layout->remainingNames.empty() ? ArrayAttr() : layout->namePattern
3121template <
typename CallableOp>
3123validateWildcardCallableSignature(CallableOp callableOp, FunctionType targetTy) {
3124 if (succeeded(callableOp.unifyTypeSignature(targetTy))) {
3127 return callableOp.emitError() <<
"call signature " << callableOp.getTypeSignature()
3128 <<
" does not match inferred callee signature " << targetTy;
3132static void updateCallableResultTypesIfNeeded(
3133 CallOp callOp,
const TypeVarReplacementConverter &converter,
bool &modified
3135 for (Value result : callOp.getResults()) {
3136 Type newTy = converter.convertType(result.getType());
3137 if (newTy != result.getType()) {
3138 result.setType(newTy);
3146updateCallableResultTypesIfNeeded(verif::IncludeOp,
const TypeVarReplacementConverter &,
bool &) {}
3149template <
typename CallableOp>
3150static FailureOr<bool> updateCallableTemplateParamsFor(
3151 ModuleOp module, DenseMap<Operation *, const TypeVarReplacementConverter *> &converters,
3152 SymbolTableCollection &tables
3154 bool modified =
false;
3155 bool failedConversion =
false;
3156 module.walk([&](CallableOp callableOp) {
3157 if (failedConversion) {
3160 auto target = callableOp.getCalleeTarget(tables);
3161 if (failed(target)) {
3164 auto targetOp = target->get();
3166 if (!parentTemplate) {
3169 const TypeVarReplacementConverter *converter = converters.lookup(parentTemplate.getOperation());
3175 bool resolveTemplateSymbolArgs =
3176 callableTemplate && callableTemplate.getOperation() == parentTemplate.getOperation();
3177 ArrayAttr oldParams = callableOp.getTemplateParamsAttr();
3178 FailureOr<ArrayAttr> newParams = converter->convertTemplateParams(
3179 oldParams, callableOp, resolveTemplateSymbolArgs,
3182 if (failed(newParams)) {
3183 failedConversion =
true;
3186 if (converter->hasWildcardForRemovedParam(oldParams)) {
3187 auto inferredTargetTy =
3188 llvm::cast<FunctionType>(converter->convertType(targetOp.getFunctionType()));
3189 if (failed(validateWildcardCallableSignature(callableOp, inferredTargetTy))) {
3190 failedConversion =
true;
3194 if (oldParams != *newParams) {
3195 callableOp.setTemplateParamsAttr(*newParams);
3199 updateCallableResultTypesIfNeeded(callableOp, *converter, modified);
3201 if (failedConversion) {
3214static FailureOr<bool> updateCallableTemplateParams(
3215 ModuleOp module, DenseMap<Operation *, const TypeVarReplacementConverter *> &converters
3217 SymbolTableCollection tables;
3218 FailureOr<bool> callsModified =
3219 updateCallableTemplateParamsFor<CallOp>(module, converters, tables);
3220 if (failed(callsModified)) {
3223 FailureOr<bool> includesModified =
3224 updateCallableTemplateParamsFor<verif::IncludeOp>(module, converters, tables);
3225 if (failed(includesModified)) {
3228 return *callsModified || *includesModified;
3237class ReferencedStructTemplateParamConverter {
3243 SymbolTableCollection &tables_;
3245 DenseMap<Operation *, const TypeVarReplacementConverter *> &converters_;
3247 Operation *diagnosticOp_ =
nullptr;
3249 bool hasFailure =
false;
3252 ReferencedStructTemplateParamConverter(
3253 MLIRContext *ctx, ModuleOp module, SymbolTableCollection &tables,
3254 DenseMap<Operation *, const TypeVarReplacementConverter *> &converters
3256 : ctx_(ctx), module_(module), tables_(tables), converters_(converters) {}
3259 void startOperation(Operation *op) {
3265 bool hadFailure()
const {
return hasFailure; }
3268 Type convertType(Type ty) {
3269 if (!ty || hasFailure) {
3272 if (
auto arrTy = llvm::dyn_cast<ArrayType>(ty)) {
3273 return convertArrayElementType(arrTy, [
this](Type elemTy) {
return convertType(elemTy); });
3275 if (
auto structTy = llvm::dyn_cast<StructType>(ty)) {
3276 return convertStructType(structTy);
3278 if (
auto podTy = llvm::dyn_cast<PodType>(ty)) {
3279 return convertPodType(podTy, ctx_, *
this);
3281 if (
auto funcTy = llvm::dyn_cast<FunctionType>(ty)) {
3282 return convertFunctionType(funcTy, *
this);
3288 Attribute convertAttr(Attribute attr) {
3292 return convertTypeOrArrayAttr(attr, ctx_, [
this](Type ty) {
3293 return convertType(ty);
3294 }, [
this](Attribute nested) {
return convertAttr(nested); });
3299 StructType convertStructType(StructType structTy) {
3300 ArrayAttr params = structTy.
getParams();
3305 SmallVector<Attribute> newParams;
3306 bool changed =
false;
3307 for (Attribute attr : params.getValue()) {
3308 Attribute newAttr = convertAttr(attr);
3309 newParams.push_back(newAttr);
3310 changed |= newAttr != attr;
3315 StructType convertedTy =
3319 tables_, convertedTy.
getNameRef(), module_,
false
3321 if (failed(lookup)) {
3325 if (!parentTemplate) {
3328 const TypeVarReplacementConverter *converter =
3329 converters_.lookup(parentTemplate.getOperation());
3335 bool resolveTemplateSymbolArgs =
3336 useTemplate && useTemplate.getOperation() == parentTemplate.getOperation();
3337 FailureOr<ArrayAttr> trimmedParams = converter->convertTemplateParams(
3338 convertedTy.
getParams(), diagnosticOp_, resolveTemplateSymbolArgs,
3341 if (failed(trimmedParams)) {
3345 if (convertedTy.
getParams() == *trimmedParams) {
3353static FailureOr<bool> updateStructTemplateParams(
3354 ModuleOp module, DenseMap<Operation *, const TypeVarReplacementConverter *> &converters
3356 SymbolTableCollection tables;
3357 ReferencedStructTemplateParamConverter converter(module.getContext(), module, tables, converters);
3358 return convertOperationTypesInAndTrack(module.getOperation(), converter);
3362static LogicalResult instantiateConcreteStructUses(ModuleOp module) {
3363 SymbolTableCollection tables;
3364 ConcreteStructInstantiationConverter converter(module.getContext(), module, tables);
3365 return convertOperationTypesIn(module.getOperation(), converter);
3370getContractTargetTemplate(verif::ContractOp contract, SymbolTableCollection &tables) {
3371 if (FailureOr<SymbolLookupResult<FuncDefOp>> funcTarget = contract.
getFuncTarget(tables);
3372 succeeded(funcTarget)) {
3375 if (FailureOr<SymbolLookupResult<StructDefOp>> structTarget = contract.
getStructTarget(tables);
3376 succeeded(structTarget)) {
3388static LogicalResult updateExternalContractTemplateParams(
3389 ModuleOp module, DenseMap<Operation *, const TypeVarReplacementConverter *> &converters
3391 bool failedConversion =
false;
3392 SymbolTableCollection tables;
3393 module.walk([&](verif::ContractOp contract) {
3394 if (failedConversion) {
3397 TemplateOp targetTemplate = getContractTargetTemplate(contract, tables);
3398 if (!targetTemplate) {
3404 const TypeVarReplacementConverter *converter = converters.lookup(targetTemplate.getOperation());
3409 auto validationResult = contract.walk([converter](Operation *op) -> WalkResult {
3410 return converter->validateOperation(op);
3412 if (validationResult.wasInterrupted() ||
3413 failed(convertOperationTypesIn(contract.getOperation(), *converter))) {
3414 failedConversion =
true;
3417 removeIdentityCasts(contract.getOperation());
3419 return failure(failedConversion);
3430static LogicalResult specializeFunctionLocalCallables(
3431 ModuleOp module, DenseMap<Operation *, const TemplateInferenceInfo *> &infoByTemplate,
3432 SpecializedCallableCloneCache &functionCloneCache,
3433 SpecializedCallableCloneCache &contractCloneCache,
3434 SpecializedTemplateCloneCache &templateCloneCache
3436 bool failedClone =
false;
3437 SymbolTableCollection tables;
3438 module.walk([&](CallOp callOp) {
3442 FailureOr<SymbolLookupResult<FuncDefOp>> target = callOp.
getCalleeTarget(tables);
3443 if (failed(target)) {
3446 FuncDefOp targetFunc = target->get();
3447 auto parentTemplate = llvm::dyn_cast_or_null<TemplateOp>(targetFunc->getParentOp());
3448 if (!parentTemplate) {
3451 const TemplateInferenceInfo *info = infoByTemplate.lookup(parentTemplate.getOperation());
3455 if (!hasResidualFunctionTvar(*info, targetFunc)) {
3459 CallableSpecializationInputs inputs;
3460 bool shouldSpecialize =
false;
3462 prepareCallableSpecialization(callOp, *info, targetFunc, inputs, shouldSpecialize)
3467 if (!shouldSpecialize) {
3470 DenseMap<StringAttr, Type> inferredReplacements =
3471 getFunctionProofReplacements(*info, targetFunc);
3472 if (failed(diagnoseCallParamsMismatch(
3473 callOp.getOperation(), inputs.params, info->oldParamOrder, inferredReplacements,
3474 &info->replacements, inputs.explicitParams
3480 InstantiationLayout layout;
3481 FailureOr<SymbolRefAttr> cloneCallee = getOrCreateSpecializedFunctionClone(
3482 parentTemplate, targetFunc, callOp.
getCalleeAttr(), *info, inputs.replacements, tables,
3483 functionCloneCache[parentTemplate.getOperation()],
3484 templateCloneCache[parentTemplate.getOperation()], layout, inputs.params
3486 if (failed(cloneCallee)) {
3494 module.walk([&](verif::IncludeOp includeOp) {
3498 FailureOr<SymbolLookupResult<verif::ContractOp>> target = includeOp.
getCalleeTarget(tables);
3499 if (failed(target)) {
3502 verif::ContractOp targetContract = target->get();
3503 auto parentTemplate = llvm::dyn_cast_or_null<TemplateOp>(targetContract->getParentOp());
3504 if (!parentTemplate) {
3507 const TemplateInferenceInfo *info = infoByTemplate.lookup(parentTemplate.getOperation());
3511 if (!hasResidualFunctionTvar(*info, targetContract)) {
3515 FailureOr<SymbolLookupResult<FuncDefOp>> targetFuncResult =
3517 if (failed(targetFuncResult)) {
3520 FuncDefOp targetFunc = targetFuncResult->get();
3525 CallableSpecializationInputs inputs;
3526 bool shouldSpecialize =
false;
3527 if (failed(prepareCallableSpecialization(
3528 includeOp, *info, targetContract, inputs, shouldSpecialize
3533 if (!shouldSpecialize) {
3536 DenseMap<StringAttr, Type> inferredReplacements =
3537 getFunctionProofReplacements(*info, targetFunc);
3538 if (failed(diagnoseCallParamsMismatch(
3539 includeOp.getOperation(), inputs.params, info->oldParamOrder, inferredReplacements,
3540 &info->replacements, inputs.explicitParams
3546 InstantiationLayout targetLayout;
3547 FailureOr<SymbolRefAttr> specializedTarget = getOrCreateSpecializedFunctionClone(
3548 parentTemplate, targetFunc, targetContract.
getTargetAttr(), *info, inputs.replacements,
3549 tables, functionCloneCache[parentTemplate.getOperation()],
3550 templateCloneCache[parentTemplate.getOperation()], targetLayout, inputs.params
3552 if (failed(specializedTarget)) {
3556 InstantiationLayout contractLayout;
3557 FailureOr<SymbolRefAttr> cloneCallee = getOrCreateSpecializedContractClone(
3558 parentTemplate, targetContract, includeOp.
getCalleeAttr(), *specializedTarget, *info,
3559 inputs.replacements, tables, contractCloneCache[parentTemplate.getOperation()],
3560 templateCloneCache[parentTemplate.getOperation()], contractLayout, inputs.params
3562 if (failed(cloneCallee)) {
3570 return failure(failedClone);
3574static bool sameReplacementTypes(
3575 const DenseMap<StringAttr, InferredType> &lhs,
const DenseMap<StringAttr, InferredType> &rhs
3577 if (lhs.size() != rhs.size()) {
3580 for (
const auto &entry : lhs) {
3581 auto rhsIt = rhs.find(entry.first);
3582 if (rhsIt == rhs.end() || rhsIt->second.type != entry.second.type) {
3595static LogicalResult collectContractTargetFunctionInferences(
3596 TemplateInferenceInfo &info, verif::ContractOp contract, ModuleOp module,
3597 DenseMap<Operation *, TemplateInferenceInfo *> *infoByTemplate, SymbolTableCollection &tables,
3600 FailureOr<SymbolLookupResult<FuncDefOp>> target = contract.
getFuncTarget(tables);
3601 if (failed(target)) {
3604 FuncDefOp targetFunc = target->get();
3609 DenseMap<StringAttr, InferredType> funcReplacements;
3610 auto funcIt = info.functionReplacements.find(targetFunc.getOperation());
3611 if (funcIt != info.functionReplacements.end()) {
3612 funcReplacements = funcIt->second;
3614 DenseMap<StringAttr, InferredType> oldFuncReplacements = funcReplacements;
3616 TypeVarInferenceCollector collector(info, funcReplacements);
3617 if (failed(collector.collect(contract.getOperation()))) {
3620 if (infoByTemplate && failed(collector.collectStructTemplateParamInferences(
3621 contract.getOperation(), module, *infoByTemplate, tables
3626 if (!sameReplacementTypes(oldFuncReplacements, funcReplacements)) {
3629 if (funcReplacements.empty()) {
3630 info.functionReplacements.erase(targetFunc.getOperation());
3632 info.functionReplacements[targetFunc.getOperation()] = std::move(funcReplacements);
3643static LogicalResult collectContractTargetStructInferences(
3644 TemplateInferenceInfo &info, verif::ContractOp contract, ModuleOp module,
3645 DenseMap<Operation *, TemplateInferenceInfo *> *infoByTemplate, SymbolTableCollection &tables,
3648 FailureOr<SymbolLookupResult<StructDefOp>> target = contract.
getStructTarget(tables);
3649 if (failed(target)) {
3652 StructDefOp targetStruct = target->get();
3657 DenseMap<StringAttr, InferredType> oldTemplateScopeReplacements = info.templateScopeReplacements;
3659 TypeVarInferenceCollector collector(info, info.templateScopeReplacements);
3661 if (contractTy.getNumInputs() > 0) {
3662 StructType targetSelfTy = targetStruct.
getType();
3663 if (
auto contractSelfTy = llvm::dyn_cast<StructType>(contractTy.getInput(0));
3664 contractSelfTy && contractSelfTy.getNameRef() == targetSelfTy.
getNameRef() &&
3665 failed(collector.collectTypeInferences(contractSelfTy, targetSelfTy, contract.getLoc()))) {
3669 if (failed(collector.collect(contract.getOperation()))) {
3672 if (infoByTemplate && failed(collector.collectStructTemplateParamInferences(
3673 contract.getOperation(), module, *infoByTemplate, tables
3678 if (!sameReplacementTypes(oldTemplateScopeReplacements, info.templateScopeReplacements)) {
3693static LogicalResult recomputeTemplateWideReplacements(TemplateInferenceInfo &info) {
3694 DenseMap<StringAttr, unsigned> mentionCounts;
3695 DenseMap<StringAttr, unsigned> proofCounts;
3696 DenseMap<StringAttr, InferredType> commonReplacements;
3697 DenseSet<StringAttr> incompatibleReplacements;
3699 for (FuncDefOp func : walkCollect<FuncDefOp>(info.templateOp)) {
3700 for (
const auto &entry : info.typeVarParams) {
3701 if (funcMentionsParam(func, entry.first)) {
3702 ++mentionCounts[entry.first];
3706 auto funcIt = info.functionReplacements.find(func.getOperation());
3707 if (funcIt == info.functionReplacements.end()) {
3710 for (
const auto &entry : funcIt->second) {
3711 ++proofCounts[entry.first];
3712 auto commonIt = commonReplacements.find(entry.first);
3713 if (commonIt == commonReplacements.end()) {
3714 commonReplacements.try_emplace(entry.first, entry.second);
3715 }
else if (commonIt->second.type != entry.second.type) {
3716 incompatibleReplacements.insert(entry.first);
3721 for (TemplateExprOp expr : walkCollect<TemplateExprOp>(info.templateOp)) {
3722 for (
const auto &entry : info.typeVarParams) {
3723 if (exprMentionsParam(expr, entry.first)) {
3724 ++mentionCounts[entry.first];
3729 info.replacements = info.templateScopeReplacements;
3730 for (
const auto &entry : info.templateScopeReplacements) {
3731 auto commonIt = commonReplacements.find(entry.first);
3732 if (commonIt != commonReplacements.end() && commonIt->second.type != entry.second.type) {
3733 InFlightDiagnostic diag = emitError(entry.second.loc)
3734 <<
"conflicting inferred type for template parameter @"
3735 << entry.first.getValue() <<
": " << commonIt->second.type <<
" vs "
3736 << entry.second.type;
3737 diag.attachNote(commonIt->second.loc) <<
"previous function-local inference here";
3742 for (
const auto &entry : commonReplacements) {
3743 StringAttr paramName = entry.first;
3744 if (info.replacements.contains(paramName)) {
3747 if (!hasUncoveredNonFunctionMention(
3748 info.templateOp, paramName, entry.second.type, info.functionReplacements
3750 !incompatibleReplacements.contains(paramName) &&
3751 proofCounts.lookup(paramName) == mentionCounts.lookup(paramName)) {
3752 info.replacements.try_emplace(paramName, entry.second);
3760static LogicalResult inferStructTemplateParamUses(
3761 ModuleOp module, MutableArrayRef<TemplateInferenceInfo> templateInfos,
3762 DenseMap<Operation *, TemplateInferenceInfo *> &infoByTemplate
3764 bool changed =
false;
3767 SymbolTableCollection tables;
3768 for (TemplateInferenceInfo &info : templateInfos) {
3769 for (FuncDefOp func : walkCollect<FuncDefOp>(info.templateOp)) {
3770 DenseMap<StringAttr, InferredType> funcReplacements;
3771 auto funcIt = info.functionReplacements.find(func.getOperation());
3772 if (funcIt != info.functionReplacements.end()) {
3773 funcReplacements = funcIt->second;
3775 DenseMap<StringAttr, InferredType> oldFuncReplacements = funcReplacements;
3777 TypeVarInferenceCollector collector(info, funcReplacements);
3778 if (failed(collector.collect(func.getOperation())) ||
3779 failed(collector.collectStructTemplateParamInferences(
3780 func.getOperation(), module, infoByTemplate, tables
3785 if (!sameReplacementTypes(oldFuncReplacements, funcReplacements)) {
3788 if (funcReplacements.empty()) {
3789 info.functionReplacements.erase(func.getOperation());
3791 info.functionReplacements[func.getOperation()] = std::move(funcReplacements);
3795 for (verif::ContractOp contract : walkCollect<verif::ContractOp>(info.templateOp)) {
3796 if (failed(collectContractTargetFunctionInferences(
3797 info, contract, module, &infoByTemplate, tables, changed
3799 failed(collectContractTargetStructInferences(
3800 info, contract, module, &infoByTemplate, tables, changed
3806 for (TemplateExprOp expr : walkCollect<TemplateExprOp>(info.templateOp)) {
3807 DenseMap<StringAttr, InferredType> oldTemplateScopeReplacements =
3808 info.templateScopeReplacements;
3810 TypeVarInferenceCollector collector(info, info.templateScopeReplacements);
3811 if (failed(collector.collect(expr.getOperation())) ||
3812 failed(collector.collectStructTemplateParamInferences(
3813 expr.getOperation(), module, infoByTemplate, tables
3818 if (!sameReplacementTypes(oldTemplateScopeReplacements, info.templateScopeReplacements)) {
3823 DenseMap<StringAttr, InferredType> oldTemplateScopeReplacements =
3824 info.templateScopeReplacements;
3825 TypeVarInferenceCollector collector(info, info.templateScopeReplacements);
3826 auto nonFunctionResult = info.templateOp.walk([&](Operation *op) -> WalkResult {
3827 if (llvm::isa<FuncDefOp, TemplateExprOp, verif::ContractOp>(op) ||
3829 return WalkResult::advance();
3831 return collector.collectOperationStructTemplateParamInferences(
3832 op, module, infoByTemplate, tables
3835 if (nonFunctionResult.wasInterrupted()) {
3838 if (!sameReplacementTypes(oldTemplateScopeReplacements, info.templateScopeReplacements)) {
3842 DenseMap<StringAttr, InferredType> oldReplacements = info.replacements;
3843 if (failed(recomputeTemplateWideReplacements(info))) {
3846 if (!sameReplacementTypes(oldReplacements, info.replacements)) {
3856static LogicalResult collectExternalContractTargetInferences(
3857 ModuleOp module, MutableArrayRef<TemplateInferenceInfo> templateInfos,
3858 DenseMap<Operation *, TemplateInferenceInfo *> &infoByTemplate
3860 bool changed =
false;
3863 bool failedCollection =
false;
3864 SymbolTableCollection tables;
3865 module.walk([&](verif::ContractOp contract) {
3866 TemplateOp targetTemplate = getContractTargetTemplate(contract, tables);
3867 if (!targetTemplate) {
3873 TemplateInferenceInfo *info = infoByTemplate.lookup(targetTemplate.getOperation());
3877 if (failed(collectContractTargetFunctionInferences(
3878 *info, contract, module, &infoByTemplate, tables, changed
3880 failed(collectContractTargetStructInferences(
3881 *info, contract, module, &infoByTemplate, tables, changed
3883 failedCollection =
true;
3886 if (failedCollection) {
3890 for (TemplateInferenceInfo &info : templateInfos) {
3891 DenseMap<StringAttr, InferredType> oldReplacements = info.replacements;
3892 if (failed(recomputeTemplateWideReplacements(info))) {
3895 if (!sameReplacementTypes(oldReplacements, info.replacements)) {
3910static FailureOr<TemplateInferenceInfo> buildInfo(TemplateOp templateOp) {
3911 TemplateInferenceInfo info;
3912 info.templateOp = templateOp;
3913 FailureOr<SymbolRefAttr> templatePath =
3914 getPathFromRoot(llvm::cast<SymbolOpInterface>(templateOp.getOperation()));
3915 if (failed(templatePath)) {
3918 info.templatePath = getStringPieces(*templatePath);
3919 for (TemplateParamOp paramOp : templateOp.
getConstOps<TemplateParamOp>()) {
3920 auto name = paramOp.getSymNameAttr();
3921 info.oldParamOrder.push_back(name);
3922 if (isTypeVarParam(paramOp)) {
3923 info.typeVarParams.try_emplace(name, paramOp);
3927 for (FuncDefOp func : walkCollect<FuncDefOp>(templateOp)) {
3928 DenseMap<StringAttr, InferredType> funcReplacements;
3929 if (failed(TypeVarInferenceCollector(info, funcReplacements).collect(func.getOperation()))) {
3932 if (!funcReplacements.empty()) {
3933 info.functionReplacements.try_emplace(func.getOperation(), funcReplacements);
3937 for (TemplateExprOp expr : walkCollect<TemplateExprOp>(templateOp)) {
3938 if (failed(TypeVarInferenceCollector(info, info.templateScopeReplacements)
3939 .collect(expr.getOperation()))) {
3944 bool changed =
false;
3945 SymbolTableCollection tables;
3946 ModuleOp module = templateOp->getParentOfType<ModuleOp>();
3947 for (verif::ContractOp contract : walkCollect<verif::ContractOp>(templateOp)) {
3948 if (failed(collectContractTargetFunctionInferences(
3949 info, contract, module,
nullptr, tables, changed
3951 failed(collectContractTargetStructInferences(
3952 info, contract, module,
nullptr, tables, changed
3958 if (failed(recomputeTemplateWideReplacements(info))) {
3971class PassImpl :
public llzk::polymorphic::impl::TypeVarInferencePassBase<PassImpl> {
3973 using Base = TypeVarInferencePassBase<PassImpl>;
3977 void runOnOperation()
override {
3978 ModuleOp module = getOperation();
3983 std::vector<TemplateInferenceInfo> templateInfos;
3984 WalkResult collectResult =
module.walk([&templateInfos](TemplateOp templateOp) {
3985 if (templateOp.getConstOps<TemplateParamOp>().empty()) {
3986 return WalkResult::advance();
3988 FailureOr<TemplateInferenceInfo> info = buildInfo(templateOp);
3990 return WalkResult::interrupt();
3992 templateInfos.push_back(std::move(*info));
3993 return WalkResult::advance();
3995 if (collectResult.wasInterrupted()) {
3996 signalPassFailure();
3999 if (templateInfos.empty()) {
4003 DenseMap<Operation *, TemplateInferenceInfo *> mutableInfoByTemplate;
4004 for (TemplateInferenceInfo &info : templateInfos) {
4005 mutableInfoByTemplate.try_emplace(info.templateOp.getOperation(), &info);
4008 collectExternalContractTargetInferences(module, templateInfos, mutableInfoByTemplate)
4010 signalPassFailure();
4013 if (failed(inferStructTemplateParamUses(module, templateInfos, mutableInfoByTemplate))) {
4014 signalPassFailure();
4018 SmallVector<TemplateInferenceInfo *> rewrites;
4019 DenseMap<Operation *, const TemplateInferenceInfo *> infoByTemplate;
4020 for (TemplateInferenceInfo &info : templateInfos) {
4021 infoByTemplate.try_emplace(info.templateOp.getOperation(), &info);
4022 if (!info.replacements.empty() || !info.functionReplacements.empty()) {
4023 rewrites.push_back(&info);
4029 SmallVector<std::unique_ptr<TypeVarReplacementConverter>> converterStorage;
4030 DenseMap<Operation *, const TypeVarReplacementConverter *> convertersByTemplate;
4031 for (TemplateInferenceInfo *info : rewrites) {
4032 DenseMap<StringAttr, Type> replacements;
4033 for (
const auto &entry : info->replacements) {
4034 replacements.try_emplace(entry.first, entry.second.type);
4036 auto converter = std::make_unique<TypeVarReplacementConverter>(
4037 module.getContext(), info->templatePath, info->oldParamOrder, replacements
4039 convertersByTemplate.try_emplace(info->templateOp.getOperation(), converter.get());
4040 converterStorage.push_back(std::move(converter));
4045 SpecializedCallableCloneCache functionCloneCache;
4046 SpecializedCallableCloneCache contractCloneCache;
4047 SpecializedTemplateCloneCache templateCloneCache;
4048 if (failed(specializeFunctionLocalCallables(
4049 module, infoByTemplate, functionCloneCache, contractCloneCache, templateCloneCache
4051 signalPassFailure();
4058 if (failed(updateCallableTemplateParams(module, convertersByTemplate))) {
4059 signalPassFailure();
4063 for (TemplateInferenceInfo *info : rewrites) {
4064 const TypeVarReplacementConverter *converter =
4065 convertersByTemplate.lookup(info->templateOp.getOperation());
4066 assert(converter &&
"rewritten template must have a converter");
4067 auto validationResult = info->templateOp.walk([converter](Operation *op) -> WalkResult {
4068 return converter->validateOperation(op);
4070 if (validationResult.wasInterrupted()) {
4071 signalPassFailure();
4074 if (failed(convertOperationTypesIn(info->templateOp.getOperation(), *converter))) {
4075 signalPassFailure();
4078 removeIdentityCasts(info->templateOp.getOperation());
4081 if (failed(updateExternalContractTemplateParams(module, convertersByTemplate))) {
4082 signalPassFailure();
4088 if (failed(updateCallableTemplateParams(module, convertersByTemplate))) {
4089 signalPassFailure();
4094 if (failed(specializeFunctionLocalCallables(
4095 module, infoByTemplate, functionCloneCache, contractCloneCache, templateCloneCache
4097 signalPassFailure();
4100 if (failed(updateStructTemplateParams(module, convertersByTemplate))) {
4101 signalPassFailure();
4108 for (TemplateInferenceInfo *info : rewrites) {
4109 if (failed(removeResolvedParams(*info))) {
4110 signalPassFailure();
4115 if (failed(instantiateConcreteStructUses(module))) {
4116 signalPassFailure();
Common private implementation for poly dialect passes.
This file defines methods symbol lookup across LLZK operations and included files.
Helper for converting between linear and multi-dimensional indexing with checks to ensure indices are...
static ArrayIndexGen from(ArrayType)
Construct new ArrayIndexGen. Will assert if hasStaticShape() is false.
ArrayType cloneWith(std::optional<::llvm::ArrayRef< int64_t > > shape, ::mlir::Type elementType) const
Clone this type with the given shape and element type.
::mlir::Type getElementType() const
::llvm::ArrayRef<::mlir::Attribute > getDimensionSizes() const
::mlir::TypedValue<::llzk::array::ArrayType > getResult()
::mlir::Operation::operand_range getElements()
StructType getType(::std::optional<::mlir::ArrayAttr > constParams={})
Gets the StructType representing this struct.
::mlir::SymbolRefAttr getFullyQualifiedName()
Return the full name for this struct from the root module, including any surrounding module scopes.
::mlir::StringAttr getSymNameAttr()
::mlir::SymbolRefAttr getNameRef() const
static StructType get(::mlir::SymbolRefAttr structName)
::mlir::FailureOr< SymbolLookupResult< StructDefOp > > getDefinition(::mlir::SymbolTableCollection &symbolTable, ::mlir::Operation *op, bool reportMissing=true) const
Gets the struct op that defines this struct.
::mlir::ArrayAttr getParams() const
::mlir::SymbolRefAttr getCalleeAttr()
::mlir::SymbolRefAttr getCallee()
void setTemplateParamsAttr(::mlir::ArrayAttr attr)
::mlir::Value getSelfValueFromConstrain()
Return the "self" value (i.e.
::llzk::component::StructType getSingleResultTypeOfWitnessGen()
Assuming the callee contains witness generation code, return the single StructType result.
void setCalleeAttr(::mlir::SymbolRefAttr attr)
::mlir::FailureOr<::llzk::SymbolLookupResult<::llzk::function::FuncDefOp > > getCalleeTarget(::mlir::SymbolTableCollection &tables)
Resolve and return the target FuncDefOp for this CallOp.
::mlir::FunctionType getFunctionType()
static PodType get(::mlir::MLIRContext *context, ::llvm::ArrayRef<::llzk::pod::RecordAttr > records)
::llvm::ArrayRef<::llzk::pod::RecordAttr > getRecords() const
::mlir::FlatSymbolRefAttr getConstNameAttr()
::mlir::Region & getBodyRegion()
OpT getConstNamed(::mlir::StringRef find)
Return the op of type OpT with the given name within the body region if it exists,...
::mlir::StringAttr getSymNameAttr()
void setSymName(::llvm::StringRef attrValue)
::llvm::StringRef getSymName()
inline ::llvm::iterator_range<::mlir::Region::op_iterator< OpT > > getConstOps()
Return ops of type OpT within the body region.
::std::optional<::mlir::Type > getTypeOpt()
::mlir::TypedValue<::mlir::Type > getInput()
::mlir::TypedValue<::mlir::Type > getResult()
::mlir::FailureOr< SymbolLookupResult< function::FuncDefOp > > getFuncTarget(::mlir::SymbolTableCollection &tables)
Return the FuncDefOp that this contract targets, or failure if it does not target a function or the f...
void setTargetAttr(::mlir::SymbolRefAttr attr)
::mlir::FunctionType getFunctionType()
::mlir::Region & getBody()
::mlir::FailureOr< SymbolLookupResult< component::StructDefOp > > getStructTarget(::mlir::SymbolTableCollection &tables)
Return the StructDefOp that this contract targets, or failure if it does not target a struct or the s...
::mlir::SymbolRefAttr getTargetAttr()
::mlir::SymbolRefAttr getCalleeAttr()
void setCalleeAttr(::mlir::SymbolRefAttr attr)
::mlir::FailureOr<::llzk::SymbolLookupResult<::llzk::verif::ContractOp > > getCalleeTarget(::mlir::SymbolTableCollection &tables)
Resolve and return the target Contract for this CallOp.
void setTemplateParamsAttr(::mlir::ArrayAttr attr)
component::StructType getStructTypeWithParams(mlir::SymbolRefAttr nameRef, mlir::ArrayAttr params)
Build a struct type while representing an empty parameter list as absent.
FailureOr< InstantiationLayout > buildInstantiationLayout(TemplateOp parentTemplate, ArrayAttr callParams, const DenseMap< Attribute, Attribute > ¶mNameToConcrete)
array::ArrayType flattenInstantiatedArrayType(array::ArrayType inputTy, mlir::Type convertedElemTy)
Merge nested array dimensions produced by replacing an array element type.
void setInstantiationNamePattern(TemplateOp templateOp, ArrayAttr namePattern)
constexpr char FUNC_NAME_COMPUTE[]
Symbol name for the witness generation (and resp.
mlir::SymbolRefAttr getPrefixAsSymbolRefAttr(mlir::SymbolRefAttr symbol)
Return SymbolRefAttr like the one given but with the leaf/final element removed.
mlir::FailureOr< SymbolLookupResultUntyped > lookupTopLevelSymbol(mlir::SymbolTableCollection &tables, mlir::SymbolRefAttr symbol, mlir::Operation *origin, bool reportMissing=true)
constexpr char FUNC_NAME_CONSTRAIN[]
mlir::DenseMap< std::pair< mlir::SymbolRefAttr, Side >, mlir::Attribute > UnificationMap
Optional result from type unifications.
bool isNullOrEmpty(mlir::ArrayAttr a)
OpClass getParentOfType(mlir::Operation *op)
Return the closest surrounding parent/ancestor operation that is of type 'OpClass'.
constexpr char FUNC_NAME_PRODUCT[]
constexpr T checkedCast(U u) noexcept
bool isDynamic(IntegerAttr intAttr)
mlir::SymbolRefAttr asSymbolRefAttr(mlir::StringAttr root, mlir::SymbolRefAttr tail)
Build a SymbolRefAttr that prepends tail with root, i.e., root::tail.
bool isTypeVarFreeType(Type type)
bool typeParamsUnify(const ArrayRef< Attribute > &lhsParams, const ArrayRef< Attribute > &rhsParams, UnificationMap *unifications)
bool isConcreteStructParamAttr(mlir::Attribute attr, bool allowStructParams=true)
Return true if attr is a concrete argument for a parameterized struct type.
bool hasParentThatIsa(mlir::Operation *op)
Return true if the parameter has a parent/ancestor op that is an instance of one of the template type...
llvm::SmallVector< FlatSymbolRefAttr > getPieces(SymbolRefAttr ref)
FailureOr< SymbolRefAttr > getPathFromRoot(SymbolOpInterface to, ModuleOp *foundRoot)
Groups the information needed after concrete parameters have been chosen to decide how to name a new ...
mlir::ArrayAttr namePattern
The refined literal chunks; fully concrete generated templates clear this state.
std::string templateNameWithAttrs
mlir::ArrayAttr rewrittenCallParams
mlir::SmallVector< mlir::Attribute > remainingNames