Commit Graph

1604 Commits

Author SHA1 Message Date
Doug Gregor
3edbb06632 [SILGen] Don't peephole closures with abstraction differences in the thrown error
The prolog and epilog code in SILGen is not set up to deal with
abstraction differences in the thrown error type of closures, so disable
the peephole optimization for closure literals.

Fixes https://github.com/apple/swift/issues/71401 / rdar://122366566,
which I've stared at for waaaaay too many hours.
2024-02-12 23:15:07 -08:00
Andrew Trick
da3f583492 Add mark_dependence [unresolved]
In preparation for inserting mark_dependence instructions for lifetime
dependencies early, immediately after SILGen. That will simplify the
implementation of borrowed arguments.

Marking them unresolved is needed to make OSSA verification
conservative until lifetime dependence diagnostics runs.
2024-02-08 22:53:16 -08:00
Ellie Shin
72a7760027 Support package SIL linkage.
Decls with a package access level are currently set to public SIL
linkages. This limits the ability to have more fine-grained control
and optimize around resilience and serialization.
This PR introduces a separate SIL linkage and FormalLinkage for
package decls, pipes them down to IRGen, and updates linkage checks
at call sites to include package linkage.

Resolves rdar://121409846
2024-02-06 01:23:14 -08:00
Pavel Yaskevich
2e9fffb524 [SILGen] Implement actor isolation erasure thunk
The thunk is a reabstraction thunk with a custom prolog that
has a runtime precondition check that makes sure that concurrent
environment where the thunk is run matches that of a global
actor associated with the thunked type.
2024-02-01 13:28:25 -08:00
Pavel Yaskevich
4debaf2c5d [AST] Introduce a new conversion expression - ActorIsolationErasure
To be used in situations when a global actor isolation is stripped
from a function type in argument positions and could be extended in
the future to cover more if needed.
2024-02-01 13:28:25 -08:00
Hamish Knight
0a4c029cfc [AST] Introduce UnreachableExpr
This models the conversion from an uninhabited
value to any type, and allows us to get rid of
a couple of places where we'd attempt to drop
the return statement instead.
2024-01-30 14:08:54 +00:00
Doug Gregor
da08b96371 Allow the main function for @main types to use typed throws
Allow the use of typed throws for the main functions of `@main` types,
and thread the thrown error through to a new entry point in the library,
`_errorInMainTyped`, which is generic in the thrown error type.

Fixes rdar://121603043.
2024-01-28 11:21:00 -08:00
Slava Pestov
166d059625 Merge pull request #70937 from slavapestov/rename-conformance-lookup
TypeChecker::conformsToProtocol() => ModuleDecl::checkConformance()
2024-01-16 22:21:04 -05:00
Doug Gregor
255009dddb Implement #isolation macro to produce the isolation of the current context
Introduce a new expression macro that produces an value of type
`(any AnyActor)?` that describes the current actor isolation. This
isolation will be `nil` in non-isolated code, and refer to either the
actor instance of shared global actor in other cases.

This is currently behind the experimental feature flag
OptionalIsolatedParameters.
2024-01-16 14:25:51 -08:00
Slava Pestov
14d1fcb51a AST: TypeChecker::conformsToProtocol() => ModuleDecl::checkConformance() 2024-01-16 17:08:00 -05:00
Holly Borla
5ac839b11d [SILGen] Only hop to the callee isolation domain once when evaluating isolated
default arguments.
2024-01-10 20:18:00 -08:00
Erik Eckstein
bc99986cf9 SIL: add a dependency token operand to global_addr
Optionally, the dependency to the initialization of the global can be specified with a dependency token `depends_on <token>`.
This is usually a `builtin "once"` which calls the initializer for the global variable.
2024-01-10 09:33:58 +01:00
Andrew Trick
264cbaea42 Add mark_dependence [nonescaping] flag.
The dependent 'value' may be marked 'nonescaping', which guarantees that the
lifetime dependence is statically enforceable. In this case, the compiler
must be able to follow all values forwarded from the dependent 'value', and
recognize all final (non-forwarded, non-escaping) use points. This implies
that `findPointerEscape` is false. A diagnostic pass checks that the
incoming SIL to verify that these use points are all initially within the
'base' lifetime. Regular 'mark_dependence' semantics ensure that
optimizations cannot violate the lifetime dependence after diagnostics.
2024-01-04 14:47:35 -08:00
Doug Gregor
d740965753 [Typed throws] Terminate with an error message for typed try! failures. 2023-12-16 23:58:51 -08:00
Felipe de Azevedo Piovezan
ac85703039 Merge pull request #70111 from felipepiovezan/felipe/fix_incorrect_debug_loc
[DebugInfo][SILGen] Ensure "guard let" is lowered with a non-implicit location
2023-11-30 19:34:02 -08:00
Felipe de Azevedo Piovezan
8baf933114 [DebugInfo][SILGen] Ensure "guard let" is lowered with a non-implicit location
Prior to this patch, a "guard let" was being lowered with an implicit debug
location, causing it to be dropped in later stages of the compiler, and making
it impossible to set a breakpoint in that line.

