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 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
|
//===--- SILGenDistributed.cpp - SILGen for distributed -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 - 2021 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
//
//===----------------------------------------------------------------------===//
#include "ArgumentSource.h"
#include "Conversion.h"
#include "ExecutorBreadcrumb.h"
#include "Initialization.h"
#include "LValue.h"
#include "RValue.h"
#include "SILGenFunction.h"
#include "SILGenFunctionBuilder.h"
#include "Scope.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/DistributedDecl.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/ProtocolConformanceRef.h"
#include "swift/Basic/Defer.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/SILOptimizer/Utils/DistributedActor.h"
using namespace swift;
using namespace Lowering;
// MARK: utility functions
/// Emit a reference to a specific stored property of the actor.
static SILValue emitActorPropertyReference(
SILGenFunction &SGF, SILLocation loc, SILValue actorSelf,
VarDecl *property) {
assert(property);
Type formalType = SGF.F.mapTypeIntoContext(property->getInterfaceType());
SILType loweredType = SGF.getLoweredType(formalType).getAddressType();
return SGF.B.createRefElementAddr(loc, actorSelf, property, loweredType);
}
/// Perform an initializing store to the given property using the value
/// \param actorSelf the value representing `self` for the actor instance.
/// \param prop the property to be initialized.
/// \param value the value to use when initializing the property.
static void initializeProperty(SILGenFunction &SGF, SILLocation loc,
SILValue actorSelf,
VarDecl* prop, SILValue value,
IsTake_t isTake) {
Type formalType = SGF.F.mapTypeIntoContext(prop->getInterfaceType());
SILType loweredType = SGF.getLoweredType(formalType);
auto fieldAddr = emitActorPropertyReference(SGF, loc, actorSelf, prop);
if (loweredType.isAddressOnly(SGF.F)) {
SGF.B.createCopyAddr(loc, value, fieldAddr, isTake, IsInitialization);
} else {
if (value->getType().isAddress()) {
SGF.emitSemanticLoadInto(loc, value, SGF.F.getTypeLowering(value->getType()),
fieldAddr, SGF.getTypeLowering(loweredType), isTake, IsInitialization);
} else {
value = SGF.B.emitCopyValueOperation(loc, value);
SGF.B.emitStoreValueOperation(
loc, value, fieldAddr, StoreOwnershipQualifier::Init);
}
}
}
/******************************************************************************/
/******************* COMMON (DISTRIBUTED) SIL PATTERNS ************************/
/******************************************************************************/
/// Emit the following branch SIL instruction:
/// \verbatim
/// if __isRemoteActor(self) {
/// <isRemoteBB>
/// } else {
/// <isLocalBB>
/// }
/// \endverbatim
void SILGenFunction::emitDistributedIfRemoteBranch(SILLocation Loc,
ManagedValue selfValue,
Type selfTy,
SILBasicBlock *isRemoteBB,
SILBasicBlock *isLocalBB) {
ASTContext &ctx = getASTContext();
FuncDecl *isRemoteFn = ctx.getIsRemoteDistributedActor();
assert(isRemoteFn && "Could not find 'is remote' function, is the "
"'Distributed' module available?");
auto conformances = SGM.M.getSwiftModule()->collectExistentialConformances(
selfTy->getCanonicalType(), ctx.getAnyObjectType());
ManagedValue selfAnyObject = B.createInitExistentialRef(
Loc,
/*existentialType=*/getLoweredType(ctx.getAnyObjectType()),
/*formalConcreteType=*/selfTy->getCanonicalType(),
selfValue, conformances);
auto result = emitApplyOfLibraryIntrinsic(
Loc, isRemoteFn, SubstitutionMap(), {selfAnyObject}, SGFContext());
SILValue isRemoteResult = std::move(result).forwardAsSingleValue(*this, Loc);
SILValue isRemoteResultUnwrapped =
emitUnwrapIntegerResult(Loc, isRemoteResult);
B.createCondBranch(Loc, isRemoteResultUnwrapped, isRemoteBB, isLocalBB);
}
// ==== ------------------------------------------------------------------------
// MARK: local instance initialization
static SILArgument *findFirstDistributedActorSystemArg(SILFunction &F) {
auto *module = F.getModule().getSwiftModule();
auto &C = F.getASTContext();
auto *DAS = C.getDistributedActorSystemDecl();
Type systemTy = DAS->getDeclaredInterfaceType();
for (auto arg : F.getArguments()) {
// TODO(distributed): also be able to locate a generic system
Type argTy = arg->getType().getASTType();
auto argDecl = arg->getDecl();
auto conformsToSystem =
module->lookupConformance(argDecl->getInterfaceType(), DAS);
// Is it a protocol that conforms to DistributedActorSystem?
if (argTy->isEqual(systemTy) || conformsToSystem) {
return arg;
}
// Is it some specific DistributedActorSystem?
auto result = module->lookupConformance(argTy, DAS);
if (!result.isInvalid()) {
return arg;
}
}
#ifndef NDEBUG
llvm_unreachable("Missing required DistributedActorSystem argument!");
#endif
return nullptr;
}
/// For the initialization of a local distributed actor instance, emits code to
/// initialize the instance's stored property corresponding to the system.
static void emitActorSystemInit(SILGenFunction &SGF,
ConstructorDecl *ctor,
SILLocation loc,
ManagedValue actorSelf,
SILValue systemValue) {
assert(ctor->isImplicit() && "unexpected explicit dist actor init");
assert(ctor->isDesignatedInit());
auto *dc = ctor->getDeclContext();
auto classDecl = dc->getSelfClassDecl();
// By construction, automatically generated distributed actor ctors have
// exactly one ActorSystem-conforming argument to the constructor,
// so we grab the first one from the params.
VarDecl *var = classDecl->getDistributedActorSystemProperty();
initializeProperty(SGF, loc, actorSelf.getValue(), var, systemValue, IsNotTake);
}
/// Emits the distributed actor's identity (`id`) initialization.
///
/// Specifically, it performs:
/// \verbatim
/// self.id = system.assignID(Self.self)
/// \endverbatim
void SILGenFunction::emitDistActorIdentityInit(ConstructorDecl *ctor,
SILLocation loc,
SILValue borrowedSelfArg,
SILValue actorSystem) {
assert(ctor->isDesignatedInit());
auto &C = ctor->getASTContext();
auto *dc = ctor->getDeclContext();
auto classDecl = dc->getSelfClassDecl();
assert(classDecl->isDistributedActor());
// --- prepare `Self.self` metatype
auto *selfTyDecl = ctor->getParent()->getSelfNominalTypeDecl();
auto selfTy = F.mapTypeIntoContext(selfTyDecl->getDeclaredInterfaceType());
auto selfMetatype = getLoweredType(MetatypeType::get(selfTy));
SILValue selfMetatypeValue = B.createMetatype(loc, selfMetatype);
// --- create a temporary storage for the result of the call
// it will be deallocated automatically as we exit this scope
VarDecl *var = classDecl->getDistributedActorIDProperty();
auto resultTy = getLoweredType(F.mapTypeIntoContext(var->getInterfaceType()));
auto temp = emitTemporaryAllocation(loc, resultTy);
// --- emit the call itself.
emitDistributedActorSystemWitnessCall(
B, loc, C.Id_assignID,
actorSystem, getLoweredType(selfTy),
{ temp, selfMetatypeValue });
// --- initialize the property.
initializeProperty(*this, loc, borrowedSelfArg, var, temp, IsTake);
}
// TODO(distributed): rename to DistributedActorID
InitializeDistActorIdentity::InitializeDistActorIdentity(ConstructorDecl *ctor,
ManagedValue actorSelf)
: ctor(ctor),
actorSelf(actorSelf) {
systemVar = ctor->getDeclContext()
->getSelfClassDecl()
->getDistributedActorSystemProperty();
assert(systemVar);
}
void InitializeDistActorIdentity::emit(SILGenFunction &SGF, CleanupLocation loc,
ForUnwind_t forUnwind) {
// If we're unwinding, that must mean we're in the case where the
// evaluating the expression being assigned to the actorSystem has
// thrown an error. In that case, we cannot initialize the identity,
// since there is no actorSystem.
if (forUnwind == IsForUnwind)
return;
// Save the current clean-up depth
auto baseDepth = SGF.getCleanupsDepth();
{
loc.markAutoGenerated();
auto borrowedSelf = actorSelf.borrow(SGF, loc);
// load the actorSystem value
Type formalType = SGF.F.mapTypeIntoContext(systemVar->getInterfaceType());
SILType loweredType = SGF.getLoweredType(formalType).getAddressType();
auto ref =
SGF.B.createRefElementAddr(loc, borrowedSelf, systemVar, loweredType);
SGFContext ctx;
auto systemVal =
SGF.emitLoad(loc, ref.getValue(),
SGF.getTypeLowering(loweredType), ctx, IsNotTake);
// Important that we mark the location as auto-generated, since the id
// is a @_compilerInitialized field.
SGF.emitDistActorIdentityInit(ctor, loc,
borrowedSelf.getValue(), systemVal.getValue());
}
// Emit any active clean-ups we just pushed.
while (SGF.getTopCleanup() != baseDepth)
SGF.Cleanups.popAndEmitCleanup(SGF.getTopCleanup(), loc, forUnwind);
}
void InitializeDistActorIdentity::dump(SILGenFunction &) const {
#ifndef NDEBUG
llvm::errs() << "InitializeDistActorIdentity\n"
<< "State: " << getState()
<< "\n";
#endif
}
void SILGenFunction::emitDistributedActorImplicitPropertyInits(
ConstructorDecl *ctor, ManagedValue selfArg) {
// Only designated initializers should perform this initialization.
assert(ctor->isDesignatedInit());
auto loc = SILLocation(ctor);
loc.markAutoGenerated();
selfArg = selfArg.borrow(*this, loc);
// implicit ctors initialize the system and identity from
// its ActorSystem parameter.
if (ctor->isImplicit()) {
SILValue actorSystem = findFirstDistributedActorSystemArg(F);
emitActorSystemInit(*this, ctor, loc, selfArg, actorSystem);
emitDistActorIdentityInit(ctor, loc, selfArg.getValue(), actorSystem);
return;
}
// for explicit ctors, store (but do not push) a clean-up that will
// initialize the identity in whichever scope it's pushed to.
DistActorCtorContext = InitializeDistActorIdentity(ctor, selfArg);
}
void SILGenFunction::emitDistributedActorReady(
SILLocation loc, ConstructorDecl *ctor, ManagedValue actorSelf) {
// Only designated initializers get the lifecycle handling injected
assert(ctor->isDesignatedInit());
auto *dc = ctor->getDeclContext();
auto classDecl = dc->getSelfClassDecl();
FullExpr scope(Cleanups, CleanupLocation(loc));
auto borrowedSelf = actorSelf.borrow(*this, loc);
// --- load the actor system from the actor instance
ManagedValue actorSystem;
SGFContext sgfCxt;
{
VarDecl *property = classDecl->getDistributedActorSystemProperty();
Type formalType = F.mapTypeIntoContext(property->getInterfaceType());
SILType loweredType = getLoweredType(formalType).getAddressType();
SILValue actorSystemRef = emitActorPropertyReference(
*this, loc, borrowedSelf.getValue(), property);
actorSystem = emitLoad(loc, actorSystemRef,
getTypeLowering(loweredType), sgfCxt, IsNotTake);
}
emitActorReadyCall(B, loc, borrowedSelf.getValue(), actorSystem.getValue());
}
// ==== ------------------------------------------------------------------------
// MARK: remote instance initialization
/// emit a call to the distributed actor system's resolve function:
///
/// \verbatim
/// system.resolve(id:as:)
/// \endverbatim
static void createDistributedActorFactory_resolve(
SILGenFunction &SGF, ASTContext &C, FuncDecl *fd, SILValue idValue,
SILValue actorSystemValue, Type selfTy, SILValue selfMetatypeValue,
SILType resultTy, SILBasicBlock *normalBB, SILBasicBlock *errorBB) {
auto &B = SGF.B;
auto loc = SILLocation(fd);
loc.markAutoGenerated();
// // ---- actually call system.resolve(id: id, as: Self.self)
emitDistributedActorSystemWitnessCall(
B, loc, C.Id_resolve, actorSystemValue, SGF.getLoweredType(selfTy),
{ idValue, selfMetatypeValue },
std::make_pair(normalBB, errorBB));
}
/// Function body of:
/// \verbatim
/// DistributedActor.resolve(
/// id: Self.ID,
/// using system: Self.ActorSystem
/// ) throws -> Self
/// \endverbatim
void SILGenFunction::emitDistributedActorFactory(FuncDecl *fd) { // TODO(distributed): rename
/// NOTE: this will only be reached if the resolve function is actually
/// demanded. For example, by declaring the actor as `public` or
/// having at least one call to the resolve function.
auto &C = getASTContext();
auto DC = fd->getDeclContext();
SILLocation loc = fd;
// ==== Prepare argument references
// --- Parameter: id
SILArgument *idArg = F.getArgument(0);
// --- Parameter: system
SILArgument *actorSystemArg = F.getArgument(1);
SILValue selfArgValue = F.getSelfArgument();
ManagedValue selfArg = ManagedValue::forBorrowedObjectRValue(selfArgValue);
// type: SpecificDistributedActor.Type
auto selfArgType = selfArg.getType().getASTType();
auto selfMetatype = getLoweredType(selfArgType);
SILValue selfMetatypeValue = B.createMetatype(loc, selfMetatype);
// type: SpecificDistributedActor
auto *selfTyDecl = DC->getSelfClassDecl();
assert(selfTyDecl->isDistributedActor());
auto selfTy = F.mapTypeIntoContext(selfTyDecl->getDeclaredInterfaceType());
auto returnTy = getLoweredType(selfTy);
// ==== Prepare all the basic blocks
auto returnBB = createBasicBlock("returnBB");
auto resolvedBB = createBasicBlock("resolvedBB");
auto makeProxyBB = createBasicBlock("makeProxyBB");
auto switchBB = createBasicBlock("switchBB");
auto errorBB = createBasicBlock("errorBB");
SILFunctionConventions fnConv = F.getConventions();
// --- get the uninitialized allocation from the runtime system.
FullExpr scope(Cleanups, CleanupLocation(fd));
auto optionalReturnTy = SILType::getOptionalType(returnTy);
// ==== Call `try system.resolve(id: id, as: Self.self)`
{
createDistributedActorFactory_resolve(
*this, C, fd, idArg, actorSystemArg, selfTy, selfMetatypeValue,
optionalReturnTy, switchBB, errorBB);
}
// ==== switch resolved { ... }
{
B.emitBlock(switchBB);
auto resolve =
switchBB->createPhiArgument(optionalReturnTy, OwnershipKind::Owned);
auto *switchEnum = B.createSwitchEnum(
loc, resolve, nullptr,
{{C.getOptionalSomeDecl(), resolvedBB},
{std::make_pair(C.getOptionalNoneDecl(), makeProxyBB)}});
switchEnum->createOptionalSomeResult();
}
// ==== Case 'some') return the resolved instance
{
B.emitBlock(resolvedBB);
B.createBranch(loc, returnBB, {resolvedBB->getArgument(0)});
}
// ==== Case 'none') Create the remote instance
{
B.emitBlock(makeProxyBB);
// ==== Create 'remote' distributed actor instance
// --- Call: _distributedActorRemoteInitialize(Self.self)
auto builtinName = C.getIdentifier(
getBuiltinName(BuiltinValueKind::InitializeDistributedRemoteActor));
auto *remote = B.createBuiltin(
loc, builtinName,
/*returnTy*/returnTy,
/*subs*/ {},
{selfMetatypeValue});
// ==== Initialize distributed actor properties
loc.markAutoGenerated();
auto *dc = fd->getDeclContext();
auto classDecl = dc->getSelfClassDecl();
initializeProperty(*this, loc, remote,
classDecl->getDistributedActorIDProperty(),
idArg,
IsNotTake);
initializeProperty(*this, loc, remote,
classDecl->getDistributedActorSystemProperty(),
actorSystemArg,
IsNotTake);
// ==== Branch to return the fully initialized remote instance
B.createBranch(loc, returnBB, {remote});
}
// --- Emit return logic
// return <remote>
{
B.emitBlock(returnBB);
auto local = returnBB->createPhiArgument(returnTy, OwnershipKind::Owned);
Cleanups.emitCleanupsForReturn(CleanupLocation(loc), NotForUnwind);
B.createReturn(loc, local);
}
// --- Emit rethrow logic
// throw error
{
B.emitBlock(errorBB);
auto error = errorBB->createPhiArgument(
fnConv.getSILErrorType(F.getTypeExpansionContext()),
OwnershipKind::Owned);
Cleanups.emitCleanupsForReturn(CleanupLocation(loc), IsForUnwind);
// FIXME: typed throws
B.createThrow(loc, error);
}
}
// ==== ------------------------------------------------------------------------
// MARK: system.resignID()
void SILGenFunction::emitDistributedActorSystemResignIDCall(
SILLocation loc, ClassDecl *actorDecl, ManagedValue actorSelf) {
ASTContext &ctx = getASTContext();
FormalEvaluationScope scope(*this);
// ==== locate: self.id
auto idRef = emitActorPropertyReference(
*this, loc, actorSelf.getValue(), actorDecl->getDistributedActorIDProperty());
// ==== locate: self.actorSystem
auto systemRef = emitActorPropertyReference(
*this, loc, actorSelf.getValue(),
actorDecl->getDistributedActorSystemProperty());
// Perform the call.
emitDistributedActorSystemWitnessCall(
B, loc, ctx.Id_resignID,
systemRef,
SILType(),
{ idRef });
}
void
SILGenFunction::emitConditionalResignIdentityCall(SILLocation loc,
ClassDecl *actorDecl,
ManagedValue actorSelf,
SILBasicBlock *continueBB,
SILBasicBlock *finishBB) {
assert(actorDecl->isDistributedActor() &&
"only distributed actors have actorSystem lifecycle hooks in deinit");
assert(continueBB && finishBB &&
"need valid continue and finish basic blocks");
auto selfTy = F.mapTypeIntoContext(actorDecl->getDeclaredInterfaceType());
// we only system.resignID if we are a local actor,
// and thus the address was created by system.assignID.
auto isRemoteBB = createBasicBlock("isRemoteBB");
auto isLocalBB = createBasicBlock("isLocalBB");
// if __isRemoteActor(self) {
// ...
// } else {
// ...
// }
emitDistributedIfRemoteBranch(loc,
actorSelf, selfTy,
/*if remote*/isRemoteBB,
/*if local*/isLocalBB);
// if remote, return early; the user defined deinit should not run.
{
B.emitBlock(isRemoteBB);
B.createBranch(loc, finishBB);
}
// if local, resign identity.
{
B.emitBlock(isLocalBB);
emitDistributedActorSystemResignIDCall(loc, actorDecl, actorSelf);
B.createBranch(loc, continueBB);
}
}
/******************************************************************************/
/******************* DISTRIBUTED DEINIT: class memberwise destruction *********/
/******************************************************************************/
void SILGenFunction::emitDistributedActorClassMemberDestruction(
SILLocation cleanupLoc, ManagedValue selfValue, ClassDecl *cd,
SILBasicBlock *normalMemberDestroyBB,
SILBasicBlock *remoteMemberDestroyBB,
SILBasicBlock *finishBB) {
auto selfTy = cd->getDeclaredInterfaceType();
Scope scope(Cleanups, CleanupLocation(cleanupLoc));
auto isLocalBB = createBasicBlock("isLocalBB");
// if __isRemoteActor(self) {
// ...
// } else {
// ...
// }
emitDistributedIfRemoteBranch(cleanupLoc,
selfValue, selfTy,
/*if remote*/remoteMemberDestroyBB,
/*if local*/isLocalBB);
// // if __isRemoteActor(self)
// {
// // destroy only self.id and self.actorSystem
// }
{
B.emitBlock(remoteMemberDestroyBB);
for (VarDecl *vd : cd->getStoredProperties()) {
if (getActorIsolation(vd) == ActorIsolation::ActorInstance)
continue;
destroyClassMember(cleanupLoc, selfValue, vd);
}
B.createBranch(cleanupLoc, finishBB);
}
// // else (local distributed actor)
// {
// <continue normal deinit>
// }
{
B.emitBlock(isLocalBB);
B.createBranch(cleanupLoc, normalMemberDestroyBB);
}
}
|