@@ -1781,6 +1781,37 @@ static DynamicCastResult tryCastToExtendedExistential(
17811781 auto *destExistentialShape = destExistentialType->Shape ;
17821782 const unsigned shapeArgumentCount =
17831783 destExistentialShape->getGenSigArgumentLayoutSizeInWords ();
1784+ const Metadata *selfType = srcType;
1785+
1786+ // If we have a type expression to look into, unwrap as much metatype
1787+ // structure as possible so we can reach the type metadata for the 'Self'
1788+ // parameter.
1789+ if (destExistentialShape->Flags .hasTypeExpression ()) {
1790+ Demangler dem;
1791+ auto *node = dem.demangleType (destExistentialShape->getTypeExpression ()->name .get ());
1792+ if (!node)
1793+ return DynamicCastResult::Failure;
1794+
1795+ while (node->getKind () == Demangle::Node::Kind::Type &&
1796+ node->getNumChildren () &&
1797+ node->getChild (0 )->getKind () == Demangle::Node::Kind::Metatype &&
1798+ node->getChild (0 )->getNumChildren ()) {
1799+ auto *metatypeMetadata = dyn_cast<MetatypeMetadata>(selfType);
1800+ if (!metatypeMetadata)
1801+ return DynamicCastResult::Failure;
1802+
1803+ selfType = metatypeMetadata->InstanceType ;
1804+ node = node->getChild (0 )->getChild (0 );
1805+ }
1806+
1807+ // Make sure the thing we've pulled out at the end is a dependent
1808+ // generic parameter.
1809+ if (!(node->getKind () == Demangle::Node::Kind::Type &&
1810+ node->getNumChildren () &&
1811+ node->getChild (0 )->getKind () ==
1812+ Demangle::Node::Kind::DependentGenericParamType))
1813+ return DynamicCastResult::Failure;
1814+ }
17841815
17851816 llvm::SmallVector<const void *, 8 > allGenericArgsVec;
17861817 unsigned witnessesMark = 0 ;
@@ -1789,7 +1820,7 @@ static DynamicCastResult tryCastToExtendedExistential(
17891820 auto genArgs = destExistentialType->getGeneralizationArguments ();
17901821 allGenericArgsVec.append (genArgs, genArgs + shapeArgumentCount);
17911822 // Tack on the `Self` argument.
1792- allGenericArgsVec.push_back ((const void *)srcType );
1823+ allGenericArgsVec.push_back ((const void *)selfType );
17931824 // Mark the point where the generic arguments end.
17941825 // _checkGenericRequirements is going to fill in a set of witness tables
17951826 // after that.
0 commit comments