This was tracked down to a piece of code in `SILGenFunction::emitExprInto`,
which takes an optional Location parameter that was being ignored in one code
path.
2023-11-30 09:14:36 -08:00
Pavel Yaskevich
c9a8355c26 [AST] Add a way to retrieve key path and its root/value types from KeyPathExpr 2023-11-28 13:02:17 -08:00
Nate Chandler
98acb40d99 [SIL] Addr-only enums have non-none ownership.
Values produced by address-only `enum` instructions have non-none
ownership.  And because `enum` is representation-changing, they have
`owned` ownership.

This corresponds at the opaque values SIL stage to the fact that at the
address-lowered SIL stage the storage location has non-trivial
initialization which must be `destroy_addr`d, regardless of whether an
empty case was stored to it.
2023-11-16 11:03:14 -08:00
Doug Gregor
ae6e303956 Merge pull request #69565 from slavapestov/optional-force-try-expr-typed-throws
SILGen: Lowering 'try?' and 'try!' with typed throws
2023-11-04 02:40:03 -07:00
Andrew Trick
86365cdbd1 Merge pull request #69476 from atrick/fix-conversion-lifetime
Fix SILGen to emit fix_lifetime for inout-to-pointer conversion.
2023-11-01 17:36:27 -07:00
Andrew Trick
966df3585c Fix SILGen to emit fix_lifetime for inout-to-pointer conversion.
This fixes use-after-free miscompilation bugs that can occur when a
lifetime-optimized standard library type, like Dictionary or String is
converted to an UnsafePointer using implicit inout-to-pointer
conversion:

func ptrToDictionary(_: UnsafePointer<Dictionary<K, V>>) {}

func testDictionary() {
  var d: Dictionary = ...
  ptrToDictionary(&d)
}

func ptrToString(_: UnsafePointer<String>) {}

func testString() {
  var s: String = ...
  ptrToString(&s)
}

Address to pointer conversion must always be guarded by either a
mark_dependence or a fix_lifetime. Use fix_lifetime for call emission
in SILGen to limit the optimization impact to the narrow scope of the
pointer conversion.

This could negatively impact performance simply because SIL does not
provide a way to scope pointer conversion. fix_lifetime is
unnecessarilly conservative and prevents the elimination of dead
allocations.

rdar://117807309 (Fix SILGen to emit fix_lifetime for
inout-to-pointer conversion)
2023-11-01 11:34:25 -07:00
Slava Pestov
204bb0c2f2 SILGen: Lowering 'try?' and 'try!' with typed throws 2023-10-31 22:55:48 -04:00
Slava Pestov
079c5c4a1c SILGen: Support for 'throw' and 'try_apply' with indirect error result 2023-10-31 16:58:54 -04:00
Holly Borla
49d6399a88 [Concurrency] Allow isolated default arguments to be used from across isolation
boundaries.
2023-10-24 22:54:22 -07:00
Doug Gregor
51eed19d4b [Typed throws] Type system support for typed throws.
Add the thrown type into the AST representation of function types,
mapping from function type representations and declarations into the
appropriate thrown type. Add tests for serialization, printing, and
basic equivalence of function types that have thrown errors.
2023-09-29 10:51:53 -07:00
Yuta Saito
c5314bd3af Centralize KeyPath accessor calling convention logic to IRGen
KeyPath's getter/setter/hash/equals functions have their own calling
convention, which receives generic arguments and embedded indices from a
given KeyPath argument buffer.
The convention was previously implemented by:
1. Accepting an argument buffer as an UnsafeRawPointer and casting it to
   indices tuple pointer in SIL.
2. Bind generic arguments info from the given argument buffer while emitting
   prologue in IRGen by creating a new forwarding thunk.

This 2-phase lowering approach was not ideal, as it blocked KeyPath
projection optimization [^1], and also required having a target arch
specific signature lowering logic in SIL-level [^2].

