@@ -445,6 +445,28 @@ std::string ASTMangler::mangleSILDifferentiabilityWitnessKey(
445445 return result;
446446}
447447
448+ // In order for the remangler to work correctly, it must agree with
449+ // AST mangler on the substitution scheme. The AST mangler will use a
450+ // substitution if a mangled type is identical to a previous type.
451+ //
452+ // In the DWARF mangling, we don't canonicalize types. Therefore, any
453+ // two types that differ by sugar must have distinct manglings. If this
454+ // invariant is not maintained, then demangling and remangling a type
455+ // will no longer be idempotent.
456+ //
457+ // Since we don't have a distinct mangling for sugared generic
458+ // parameter types, we must desugar them here.
459+ static Type getTypeForDWARFMangling (Type t) {
460+ return t.subst (
461+ [](SubstitutableType *t) -> Type {
462+ if (isa<GenericTypeParamType>(t))
463+ return t->getCanonicalType ();
464+ return t;
465+ },
466+ MakeAbstractConformanceForGenericType (),
467+ SubstFlags::AllowLoweredTypes);
468+ }
469+
448470std::string ASTMangler::mangleTypeForDebugger (Type Ty, const DeclContext *DC) {
449471 PrettyStackTraceType prettyStackTrace (Ty->getASTContext (),
450472 " mangling type for debugger" , Ty);
@@ -453,6 +475,8 @@ std::string ASTMangler::mangleTypeForDebugger(Type Ty, const DeclContext *DC) {
453475 OptimizeProtocolNames = false ;
454476 beginMangling ();
455477
478+ Ty = getTypeForDWARFMangling (Ty);
479+
456480 if (DC)
457481 bindGenericParameters (DC);
458482
@@ -552,7 +576,9 @@ std::string ASTMangler::mangleTypeAsContextUSR(const NominalTypeDecl *type) {
552576std::string ASTMangler::mangleTypeAsUSR (Type Ty) {
553577 DWARFMangling = true ;
554578 beginMangling ();
555-
579+
580+ Ty = getTypeForDWARFMangling (Ty);
581+
556582 if (auto *fnType = Ty->getAs <AnyFunctionType>()) {
557583 appendFunction (fnType, false );
558584 } else {
@@ -1130,6 +1156,10 @@ void ASTMangler::appendType(Type type, const ValueDecl *forDecl) {
11301156
11311157 case TypeKind::GenericTypeParam: {
11321158 auto paramTy = cast<GenericTypeParamType>(tybase);
1159+ // If this assertion fires, it probably means the type being mangled here
1160+ // didn't go through getTypeForDWARFMangling().
1161+ assert (paramTy->getDecl () == nullptr &&
1162+ " cannot mangle non-canonical generic parameter" );
11331163 // A special mangling for the very first generic parameter. This shows up
11341164 // frequently because it corresponds to 'Self' in protocol requirement
11351165 // generic signatures.
0 commit comments