1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
|
//===--- SILTypeSubstitution.cpp - Apply substitutions to SIL types -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the core operations that apply substitutions to
// the lowered types used for SIL values.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "libsil"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/AST/InFlightSubstitution.h"
#include "swift/AST/PackConformance.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/CanTypeVisitor.h"
using namespace swift;
using namespace Lowering;
namespace {
/// Given a lowered SIL type, apply a substitution to it to produce another
/// lowered SIL type which uses the same abstraction conventions.
class SILTypeSubstituter :
public CanTypeVisitor<SILTypeSubstituter, CanType> {
TypeConverter &TC;
InFlightSubstitution &IFS;
// The signature for the original type.
//
// Replacement types are lowered with respect to the current
// context signature.
CanGenericSignature Sig;
TypeExpansionContext typeExpansionContext;
public:
SILTypeSubstituter(TypeConverter &TC,
TypeExpansionContext context,
InFlightSubstitution &IFS,
CanGenericSignature Sig)
: TC(TC),
IFS(IFS),
Sig(Sig),
typeExpansionContext(context)
{}
// SIL type lowering only does special things to tuples and functions.
// When a function appears inside of another type, we only perform
// substitutions if it is not polymorphic.
CanSILFunctionType visitSILFunctionType(CanSILFunctionType origType) {
return substSILFunctionType(origType, false);
}
SubstitutionMap substOpaqueTypes(SubstitutionMap subs) {
if (!typeExpansionContext.shouldLookThroughOpaqueTypeArchetypes())
return subs;
return subs.subst([&](SubstitutableType *s) -> Type {
return substOpaqueTypesWithUnderlyingTypes(s->getCanonicalType(),
typeExpansionContext);
}, [&](CanType dependentType,
Type conformingReplacementType,
ProtocolDecl *conformedProtocol) -> ProtocolConformanceRef {
return substOpaqueTypesWithUnderlyingTypes(
ProtocolConformanceRef(conformedProtocol),
conformingReplacementType->getCanonicalType(),
typeExpansionContext);
},
SubstFlags::SubstituteOpaqueArchetypes |
SubstFlags::PreservePackExpansionLevel);
}
// Substitute a function type.
CanSILFunctionType substSILFunctionType(CanSILFunctionType origType,
bool isGenericApplication) {
assert((!isGenericApplication || origType->isPolymorphic()) &&
"generic application without invocation signature or with "
"existing arguments");
assert((!isGenericApplication || !IFS.shouldSubstituteOpaqueArchetypes()) &&
"generic application while substituting opaque archetypes");
// The general substitution rule is that we should only substitute
// into the free components of the type, i.e. the components that
// aren't inside a generic signature. That rule would say:
//
// - If there are invocation substitutions, just substitute those;
// the other components are necessarily inside the invocation
// generic signature.
//
// - Otherwise, if there's an invocation generic signature,
// substitute nothing. If we are applying generic arguments,
// add the appropriate invocation substitutions.
//
// - Otherwise, if there are pattern substitutions, just substitute
// those; the other components are inside the pattern generic
// signature.
//
// - Otherwise, substitute the basic components.
//
// There are two caveats here. The first is that we haven't yet
// written all the code that would be necessary in order to handle
// invocation substitutions everywhere, and so we never build those.
// Instead, we substitute into the pattern substitutions if present,
// or the components if not, and build a type with no invocation
// signature. As a special case, when substituting a coroutine type,
// we build pattern substitutions instead of substituting the
// component types in order to preserve the original yield structure,
// which factors into the continuation function ABI.
//
// The second is that this function is also used when substituting
// opaque archetypes. In this case, we may need to substitute
// into component types even within generic signatures. This is
// safe because the substitutions used in this case don't change
// generics, they just narrowly look through certain opaque archetypes.
// If substitutions are present, we still don't substitute into
// the basic components, in order to maintain the information about
// what was abstracted there.
auto patternSubs = origType->getPatternSubstitutions();
// If we have an invocation signature, we generally shouldn't
// substitute into the pattern substitutions and component types.
if (auto sig = origType->getInvocationGenericSignature()) {
// Substitute the invocation substitutions if present.
if (auto invocationSubs = origType->getInvocationSubstitutions()) {
assert(!isGenericApplication);
invocationSubs = substSubstitutions(invocationSubs);
auto substType =
origType->withInvocationSubstitutions(invocationSubs);
// Also do opaque-type substitutions on the pattern substitutions
// if requested and applicable.
if (patternSubs) {
patternSubs = substOpaqueTypes(patternSubs);
substType = substType->withPatternSubstitutions(patternSubs);
}
return substType;
}
// Otherwise, we shouldn't substitute any components except
// when substituting opaque archetypes.
// If we're doing a generic application, and there are pattern
// substitutions, substitute into the pattern substitutions; or if
// it's a coroutine, build pattern substitutions; or else, fall
// through to substitute the component types as discussed above.
if (isGenericApplication) {
if (patternSubs || origType->isCoroutine()) {
CanSILFunctionType substType = origType;
if (typeExpansionContext.shouldLookThroughOpaqueTypeArchetypes()) {
substType =
origType->substituteOpaqueArchetypes(TC, typeExpansionContext);
}
SubstitutionMap subs;
if (patternSubs) {
subs = substSubstitutions(patternSubs);
} else {
subs = SubstitutionMap::get(sig, IFS);
}
auto witnessConformance = substWitnessConformance(origType);
substType = substType->withPatternSpecialization(nullptr, subs,
witnessConformance);
if (typeExpansionContext.shouldLookThroughOpaqueTypeArchetypes()) {
substType =
substType->substituteOpaqueArchetypes(TC, typeExpansionContext);
}
return substType;
}
// else fall down to component substitution
// If we're substituting opaque archetypes, and there are pattern
// substitutions present, just substitute those and preserve the
// basic structure in the component types. Otherwise, fall through
// to substitute the component types.
} else if (IFS.shouldSubstituteOpaqueArchetypes()) {
if (patternSubs) {
patternSubs = substOpaqueTypes(patternSubs);
auto witnessConformance = substWitnessConformance(origType);
return origType->withPatternSpecialization(sig, patternSubs,
witnessConformance);
}
// else fall down to component substitution
// Otherwise, don't try to substitute bound components.
} else {
auto substType = origType;
if (patternSubs) {
patternSubs = substOpaqueTypes(patternSubs);
auto witnessConformance = substWitnessConformance(origType);
substType = substType->withPatternSpecialization(sig, patternSubs,
witnessConformance);
}
return substType;
}
// Otherwise, if there are pattern substitutions, just substitute
// into those and don't touch the component types.
} else if (patternSubs) {
patternSubs = substSubstitutions(patternSubs);
auto witnessConformance = substWitnessConformance(origType);
return origType->withPatternSpecialization(nullptr, patternSubs,
witnessConformance);
}
// Otherwise, we need to substitute component types.
SmallVector<SILResultInfo, 8> substResults;
substResults.reserve(origType->getNumResults());
for (auto origResult : origType->getResults()) {
substResults.push_back(substInterface(origResult));
}
auto substErrorResult = origType->getOptionalErrorResult();
if (substErrorResult)
substErrorResult = substInterface(*substErrorResult);
SmallVector<SILParameterInfo, 8> substParams;
substParams.reserve(origType->getParameters().size());
for (auto &origParam : origType->getParameters()) {
substParams.push_back(substInterface(origParam));
}
SmallVector<SILYieldInfo, 8> substYields;
substYields.reserve(origType->getYields().size());
for (auto &origYield : origType->getYields()) {
substYields.push_back(substInterface(origYield));
}
auto witnessMethodConformance = substWitnessConformance(origType);
// The substituted type is no longer generic, so it'd never be
// pseudogeneric.
auto extInfo = origType->getExtInfo();
if (!IFS.shouldSubstituteOpaqueArchetypes())
extInfo = extInfo.intoBuilder().withIsPseudogeneric(false).build();
auto genericSig = IFS.shouldSubstituteOpaqueArchetypes()
? origType->getInvocationGenericSignature()
: nullptr;
return SILFunctionType::get(genericSig, extInfo,
origType->getCoroutineKind(),
origType->getCalleeConvention(), substParams,
substYields, substResults, substErrorResult,
SubstitutionMap(), SubstitutionMap(),
TC.Context, witnessMethodConformance);
}
ProtocolConformanceRef substWitnessConformance(CanSILFunctionType origType) {
auto conformance = origType->getWitnessMethodConformanceOrInvalid();
if (!conformance) return conformance;
assert(origType->getExtInfo().hasSelfParam());
auto selfType = origType->getSelfParameter().getInterfaceType();
// The Self type can be nested in a few layers of metatypes (etc.).
while (auto metatypeType = dyn_cast<MetatypeType>(selfType)) {
auto next = metatypeType.getInstanceType();
if (next == selfType)
break;
selfType = next;
}
auto substConformance = conformance.subst(selfType, IFS);
// Substitute the underlying conformance of opaque type archetypes if we
// should look through opaque archetypes.
if (typeExpansionContext.shouldLookThroughOpaqueTypeArchetypes()) {
auto substType = IFS.withNewOptions(std::nullopt, [&] {
return selfType.subst(IFS)->getCanonicalType();
});
if (substType->hasOpaqueArchetype()) {
substConformance = substOpaqueTypesWithUnderlyingTypes(
substConformance, substType, typeExpansionContext);
}
}
return substConformance;
}
SILType subst(SILType type) {
return SILType::getPrimitiveType(visit(type.getRawASTType()),
type.getCategory());
}
SILResultInfo substInterface(SILResultInfo orig) {
return SILResultInfo(visit(orig.getInterfaceType()), orig.getConvention(),
orig.getOptions());
}
SILYieldInfo substInterface(SILYieldInfo orig) {
return SILYieldInfo(visit(orig.getInterfaceType()), orig.getConvention());
}
SILParameterInfo substInterface(SILParameterInfo orig) {
return SILParameterInfo(visit(orig.getInterfaceType()),
orig.getConvention(), orig.getOptions());
}
CanType visitSILPackType(CanSILPackType origType) {
// Fast-path the empty pack.
if (origType->getNumElements() == 0) return origType;
SmallVector<CanType, 8> substEltTypes;
substEltTypes.reserve(origType->getNumElements());
for (CanType origEltType : origType->getElementTypes()) {
if (auto origExpansionType = dyn_cast<PackExpansionType>(origEltType)) {
substPackExpansion(origExpansionType, [&](CanType substExpandedType) {
substEltTypes.push_back(substExpandedType);
});
} else {
auto substEltType = visit(origEltType);
substEltTypes.push_back(substEltType);
}
}
return SILPackType::get(TC.Context, origType->getExtInfo(), substEltTypes);
}
CanType visitPackType(CanPackType origType) {
llvm_unreachable("CanPackType shouldn't show in lowered types");
}
/* FIXME: Uncomment this once SubstFlags::PreservePackExpansionLevel is gone */
#if 0
CanType visitPackExpansionType(CanPackExpansionType origType) {
llvm_unreachable("shouldn't substitute an independent lowered pack "
"expansion type");
}
#endif
void substPackExpansion(CanPackExpansionType origType,
llvm::function_ref<void(CanType)> addExpandedType) {
IFS.expandPackExpansionShape(origType.getCountType(),
[&](Type substExpansionShape) {
CanType substComponentType = visit(origType.getPatternType());
if (substExpansionShape) {
if (auto packArchetype = substExpansionShape->getAs<PackArchetypeType>())
substExpansionShape = packArchetype->getReducedShape();
substComponentType = CanPackExpansionType::get(substComponentType,
substExpansionShape->getCanonicalType());
}
addExpandedType(substComponentType);
});
}
/// Tuples need to have their component types substituted by these
/// same rules.
CanType visitTupleType(CanTupleType origType) {
// Fast-path the empty tuple.
if (origType->getNumElements() == 0) return origType;
SmallVector<TupleTypeElt, 8> substElts;
substElts.reserve(origType->getNumElements());
for (auto &origElt : origType->getElements()) {
CanType origEltType = CanType(origElt.getType());
if (auto origExpansion = dyn_cast<PackExpansionType>(origEltType)) {
bool first = true;
substPackExpansion(origExpansion, [&](CanType substEltType) {
auto substElt = origElt.getWithType(substEltType);
if (first) {
first = false;
} else {
substElt = substElt.getWithoutName();
}
substElts.push_back(substElt);
});
} else {
auto substEltType = visit(origEltType);
substElts.push_back(origElt.getWithType(substEltType));
}
}
// Turn unlabeled singleton scalar tuples into their underlying types.
// The AST type substituter doesn't actually implement this rule yet,
// but we need to implement it in SIL in order to support testing,
// since the type parser can't parse a singleton tuple.
//
// For compatibility with previous behavior, don't do this if the
// original tuple type was singleton. AutoDiff apparently really
// likes making singleton tuples.
if (isParenType(substElts) && !isParenType(origType->getElements()))
return CanType(substElts[0].getType());
return CanType(TupleType::get(substElts, TC.Context));
}
static bool isParenType(ArrayRef<TupleTypeElt> elts) {
return (elts.size() == 1 &&
!elts[0].hasName() &&
!isa<PackExpansionType>(CanType(elts[0].getType())));
}
// Block storage types need to substitute their capture type by these same
// rules.
CanType visitSILBlockStorageType(CanSILBlockStorageType origType) {
auto substCaptureType = visit(origType->getCaptureType());
return SILBlockStorageType::get(substCaptureType);
}
/// Optionals need to have their object types substituted by these rules.
CanType visitBoundGenericEnumType(CanBoundGenericEnumType origType) {
// Only use a special rule if it's Optional.
if (!origType->getDecl()->isOptionalDecl()) {
return visitType(origType);
}
CanType origObjectType = origType.getGenericArgs()[0];
CanType substObjectType = visit(origObjectType);
return CanType(BoundGenericType::get(origType->getDecl(), Type(),
substObjectType));
}
/// Any other type would be a valid type in the AST. Just apply the
/// substitution on the AST level and then lower that.
CanType visitType(CanType origType) {
assert(!isa<AnyFunctionType>(origType));
assert(!isa<LValueType>(origType) && !isa<InOutType>(origType));
CanType substType = substASTType(origType);
// If the substitution didn't change anything, we know that the
// original type was a lowered type, so we're good.
if (origType == substType) {
return origType;
}
// We've looked through all the top-level structure in the orig
// type that's affected by type lowering. If substitution has
// given us a type with top-level structure that's affected by
// type lowering, it must be because the orig type was a type
// variable of some sort, and we should lower using an opaque
// abstraction pattern. If substitution hasn't given us such a
// type, it doesn't matter what abstraction pattern we use,
// lowering will just come back with substType. So we can just
// use an opaque abstraction pattern here and not put any effort
// into computing a more "honest" abstraction pattern.
AbstractionPattern abstraction = AbstractionPattern::getOpaque();
return TC.getLoweredRValueType(typeExpansionContext, abstraction,
substType);
}
CanType substASTType(CanType origType) {
return origType.subst(IFS)->getCanonicalType();
}
SubstitutionMap substSubstitutions(SubstitutionMap subs) {
SubstitutionMap newSubs = subs.subst(IFS);
// If we need to look through opaque types in this context, re-substitute
// according to the expansion context.
newSubs = substOpaqueTypes(newSubs);
return newSubs;
}
};
} // end anonymous namespace
static bool isSubstitutionInvariant(SILType ty, SubstOptions options) {
return (!ty.hasArchetype() &&
!ty.hasTypeParameter() &&
(!options.contains(SubstFlags::SubstituteOpaqueArchetypes) ||
!ty.getRawASTType()->hasOpaqueArchetype()));
}
SILType SILType::subst(TypeConverter &tc, TypeSubstitutionFn subs,
LookupConformanceFn conformances,
CanGenericSignature genericSig,
SubstOptions options) const {
if (isSubstitutionInvariant(*this, options))
return *this;
InFlightSubstitution IFS(subs, conformances, options);
SILTypeSubstituter STST(tc, TypeExpansionContext::minimal(), IFS,
genericSig);
return STST.subst(*this);
}
SILType SILType::subst(TypeConverter &tc, InFlightSubstitution &IFS,
CanGenericSignature genericSig) const {
if (isSubstitutionInvariant(*this, IFS.getOptions()))
return *this;
SILTypeSubstituter STST(tc, TypeExpansionContext::minimal(), IFS,
genericSig);
return STST.subst(*this);
}
SILType SILType::subst(SILModule &M, TypeSubstitutionFn subs,
LookupConformanceFn conformances,
CanGenericSignature genericSig,
SubstOptions options) const {
return subst(M.Types, subs, conformances, genericSig, options);
}
SILType SILType::subst(TypeConverter &tc, SubstitutionMap subs) const {
auto sig = subs.getGenericSignature();
InFlightSubstitutionViaSubMap IFS(subs, std::nullopt);
return subst(tc, IFS, sig.getCanonicalSignature());
}
SILType SILType::subst(SILModule &M, SubstitutionMap subs) const{
return subst(M.Types, subs);
}
SILType SILType::subst(SILModule &M, SubstitutionMap subs,
TypeExpansionContext context) const {
if (isSubstitutionInvariant(*this, std::nullopt))
return *this;
InFlightSubstitutionViaSubMap IFS(subs, std::nullopt);
SILTypeSubstituter STST(M.Types, context, IFS,
subs.getGenericSignature().getCanonicalSignature());
return STST.subst(*this);
}
/// Apply a substitution to this polymorphic SILFunctionType so that
/// it has the form of the normal SILFunctionType for the substituted
/// type, except using the original conventions.
CanSILFunctionType
SILFunctionType::substGenericArgs(SILModule &silModule, SubstitutionMap subs,
TypeExpansionContext context) {
if (!isPolymorphic()) {
return CanSILFunctionType(this);
}
if (subs.empty()) {
return CanSILFunctionType(this);
}
InFlightSubstitutionViaSubMap IFS(subs, std::nullopt);
return substGenericArgs(silModule, IFS, context);
}
CanSILFunctionType
SILFunctionType::substGenericArgs(SILModule &silModule,
TypeSubstitutionFn subs,
LookupConformanceFn conformances,
TypeExpansionContext context) {
if (!isPolymorphic()) return CanSILFunctionType(this);
InFlightSubstitution IFS(subs, conformances, std::nullopt);
return substGenericArgs(silModule, IFS, context);
}
CanSILFunctionType
SILFunctionType::substGenericArgs(SILModule &silModule,
InFlightSubstitution &IFS,
TypeExpansionContext context) {
if (!isPolymorphic()) return CanSILFunctionType(this);
SILTypeSubstituter substituter(silModule.Types, context, IFS,
getSubstGenericSignature());
return substituter.substSILFunctionType(CanSILFunctionType(this), true);
}
CanSILFunctionType
SILFunctionType::substituteOpaqueArchetypes(TypeConverter &TC,
TypeExpansionContext context) {
if (!hasOpaqueArchetype() ||
!context.shouldLookThroughOpaqueTypeArchetypes())
return CanSILFunctionType(this);
ReplaceOpaqueTypesWithUnderlyingTypes replacer(
context.getContext(), context.getResilienceExpansion(),
context.isWholeModuleContext());
InFlightSubstitution IFS(replacer, replacer,
SubstFlags::SubstituteOpaqueArchetypes |
SubstFlags::PreservePackExpansionLevel);
SILTypeSubstituter substituter(TC, context, IFS, getSubstGenericSignature());
auto resTy =
substituter.substSILFunctionType(CanSILFunctionType(this), false);
return resTy;
}
|