|
| 1 | +//===--- ExistentialGeneralization.cpp - Shape generalization algorithm ---===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | +// |
| 13 | +// This file defines the existential type generalization algorithm, |
| 14 | +// which is used in the ABI for existential types. |
| 15 | +// |
| 16 | +//===----------------------------------------------------------------------===// |
| 17 | + |
| 18 | +#include "GenericSignatureBuilder.h" |
| 19 | +#include "swift/AST/Types.h" |
| 20 | +#include "swift/AST/CanTypeVisitor.h" |
| 21 | +#include "llvm/ADT/DenseMap.h" |
| 22 | + |
| 23 | +using namespace swift; |
| 24 | + |
| 25 | +namespace { |
| 26 | + |
| 27 | +/// A helper type for performing existential type generalization. |
| 28 | +class Generalizer : public CanTypeVisitor<Generalizer, Type> { |
| 29 | + friend CanTypeVisitor<Generalizer, Type>; |
| 30 | + |
| 31 | + ASTContext &ctx; |
| 32 | + |
| 33 | + llvm::DenseMap<CanType, Type> substTypes; |
| 34 | + llvm::DenseMap<std::pair<CanType, ProtocolDecl*>, |
| 35 | + ProtocolConformanceRef> substConformances; |
| 36 | + |
| 37 | + Optional<GenericSignatureBuilder> sigBuilderStorage; |
| 38 | + |
| 39 | + GenericSignatureBuilder &sigBuilder() { |
| 40 | + if (!sigBuilderStorage) |
| 41 | + sigBuilderStorage.emplace(ctx); |
| 42 | + return *sigBuilderStorage; |
| 43 | + } |
| 44 | + |
| 45 | +public: |
| 46 | + Generalizer(ASTContext &ctx) : ctx(ctx) {} |
| 47 | + |
| 48 | + /// Given that the given type is not itself substitutable in whatever |
| 49 | + /// position it appears in, generalize it. |
| 50 | + Type generalizeStructure(CanType type) { |
| 51 | + return visit(type); |
| 52 | + } |
| 53 | + |
| 54 | + SubstitutionMap getGeneralizationSubstitutions() { |
| 55 | + // If we never introduced a generalization parameter, we're done. |
| 56 | + if (!sigBuilderStorage) return SubstitutionMap(); |
| 57 | + |
| 58 | + // Finish the signature. |
| 59 | + auto sig = std::move(*sigBuilderStorage).computeGenericSignature(); |
| 60 | + sigBuilderStorage.reset(); |
| 61 | + |
| 62 | + // TODO: minimize the signature by removing redundant generic |
| 63 | + // parameters. |
| 64 | + |
| 65 | + auto lookupParameter = [&](SubstitutableType *type) { |
| 66 | + auto it = substTypes.find(CanType(type)); |
| 67 | + assert(it != substTypes.end()); |
| 68 | + return it->second; |
| 69 | + }; |
| 70 | + auto lookupConformance = [&](CanType dependentType, |
| 71 | + Type conformingReplacementType, |
| 72 | + ProtocolDecl *conformedProtocol) { |
| 73 | + auto it = substConformances.find({dependentType, conformedProtocol}); |
| 74 | + assert(it != substConformances.end()); |
| 75 | + return it->second; |
| 76 | + }; |
| 77 | + return SubstitutionMap::get(sig, lookupParameter, lookupConformance); |
| 78 | + } |
| 79 | + |
| 80 | +private: |
| 81 | + Type visitProtocolType(CanProtocolType type) { |
| 82 | + // Simple protocol types have no sub-structure. |
| 83 | + assert(!type.getParent()); |
| 84 | + return type; |
| 85 | + } |
| 86 | + |
| 87 | + Type visitParameterizedProtocolType(CanParameterizedProtocolType origType) { |
| 88 | + // Generalize the argument types of parameterized protocols, |
| 89 | + // but don't generalize the base type. |
| 90 | + auto origArgs = origType.getArgs(); |
| 91 | + SmallVector<Type, 4> newArgs; |
| 92 | + newArgs.reserve(origArgs.size()); |
| 93 | + for (auto origArg: origArgs) { |
| 94 | + newArgs.push_back(generalizeComponentType(origArg)); |
| 95 | + } |
| 96 | + return ParameterizedProtocolType::get(ctx, origType->getBaseType(), |
| 97 | + newArgs); |
| 98 | + } |
| 99 | + |
| 100 | + Type visitProtocolCompositionType(CanProtocolCompositionType origType) { |
| 101 | + // The member types of protocol compositions are not substitutable, |
| 102 | + // including class constraints. Generalize them individually, |
| 103 | + // preserving structure. |
| 104 | + auto origMembers = origType.getMembers(); |
| 105 | + SmallVector<Type, 4> newMembers; |
| 106 | + newMembers.reserve(origMembers.size()); |
| 107 | + for (auto origMember: origMembers) { |
| 108 | + newMembers.push_back(generalizeStructure(origMember)); |
| 109 | + } |
| 110 | + return ProtocolCompositionType::get(ctx, newMembers, |
| 111 | + origType->hasExplicitAnyObject()); |
| 112 | + } |
| 113 | + |
| 114 | + // Generalize the type arguments of nominal types. |
| 115 | + Type visitBoundGenericType(CanBoundGenericType origType) { |
| 116 | + return generalizeGenericArguments(origType->getDecl(), origType); |
| 117 | + } |
| 118 | + Type visitNominalType(CanNominalType origType) { |
| 119 | + auto decl = origType->getDecl(); |
| 120 | + if (decl->isGenericContext()) |
| 121 | + return generalizeGenericArguments(decl, origType); |
| 122 | + return origType; |
| 123 | + } |
| 124 | + |
| 125 | + // Preserve existential structure. |
| 126 | + Type visitExistentialType(CanExistentialType origType) { |
| 127 | + return ExistentialType::get( |
| 128 | + generalizeStructure(origType.getConstraintType())); |
| 129 | + } |
| 130 | + Type visitExistentialMetatypeType(CanExistentialMetatypeType origType) { |
| 131 | + assert(!origType->hasRepresentation()); |
| 132 | + return ExistentialMetatypeType::get( |
| 133 | + generalizeStructure(origType.getInstanceType())); |
| 134 | + } |
| 135 | + |
| 136 | + // These types can be generalized by a recursive transform of |
| 137 | + // their component types; we don't need to exclude anything or |
| 138 | + // handle conformances. |
| 139 | +#define GENERALIZE_COMPONENTS(ID) \ |
| 140 | + Type visit##ID##Type(Can##ID##Type origType) { \ |
| 141 | + return generalizeComponentTypes(origType); \ |
| 142 | + } |
| 143 | + GENERALIZE_COMPONENTS(Function) |
| 144 | + GENERALIZE_COMPONENTS(Metatype) |
| 145 | + GENERALIZE_COMPONENTS(Tuple) |
| 146 | +#undef GENERALIZE_COMPONENTS |
| 147 | + |
| 148 | + // These types can never contain component types with abstract |
| 149 | + // constraints, so generalizeComponentType should always substitute |
| 150 | + // them out. |
| 151 | +#define NO_PRESERVABLE_STRUCTURE(ID) \ |
| 152 | + Type visit##ID##Type(Can##ID##Type origType) { \ |
| 153 | + llvm_unreachable(#ID "Type has no structure to preserve"); \ |
| 154 | + } |
| 155 | + NO_PRESERVABLE_STRUCTURE(Archetype) |
| 156 | + NO_PRESERVABLE_STRUCTURE(Builtin) |
| 157 | + NO_PRESERVABLE_STRUCTURE(DependentMember) |
| 158 | + NO_PRESERVABLE_STRUCTURE(GenericTypeParam) |
| 159 | + NO_PRESERVABLE_STRUCTURE(Module) |
| 160 | + NO_PRESERVABLE_STRUCTURE(Pack) |
| 161 | + NO_PRESERVABLE_STRUCTURE(PackExpansion) |
| 162 | +#undef NO_PRESERVABLE_STRUCTURE |
| 163 | + |
| 164 | + // These types simply shouldn't appear in types that we generalize at all. |
| 165 | +#define INVALID_TO_GENERALIZE(ID) \ |
| 166 | + Type visit##ID##Type(Can##ID##Type origType) { \ |
| 167 | + llvm_unreachable(#ID "type should not be found by generalization"); \ |
| 168 | + } |
| 169 | + INVALID_TO_GENERALIZE(DynamicSelf) |
| 170 | + INVALID_TO_GENERALIZE(Error) |
| 171 | + INVALID_TO_GENERALIZE(GenericFunction) |
| 172 | + INVALID_TO_GENERALIZE(InOut) |
| 173 | + INVALID_TO_GENERALIZE(LValue) |
| 174 | + INVALID_TO_GENERALIZE(ReferenceStorage) |
| 175 | + INVALID_TO_GENERALIZE(SILBlockStorage) |
| 176 | + INVALID_TO_GENERALIZE(SILBox) |
| 177 | + INVALID_TO_GENERALIZE(SILFunction) |
| 178 | + INVALID_TO_GENERALIZE(SILToken) |
| 179 | +#undef INVALID_TO_GENERALIZE |
| 180 | + |
| 181 | + /// Generalize the generic arguments of the given generic type.s |
| 182 | + Type generalizeGenericArguments(NominalTypeDecl *decl, CanType type) { |
| 183 | + assert(decl->isGenericContext()); |
| 184 | + auto origSubs = type->getContextSubstitutionMap(decl->getModuleContext(), |
| 185 | + decl); |
| 186 | + |
| 187 | + // Generalize all of the arguments. |
| 188 | + auto origArgs = origSubs.getReplacementTypes(); |
| 189 | + SmallVector<Type, 4> newArgs; |
| 190 | + for (auto origArg: origArgs) { |
| 191 | + newArgs.push_back(generalizeComponentType(CanType(origArg))); |
| 192 | + } |
| 193 | + |
| 194 | + // Generalize all of the conformances. |
| 195 | + // TODO: for abstract requirements, we might not generalize all |
| 196 | + // arguments, and we may need to leave corresponding conformances |
| 197 | + // concrete. |
| 198 | + SmallVector<ProtocolConformanceRef, 4> newConformances; |
| 199 | + auto origConformances = origSubs.getConformances(); |
| 200 | + for (auto origConformance: origConformances) { |
| 201 | + newConformances.push_back( |
| 202 | + ProtocolConformanceRef(origConformance.getRequirement())); |
| 203 | + } |
| 204 | + |
| 205 | + auto origSig = origSubs.getGenericSignature(); |
| 206 | + auto newSubs = SubstitutionMap::get(origSig, newArgs, newConformances); |
| 207 | + |
| 208 | + // Add any conformance requirements to the generic signature and |
| 209 | + // remember the conformances we generalized. |
| 210 | + if (!origConformances.empty()) { |
| 211 | + size_t i = 0; |
| 212 | + for (auto &origReq: origSig.getRequirements()) { |
| 213 | + if (origReq.getKind() != RequirementKind::Conformance) continue; |
| 214 | + auto origConformance = origConformances[i++]; |
| 215 | + |
| 216 | + auto optNewReq = origReq.subst(newSubs); |
| 217 | + assert(optNewReq && "generalization substitution failed"); |
| 218 | + auto &newReq = *optNewReq; |
| 219 | + |
| 220 | + auto source = GenericSignatureBuilder:: |
| 221 | + FloatingRequirementSource::forInferred(SourceLoc()); |
| 222 | + |
| 223 | + sigBuilder().addRequirement(newReq, source, nullptr); |
| 224 | + |
| 225 | + substConformances.insert({{newReq.getFirstType()->getCanonicalType(), |
| 226 | + newReq.getProtocolDecl()}, |
| 227 | + origConformance}); |
| 228 | + } |
| 229 | + } |
| 230 | + |
| 231 | + // Build the new type. |
| 232 | + return decl->getDeclaredInterfaceType().subst(newSubs); |
| 233 | + } |
| 234 | + |
| 235 | + /// Generalize the given type by preserving its top-level strcture |
| 236 | + /// but generalizing its component types. |
| 237 | + Type generalizeComponentTypes(CanType type) { |
| 238 | + return type.transformRec([&](TypeBase *componentType) -> Optional<Type> { |
| 239 | + // Ignore the top level. |
| 240 | + if (componentType == type.getPointer()) |
| 241 | + return None; |
| 242 | + |
| 243 | + return generalizeComponentType(CanType(componentType)); |
| 244 | + }); |
| 245 | + } |
| 246 | + |
| 247 | + Type generalizeComponentType(CanType origArg) { |
| 248 | + // TODO: Abstract constraints (some P) introduce *existential* |
| 249 | + // component types, which are not substitutable. Therefore, types |
| 250 | + // containing them must be generalized preserving that structure |
| 251 | + // rather than wholly substituted. They can appear in arbitrary |
| 252 | + // positions, including within tuple, function, and metatype types, |
| 253 | + // so we'll need to add cases for those to generalizeStructure |
| 254 | + // above. |
| 255 | + |
| 256 | + // Create a new generalization type parameter and record the |
| 257 | + // substitution. |
| 258 | + auto newParam = GenericTypeParamType::get(/*sequence*/ false, |
| 259 | + /*depth*/ 0, |
| 260 | + /*index*/ substTypes.size(), |
| 261 | + ctx); |
| 262 | + sigBuilder().addGenericParameter(newParam); |
| 263 | + substTypes.insert({CanType(newParam), origArg}); |
| 264 | + return newParam; |
| 265 | + } |
| 266 | +}; |
| 267 | + |
| 268 | +} // end anonymous namespace |
| 269 | + |
| 270 | +ExistentialTypeGeneralization |
| 271 | +ExistentialTypeGeneralization::get(Type rawType) { |
| 272 | + assert(rawType->isExistentialType()); |
| 273 | + assert(!rawType->hasTypeParameter()); |
| 274 | + |
| 275 | + // Canonicalize. We need to generalize the canonical shape of the |
| 276 | + // type or else generalization parameters won't match up. |
| 277 | + CanType type = rawType->getCanonicalType(); |
| 278 | + |
| 279 | + Generalizer generalizer(type->getASTContext()); |
| 280 | + Type shape = generalizer.generalizeStructure(type); |
| 281 | + auto subs = generalizer.getGeneralizationSubstitutions(); |
| 282 | + |
| 283 | + return {shape, subs}; |
| 284 | +} |
0 commit comments