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
|
//===--- SILGenTopLevel.cpp - Top-level Code Emission ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 "SILGenTopLevel.h"
#include "SILGenFunction.h"
#include "Scope.h"
#include "swift/AST/DiagnosticsSIL.h"
#define DEBUG_TYPE "silgen"
using namespace swift;
using namespace Lowering;
static FuncDecl *synthesizeExit(ASTContext &ctx, ModuleDecl *moduleDecl) {
// Synthesize an exit function with this interface.
// @_extern(c)
// func exit(_: Int32) -> Never
ParameterList *params =
ParameterList::createWithoutLoc(ParamDecl::createImplicit(
ctx, Identifier(), Identifier(), ctx.getInt32Type(), moduleDecl));
FuncDecl *exitFuncDecl = FuncDecl::createImplicit(
ctx, StaticSpellingKind::None,
DeclName(ctx, DeclBaseName(ctx.getIdentifier("exit")), params), {},
/*async*/ false, /*throws*/ false, /*thrownType*/ Type(), {}, params,
ctx.getNeverType(), moduleDecl);
exitFuncDecl->getAttrs().add(new (ctx) ExternAttr(
std::nullopt, std::nullopt, ExternKind::C, /*implicit*/ true));
return exitFuncDecl;
}
void SILGenModule::emitEntryPoint(SourceFile *SF, SILFunction *TopLevel) {
auto EntryRef = SILDeclRef::getMainFileEntryPoint(SF);
bool isAsyncTopLevel = false;
if (SF->isAsyncContext()) {
isAsyncTopLevel = true;
auto asyncEntryRef = SILDeclRef::getAsyncMainFileEntryPoint(SF);
auto *asyncTopLevel = getFunction(asyncEntryRef, ForDefinition);
SILGenFunction(*this, *TopLevel, SF)
.emitAsyncMainThreadStart(asyncEntryRef);
TopLevel = asyncTopLevel;
EntryRef = asyncEntryRef;
}
TopLevel->createProfiler(EntryRef);
SILGenFunction TopLevelSGF(*this, *TopLevel, SF,
/* IsEmittingTopLevelCode */ true);
TopLevelSGF.MagicFunctionName = SwiftModule->getName();
auto moduleCleanupLoc = CleanupLocation::getModuleCleanupLocation();
TopLevelSGF.prepareEpilog(SF, std::nullopt,
getASTContext().getErrorExistentialType(),
moduleCleanupLoc);
auto prologueLoc = RegularLocation::getModuleLocation();
prologueLoc.markAsPrologue();
if (SF->isAsyncContext()) {
// emitAsyncMainThreadStart will create argc and argv.
// Just set the main actor as the expected executor; we should
// already be running on it.
SILValue executor = TopLevelSGF.emitMainExecutor(prologueLoc);
TopLevelSGF.ExpectedExecutor = TopLevelSGF.B.createOptionalSome(
prologueLoc, executor, SILType::getOptionalType(executor->getType()));
} else {
// Create the argc and argv arguments.
auto entry = TopLevelSGF.B.getInsertionBB();
auto context = TopLevelSGF.getTypeExpansionContext();
auto paramTypeIter =
TopLevelSGF.F.getConventions().getParameterSILTypes(context).begin();
entry->createFunctionArgument(*paramTypeIter);
entry->createFunctionArgument(*std::next(paramTypeIter));
}
{
Scope S(TopLevelSGF.Cleanups, moduleCleanupLoc);
SILGenTopLevel(TopLevelSGF).visitSourceFile(SF);
}
// Unregister the top-level function emitter.
TopLevelSGF.stopEmittingTopLevelCode();
// Write out the epilog.
auto moduleLoc = RegularLocation::getModuleLocation();
moduleLoc.markAutoGenerated();
auto returnInfo = TopLevelSGF.emitEpilogBB(moduleLoc);
auto returnLoc = returnInfo.second;
returnLoc.markAutoGenerated();
SILFunction *exitFunc = nullptr;
SILType returnType;
if (isAsyncTopLevel) {
FuncDecl *exitFuncDecl = getExit();
if (!exitFuncDecl) {
// If it doesn't exist, we can conjure one up instead of crashing
exitFuncDecl = synthesizeExit(getASTContext(), TopLevel->getModule().getSwiftModule());
}
exitFunc = getFunction(
SILDeclRef(exitFuncDecl, SILDeclRef::Kind::Func, /*isForeign*/ true),
NotForDefinition);
SILFunctionType &funcType =
*exitFunc->getLoweredType().getAs<SILFunctionType>();
returnType = SILType::getPrimitiveObjectType(
funcType.getParameters().front().getInterfaceType());
} else {
returnType = TopLevelSGF.F.getConventions().getSingleSILResultType(
TopLevelSGF.getTypeExpansionContext());
}
auto emitTopLevelReturnValue = [&](unsigned value) -> SILValue {
// Create an integer literal for the value.
auto litType = SILType::getBuiltinIntegerType(32, getASTContext());
SILValue retValue =
TopLevelSGF.B.createIntegerLiteral(moduleLoc, litType, value);
// Wrap that in a struct if necessary.
if (litType != returnType) {
retValue = TopLevelSGF.B.createStruct(moduleLoc, returnType, retValue);
}
return retValue;
};
// Fallthrough should signal a normal exit by returning 0.
SILValue returnValue;
if (TopLevelSGF.B.hasValidInsertionPoint())
returnValue = emitTopLevelReturnValue(0);
// Handle the implicit rethrow block.
auto rethrowBB = TopLevelSGF.ThrowDest.getBlock();
TopLevelSGF.ThrowDest = JumpDest::invalid();
// If the rethrow block wasn't actually used, just remove it.
if (rethrowBB->pred_empty()) {
TopLevelSGF.eraseBasicBlock(rethrowBB);
// Otherwise, we need to produce a unified return block.
} else {
auto returnBB = TopLevelSGF.createBasicBlock();
if (TopLevelSGF.B.hasValidInsertionPoint())
TopLevelSGF.B.createBranch(returnLoc, returnBB, returnValue);
returnValue = returnBB->createPhiArgument(returnType, OwnershipKind::Owned);
TopLevelSGF.B.emitBlock(returnBB);
// Emit the rethrow block.
SILGenSavedInsertionPoint savedIP(TopLevelSGF, rethrowBB,
FunctionSection::Postmatter);
// Log the error.
SILValue error = rethrowBB->getArgument(0);
TopLevelSGF.B.createBuiltin(moduleLoc,
getASTContext().getIdentifier("errorInMain"),
Types.getEmptyTupleType(), {}, {error});
// Then end the lifetime of the error.
//
// We do this to appease the ownership verifier. We do not care about
// actually destroying the value since we are going to immediately exit,
// so this saves us a slight bit of code-size since end_lifetime is
// stripped out after ownership is removed.
TopLevelSGF.B.createEndLifetime(moduleLoc, error);
// Signal an abnormal exit by returning 1.
TopLevelSGF.Cleanups.emitCleanupsForReturn(CleanupLocation(moduleLoc),
IsForUnwind);
TopLevelSGF.B.createBranch(returnLoc, returnBB, emitTopLevelReturnValue(1));
}
// Return.
if (TopLevelSGF.B.hasValidInsertionPoint()) {
if (isAsyncTopLevel) {
SILValue exitCall = TopLevelSGF.B.createFunctionRef(moduleLoc, exitFunc);
TopLevelSGF.B.createApply(moduleLoc, exitCall, {}, {returnValue});
TopLevelSGF.B.createUnreachable(moduleLoc);
} else {
TopLevelSGF.B.createReturn(returnLoc, returnValue);
}
}
// Okay, we're done emitting the top-level function; destroy the
// emitter and verify the result.
SILFunction &toplevel = TopLevelSGF.getFunction();
LLVM_DEBUG(llvm::dbgs() << "lowered toplevel sil:\n";
toplevel.print(llvm::dbgs()));
toplevel.verifyIncompleteOSSA();
emitLazyConformancesForFunction(&toplevel);
}
/// Generate code for calling the given main function.
void SILGenFunction::emitCallToMain(FuncDecl *mainFunc) {
// This function is effectively emitting SIL for:
// return try await TheType.$main();
auto loc = SILLocation(mainFunc);
auto *entryBlock = B.getInsertionBB();
SILDeclRef mainFunctionDeclRef(mainFunc, SILDeclRef::Kind::Func);
SILFunction *mainFunction =
SGM.getFunction(mainFunctionDeclRef, NotForDefinition);
NominalTypeDecl *mainType =
mainFunc->getDeclContext()->getSelfNominalTypeDecl();
auto metatype = B.createMetatype(mainType, getLoweredType(mainType->getInterfaceType()));
auto mainFunctionRef = B.createFunctionRef(loc, mainFunction);
auto builtinInt32Type = SILType::getBuiltinIntegerType(
32, getASTContext());
// Set up the exit block, which will either return the exit value
// (for synchronous main()) or call exit() with the return value (for
// asynchronous main()).
auto *exitBlock = createBasicBlock();
SILValue exitCode =
exitBlock->createPhiArgument(builtinInt32Type, OwnershipKind::None);
B.setInsertionPoint(exitBlock);
if (!mainFunc->hasAsync()) {
auto returnType = F.getConventions().getSingleSILResultType(
B.getTypeExpansionContext());
if (exitCode->getType() != returnType)
exitCode = B.createStruct(loc, returnType, exitCode);
B.createReturn(loc, exitCode);
} else {
FuncDecl *exitFuncDecl = SGM.getExit();
if (!exitFuncDecl) {
// If it doesn't exist, we can conjure one up instead of crashing
exitFuncDecl = synthesizeExit(getASTContext(), mainFunc->getModuleContext());
}
SILFunction *exitSILFunc = SGM.getFunction(
SILDeclRef(exitFuncDecl, SILDeclRef::Kind::Func, /*isForeign*/ true),
NotForDefinition);
SILFunctionType &funcType =
*exitSILFunc->getLoweredType().getAs<SILFunctionType>();
SILType retType = SILType::getPrimitiveObjectType(
funcType.getParameters().front().getInterfaceType());
exitCode = B.createStruct(loc, retType, exitCode);
SILValue exitCall = B.createFunctionRef(loc, exitSILFunc);
B.createApply(loc, exitCall, {}, {exitCode});
B.createUnreachable(loc);
}
// Form a call to the main function.
CanSILFunctionType mainFnType = mainFunction->getConventions().funcTy;
ASTContext &ctx = getASTContext();
if (mainFnType->hasErrorResult()) {
auto *successBlock = createBasicBlock();
B.setInsertionPoint(successBlock);
successBlock->createPhiArgument(SGM.Types.getEmptyTupleType(),
OwnershipKind::None);
SILValue zeroReturnValue =
B.createIntegerLiteral(loc, builtinInt32Type, 0);
B.createBranch(loc, exitBlock, {zeroReturnValue});
SILResultInfo errorResult = mainFnType->getErrorResult();
SILType errorType = errorResult.getSILStorageInterfaceType();
auto *failureBlock = createBasicBlock();
B.setInsertionPoint(failureBlock);
SILValue error;
if (IndirectErrorResult) {
error = IndirectErrorResult;
} else {
error = failureBlock->createPhiArgument(
errorType, OwnershipKind::Owned);
}
// Log the error.
if (errorType.getASTType()->isErrorExistentialType()) {
// Load the indirect error, if needed.
if (IndirectErrorResult) {
const TypeLowering &errorExistentialTL = getTypeLowering(errorType);
error = emitLoad(
loc, IndirectErrorResult, errorExistentialTL, SGFContext(),
IsTake).forward(*this);
}
// Call the errorInMain entrypoint, which takes an existential
// error.
B.createBuiltin(loc, ctx.getIdentifier("errorInMain"),
SGM.Types.getEmptyTupleType(), {}, {error});
} else {
// Call the _errorInMainTyped entrypoint, which handles
// arbitrary error types.
SILValue tmpBuffer;
FuncDecl *entrypoint = ctx.getErrorInMainTyped();
auto genericSig = entrypoint->getGenericSignature();
SubstitutionMap subMap = SubstitutionMap::get(
genericSig, [&](SubstitutableType *dependentType) {
return errorType.getASTType();
}, LookUpConformanceInModule(getModule().getSwiftModule()));
// Generic errors are passed indirectly.
if (!error->getType().isAddress()) {
auto *tmp = B.createAllocStack(loc, error->getType().getObjectType(),
std::nullopt);
emitSemanticStore(
loc, error, tmp,
getTypeLowering(tmp->getType()), IsInitialization);
tmpBuffer = tmp;
error = tmp;
}
emitApplyOfLibraryIntrinsic(
loc, entrypoint, subMap,
{ ManagedValue::forForwardedRValue(*this, error) },
SGFContext());
}
B.createUnreachable(loc);
B.setInsertionPoint(entryBlock);
B.createTryApply(loc, mainFunctionRef, SubstitutionMap(),
{metatype}, successBlock, failureBlock);
} else {
B.setInsertionPoint(entryBlock);
B.createApply(loc, mainFunctionRef, SubstitutionMap(), {metatype});
SILValue returnValue =
B.createIntegerLiteral(loc, builtinInt32Type, 0);
B.createBranch(loc, exitBlock, {returnValue});
}
}
void SILGenModule::emitEntryPoint(SourceFile *SF) {
assert(!M.lookUpFunction(getASTContext().getEntryPointFunctionName()) &&
"already emitted toplevel?!");
auto mainEntryRef = SILDeclRef::getMainFileEntryPoint(SF);
SILFunction *TopLevel = getFunction(mainEntryRef, ForDefinition);
TopLevel->setBare(IsBare);
emitEntryPoint(SF, TopLevel);
}
void SILGenFunction::emitMarkFunctionEscapeForTopLevelCodeGlobals(
SILLocation Loc, CaptureInfo CaptureInfo) {
llvm::SmallVector<SILValue, 4> Captures;
for (auto Capture : CaptureInfo.getCaptures()) {
// Decls captured by value don't escape.
auto It = VarLocs.find(Capture.getDecl());
if (It == VarLocs.end() || !It->getSecond().value->getType().isAddress())
continue;
Captures.push_back(It->second.value);
}
if (!Captures.empty())
B.createMarkFunctionEscape(Loc, Captures);
}
/// Emit a `mark_function_escape_instruction` into `SGF` if `AFD` captures an
/// uninitialized global variable
static void emitMarkFunctionEscape(SILGenFunction &SGF,
AbstractFunctionDecl *AFD) {
if (AFD->getDeclContext()->isLocalContext())
return;
auto CaptureInfo = AFD->getCaptureInfo();
SGF.emitMarkFunctionEscapeForTopLevelCodeGlobals(AFD, std::move(CaptureInfo));
}
SILGenTopLevel::SILGenTopLevel(SILGenFunction &SGF) : SGF(SGF) {}
void SILGenTopLevel::visitSourceFile(SourceFile *SF) {
for (auto *D : SF->getTopLevelDecls()) {
D->visitAuxiliaryDecls([&](Decl *AuxiliaryDecl) { visit(AuxiliaryDecl); });
visit(D);
}
if (auto *SynthesizedFile = SF->getSynthesizedFile()) {
for (auto *D : SynthesizedFile->getTopLevelDecls()) {
assert(isa<ExtensionDecl>(D) || isa<ProtocolDecl>(D));
visit(D);
}
}
for (Decl *D : SF->getHoistedDecls()) {
visit(D);
}
for (TypeDecl *TD : SF->getLocalTypeDecls()) {
if (TD->getDeclContext()->getInnermostSkippedFunctionContext())
continue;
visit(TD);
}
}
void SILGenTopLevel::visitNominalTypeDecl(NominalTypeDecl *NTD) {
TypeVisitor(SGF).emit(NTD);
}
void SILGenTopLevel::visitExtensionDecl(ExtensionDecl *ED) {
ExtensionVisitor(SGF).emit(ED);
}
void SILGenTopLevel::visitAbstractFunctionDecl(AbstractFunctionDecl *AFD) {
emitMarkFunctionEscape(SGF, AFD);
}
void SILGenTopLevel::visitAbstractStorageDecl(AbstractStorageDecl *ASD) {
SGF.SGM.visitEmittedAccessors(ASD,
[this](AccessorDecl *Accessor) { visitAbstractFunctionDecl(Accessor); });
}
void SILGenTopLevel::visitTopLevelCodeDecl(TopLevelCodeDecl *TD) {
SGF.emitProfilerIncrement(TD->getBody());
DebugScope DS(SGF, CleanupLocation(TD));
for (auto &ESD : TD->getBody()->getElements()) {
if (!SGF.B.hasValidInsertionPoint()) {
if (auto *S = ESD.dyn_cast<Stmt *>()) {
if (S->isImplicit())
continue;
} else if (auto *E = ESD.dyn_cast<Expr *>()) {
if (E->isImplicit())
continue;
}
SGF.SGM.diagnose(ESD.getStartLoc(), diag::unreachable_code);
// There's no point in trying to emit anything else.
return;
}
if (auto *S = ESD.dyn_cast<Stmt *>()) {
SGF.emitStmt(S);
} else if (auto *E = ESD.dyn_cast<Expr *>()) {
SGF.emitIgnoredExpr(E);
} else {
SGF.visit(ESD.get<Decl *>());
}
}
}
SILGenTopLevel::TypeVisitor::TypeVisitor(SILGenFunction &SGF) : SGF(SGF) {}
void SILGenTopLevel::TypeVisitor::emit(IterableDeclContext *Ctx) {
for (auto *Member : Ctx->getABIMembers()) {
visit(Member);
}
}
void SILGenTopLevel::TypeVisitor::visit(Decl *D) {
if (SGF.SGM.shouldSkipDecl(D))
return;
TypeMemberVisitor::visit(D);
}
void SILGenTopLevel::TypeVisitor::visitPatternBindingDecl(
PatternBindingDecl *PD) {
for (auto i : range(PD->getNumPatternEntries())) {
if (!PD->getExecutableInit(i) || PD->isStatic())
continue;
auto *Var = PD->getAnchoringVarDecl(i);
if (Var->getDeclContext()->isLocalContext())
continue;
auto CaptureInfo = PD->getCaptureInfo(i);
// If this is a stored property initializer inside a type at global scope,
// it may close over a global variable. If we're emitting top-level code,
// then emit a "mark_function_escape" that lists the captured global
// variables so that definite initialization can reason about this
// escape point.
SGF.emitMarkFunctionEscapeForTopLevelCodeGlobals(Var,
std::move(CaptureInfo));
}
}
void SILGenTopLevel::TypeVisitor::visitNominalTypeDecl(NominalTypeDecl *NTD) {
TypeVisitor(SGF).emit(NTD);
}
void SILGenTopLevel::TypeVisitor::visitAbstractFunctionDecl(
AbstractFunctionDecl *AFD) {
emitMarkFunctionEscape(SGF, AFD);
}
void SILGenTopLevel::TypeVisitor::visitAbstractStorageDecl(
AbstractStorageDecl *ASD) {
SGF.SGM.visitEmittedAccessors(ASD,
[this](AccessorDecl *Accessor) { visitAbstractFunctionDecl(Accessor); });
}
SILGenTopLevel::ExtensionVisitor::ExtensionVisitor(SILGenFunction &SGF)
: TypeVisitor(SGF) {}
void SILGenTopLevel::ExtensionVisitor::visitPatternBindingDecl(
PatternBindingDecl *PD) {
auto *Ctx = PD->getDeclContext();
if (isa<ExtensionDecl>(Ctx) &&
cast<ExtensionDecl>(Ctx)->isObjCImplementation()) {
TypeVisitor::visitPatternBindingDecl(PD);
}
}
|