This patch centralizes the KeyPath accessor calling convention logic to
IRGen, by introducing `@convention(keypath_accessor_XXX)` convention in
SIL and lowering it in IRGen. This change unblocks the KeyPath projection
optimization while capturing subscript indices, and also makes it easier
to support WebAssembly target.

[^1]: https://github.com/apple/swift/pull/28799
[^2]: https://forums.swift.org/t/wasm-support/16087/21
2023-09-20 11:25:39 -07:00
Kavon Farvardin
54e5205194 Merge pull request #68600 from kavon/optional-try-coercion-bug-v2
[SILGen] fix SR-14882: Assertion failed: (!concreteBuffer && "concrete buffer already formed?!")
2023-09-19 09:42:04 -07:00
Kavon Farvardin
583f127de7 fix [SR-14882]: Assertion failed: (!concreteBuffer && "concrete buffer already formed?!")
The problem was that in the by-address emission, we were calling
 `getAddressForInPlaceInitialization` twice, triggering the assert.

The first time in `emitExprInto` for the normal result case.

The second time to obtain the address again when generating the
catch block to inject a `.none` into that same address.

This patch does a light refactoring to more closely mirror
`visitOptionalEvaluationExpr`, which avoids calling the asserting method.

fixes rdar://80277465
2023-09-18 15:41:43 -07:00
Hamish Knight
6ee44f09b4 Introduce then statements
These allow multi-statement `if`/`switch` expression
branches that can produce a value at the end by
saying `then <expr>`. This is gated behind
`-enable-experimental-feature ThenStatements`
pending evolution discussion.
2023-09-01 14:32:14 +01:00
Michael Gottesman
37d60a08bb [move-only] Rename mark_must_check -> mark_unresolved_non_copyable_value.
I was originally hoping to reuse mark_must_check for multiple types of checkers.
In practice, this is not what happened... so giving it a name specifically to do
with non copyable types makes more sense and makes the code clearer.

Just a pure rename.
2023-08-30 22:29:30 -07:00
Nate Chandler
49e76caca5 [OpaqueValues] Consume addr-only vars as loadable. 2023-08-22 17:41:15 -07:00
Nate Chandler
8c48ca2e8c [OpaqueValues] Addr-only consumes emit loadably. 2023-08-22 11:18:44 -07:00
Michael Gottesman
543063ef0e [silgen] Make ManagedValue::forUnmanaged private and change users to use other more specific APIs.
I have been doing this over the past couple of days in preparation for changing
ManagedValue to specify the type of scope its cleanup is connected to.
2023-08-19 14:11:44 -07:00
Michael Gottesman
104379adab [silgen] Rename SILGenFunction::emitManagedRetain -> emitManagedCopy.
This is an old API that should have been renamed a long time ago. It just kept
its early name due to inertia.
2023-08-19 14:11:44 -07:00
Allan Shortlidge
d062489344 SILGen: Don't reference external property descriptors for @backDeployed properties.
The property descriptors of `@backDeployed` properties aren't available on OSes
prior to the "back deployed before" OS version, so the descriptors cannot be
referenced by clients that may run against older versions of the library
that defines the property.

See https://github.com/apple/swift/pull/59214 for prior art.

Resolves rdar://106517386
2023-08-16 23:19:15 -07:00
Michael Gottesman
ff948f7309 [silgen] Convert even more cases of using trivial and values without ownership to use for*RValueWithoutOwnership APIs. 2023-08-15 11:04:01 -07:00
Nate Chandler
999f2b023a [OpaqueValues] AnyHashable src gets new context.
When storing an instance of some type that conforms to Hashable into an
lvalue of type AnyHashable, the source rvalue needs to be emitted within
a new SGFContext.  Otherwise, the LocalVarInitialization for the var of
type AnyHashable would be used and an attempt would be made to store the
instance of the conforming type into the projected box.
2023-08-09 07:03:07 -07:00
Michael Gottesman
cece84f345 [silgen] Rename forTrivialRValue -> forRValueWithoutOwnership and use it in a few places to eliminate more forUnmanaged.
With this commit, we have now eliminated ~55% of all forUnmanaged in the code
base.
2023-08-08 11:15:06 -07:00
Michael Gottesman
85e38afbac Merge pull request #67780 from gottesmm/pr-d9b586775f6ea84fe9868857eb8dd2eeaeb39f6f
[silgen] Rename forTrivialObjectRValue -> forObjectRValueWithoutOwnership and change a bunch of forUnmanaged to use this API
2023-08-08 09:58:33 -07:00
Michael Gottesman
2208caac32 [silgen] Convert a bunch of forUnmanaged -> forObjectRValueWithoutOwnership.
NFCI.
2023-08-07 13:36:02 -07:00
Michael Gottesman
7dbcdfb126 [silgen] Rename forTrivialObjectRValue -> forObjectRValueWithoutOwnership.
The reason to do this rename is that this is also used for objects that while
non-trivial have .none ownership. Example: enum instance without a case.
2023-08-07 13:36:02 -07:00
Slava Pestov
9ebb5f2e03 AST: Rename VarDecl::getType() to VarDecl::getTypeInContext()
This is a futile attempt to discourage future use of getType() by
giving it a "scary" name.

We want people to use getInterfaceType() like with the other decl kinds.
2023-08-04 14:19:25 -04:00
Nate Chandler
0ae2c0748d [OpaqueValues] Keypath setters observe triviality.
When constructing r-values during keypath setter emission, consider
whether the argument's type is trivial and construct the relevant
r-value based on that.  This worked before without opaque values because
the value is always an address.
2023-08-02 13:45:35 -07:00
Nate Chandler
aba12b3398 [OpaqueValues] Use silConv for keypath args.
Replace direct calls to SILParamInfo::getSILStorageType with calls to
SILModuleConventions::getSILType for keypath functions.
2023-08-02 13:45:35 -07:00
Joe Groff
c52ae08c7d SILGen: Don't reuse the Initialization across branches of an if or switch expression.
`Initialization` is stateful and not meant to be emitted into multiple times across different contexts.
If emitting into an initialization causes it to be split or aborted, that will carry over into
further uses of the initialization. This was happening during `if` and `switch` expression
emission, leading to miscompiles or compiler crashes. Fix this by saving only the buffer when
we prepare emission for a statement expression, and creating the initialization in the scope
where the expression for a branch actually gets emitted. Fixes rdar://112213253.
2023-07-14 14:21:57 -07:00
Evan Wilde
250082df25 [NFC] Reformat all the LLVMs
Reformatting everything now that we have `llvm` namespaces. I've
separated this from the main commit to help manage merge-conflicts and
for making it a bit easier to read the mega-patch.
2023-06-27 09:03:52 -07:00
Evan Wilde
f3ff561c6f [NFC] add llvm namespace to Optional and None
This is phase-1 of switching from llvm::Optional to std::optional in the
next rebranch. llvm::Optional was removed from upstream LLVM, so we need
to migrate off rather soon. On Darwin, std::optional, and llvm::Optional
have the same layout, so we don't need to be as concerned about ABI
beyond the name mangling. `llvm::Optional` is only returned from one
function in
```
getStandardTypeSubst(StringRef TypeName,
                     bool allowConcurrencyManglings);
```
It's the return value, so it should not impact the mangling of the
function, and the layout is the same as `std::optional`, so it should be
mostly okay. This function doesn't appear to have users, and the ABI was
already broken 2 years ago for concurrency and no one seemed to notice
so this should be "okay".

I'm doing the migration incrementally so that folks working on main can
cherry-pick back to the release/5.9 branch. Once 5.9 is done and locked
away, then we can go through and finish the replacement. Since `None`
and `Optional` show up in contexts where they are not `llvm::None` and
`llvm::Optional`, I'm preparing the work now by going through and
removing the namespace unwrapping and making the `llvm` namespace
explicit. This should make it fairly mechanical to go through and
replace llvm::Optional with std::optional, and llvm::None with
std::nullopt. It's also a change that can be brought onto the
release/5.9 with minimal impact. This should be an NFC change.
2023-06-27 09:03:52 -07:00
Hamish Knight
cca5a6e524 [SILGen] Emit block after unreachable when emitting if/switch expressions
When emitting the underlying `switch` statement
for a `switch` expression, we emit an `unreachable`
if the subject is uninhabited. Statement emission
code can handle this, but expression emission expects
an RValue to handed back. To remedy this, emit
an unreachable block that we can emit the rest of
the expression emission code into. The SILOptimizer
will then drop this unreachable block.
2023-06-12 11:29:53 +01:00
Doug Gregor
5ea559435d Merge pull request #66387 from DougGregor/silgen-freestanding-local-vars 2023-06-07 06:49:23 -07:00
Michael Gottesman
59c8cff917 [borrowing] Add support for borrowing/consuming copyable types to be a noimplicitcopy type.
rdar://108383660
2023-06-06 18:12:29 -04:00