Commit Graph

188 Commits

Author SHA1 Message Date
Gabor Horvath
f26749245b [SILGen] Fix the type of closure thunks that are passed const reference structs
This PR is another attempt at landing #76903. The changes compared to
the original PR:
* Instead of increasing the size of SILDeclRef, store the necessary type
  information in a side channel using withClosureTypeInfo.
* Rely on SGFContext to get the right ClangType
* Extend BridgingConversion with an AbstractionPattern to store the
  original clang type.
* The PR above introduced a crash during indexing system modules that
  references foreign types coming from modules imported as
  implementation only. These entities are implementation details so they
  do not need to be included during serialization. This PR adds a test
  and adds logic to exclude such clang types in the serialization
  process.

rdar://131321096&141786724
2025-09-09 12:07:52 +01:00
Doug Gregor
731f58443c Address review feedback on AbstractConformance in ProtocolConformanceRef 2025-03-23 20:54:39 -07:00
Alexis Laferrière
e97db1c844 Merge pull request #79487 from xymus/limit-nserror-optimization-to-import
SILGen: Ensure Foundation is publicly imported before referencing `NSError` in code gen
2025-02-28 15:21:11 -08:00
Alexis Laferrière
db7126c390 SILGen: Limit references to NSError in inlinable code optimization
Revisit the optimization that provides a fast path for instances of
`NSError` when erasing the `Error` type in `emitExistentialErasure`. It
generated references to `NSError` when the `Foundation` module was
loaded, no matter how it was imported. This lead to deserialization
failures at reading the swiftmodule when that reference was added to
inlinable code while `Foundation` was not a public dependency.

Fix this crash by limiting the optimization to all non-inlinable code
and only inlinable code from a module with a public dependency on
`Foundation`. This is the similar check we apply to user written
inlinable code, however here we use the module-wide dependency instead
of per file imports.

rdar://142438679
2025-02-19 15:34:20 -08:00
kibeom lee
2311794184 Fix typo in comments 2025-02-07 15:12:11 +09:00
Slava Pestov
7648a31b05 SILGen: Remove usages of SubstitutionMap::combineSubstitutionMaps() 2024-08-29 16:18:14 -04:00
Slava Pestov
375363a473 AST: Move global conformance lookup entry points to ConformanceLookup.h 2024-08-08 23:35:58 -04:00
Slava Pestov
fae01d9776 AST: Remove ModuleDecl parameter from more places 2024-07-06 12:05:46 -04:00
Tim Kientzle
1d961ba22d Add #include "swift/Basic/Assertions.h" to a lot of source files
Although I don't plan to bring over new assertions wholesale
into the current qualification branch, it's entirely possible
that various minor changes in main will use the new assertions;
having this basic support in the release branch will simplify that.
(This is why I'm adding the includes as a separate pass from
rewriting the individual assertions)
2024-06-05 19:37:30 -07:00
Joe Groff
82e566a23a SILGen: Treat Optional x! force unwrapping as a forwarding operation.
Like `?` or property access, `x!` can be borrowing, consuming, or mutated
through depending on the use site and the ownership of the base value.
Alter SILGen to emit `x!` as a borrowing operation when the result is only
used as a borrow. Fix the move-only checker not to treat the unreachable
branch as a dead path for values and try to destroy the value unnecessarily
and possibly out-of-order with cleanups on the value. Fixes rdar://127459955.
2024-05-08 15:35:07 -07:00
Slava Pestov
90ab23ed6f SILGen: Fix invariant violation with existential conformances
When erasing a pseudogeneric value in SILGen, we actually treat
the value as if it had the type `any AnyObject`, while in Sema,
it's an archetype. This requires SILGen to look up conformances
again instead of using the ones in the ErasureExpr.
2024-04-01 23:05:35 -04:00
John McCall
15b5dcb870 Simplify the representation of conversions to make it easier to extract
the source/result/lowered-result types.
2024-03-22 17:04:25 -04:00
John McCall
79d1d684be Just replace the inner abstraction pattern when combining a subtype conversion
into a reabstraction.
2024-03-22 17:03:04 -04:00
John McCall
3e64f9d69f Push isolated(any) conversions down through multiple levels of conversion.
I'm not sure there's any way to test this right now.  We don't naturally
emit multiple function conversions on a single operand, and the only way
to get a similar effect is to coerce, which interrupts the application of
`@_inheritActorContext`.  So I think this is dead code until we add closure
isolation controls, and even then it might be dead unless we allow coercion
of isolated closures, which maybe we won't.  But it's the right thing to do
in the abstract, and I was thinking of it now.
2024-03-22 02:20:44 -04:00
John McCall
a040df9aa8 Teach optional injection to peephole into more converting contexts
This allows us to propagate abstraction patterns from optional parameters
all the way to closure emission, which optimizes some code patterns but
(more importantly) propagates our knowledge that we're converting to an
`@isolated(any)` function type down to closure emission, allowing us to
set the isolation correctly.

There are still some conversion cases missing --- if we can't combine
conversions for whatever reason, we should at least shift our knowledge
that we need to produce an `@isolated(any)` type down, the same way that
we shift it when emitting a closure that we can't directly emit in the
target abstraction pattern.  But this completes the obvious cases of
peepholing for closure emission.
2024-03-22 01:19:29 -04:00
John McCall
783dd2050f [NFC] Set up the conversion peephole to turn back into normal conversions. 2024-03-21 18:10:52 -04:00
John McCall
16093848fc [NFC] Work in preparation of generalizing how we combine conversions 2024-03-21 12:47:56 -04:00
John McCall
c7d3e8f559 [NFC] Generalize how Conversion works with reabstraction conversions and
force callers to specify the input lowered type as well.
2024-03-21 12:47:56 -04:00
John McCall
5c2cd18a5b Teach SILGen to try to peephole a function conversion into the emission of
a closure expression, then don't actually do it.  The long term plan is
to actually do this, which should just be a matter of taking some of the
code out of reabstraction thunk emission and using it in prolog/epilog/return
emission.  In the short term, the goal is just to get the conversion
information down to the closure emitter so that we can see that we're
erasing into an `@isolated(any)` type and then actually erase the
closure's isolation properly instead of relying on type-based erasure,
which can't handle parameter/capture isolation correctly.
2024-02-23 02:59:39 -05:00
Ben Barham
ef8825bfe6 Migrate llvm::Optional to std::optional
LLVM has removed llvm::Optional, move over to std::optional. Also
clang-format to fix up all the renamed #includes.
2024-02-21 11:20:06 -08:00
John McCall
2d71c604ed Emit enum element arguments directly into the enum payload.
This generates significantly better code directly out of SILGen, at
the cost of having to reimplement a little bit of the argument-emission
logic to handle default arguments.  But it also neatly sidesteps the
problems we have with splitting tuple RValues when the tuple contains
a pack expansion, which will require some significant surgery to RValue
to fix.  That, in turn, fixes rdar://121489308.
2024-02-15 01:09:12 -05:00
Slava Pestov
afe05e9ff7 SILGen: Add missing call to collectExistentialConformances() 2024-02-05 18:43:06 -05: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
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
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
Andrew Trick
ea7b8055bc Rewrite some isPlusOne calls to isPlusOneOrTrivial.
Whenever we want to forward to a +1 value but don't need to destroy
the original memory, use isPlusOneOrTrivial.

This follows the existing naming scheme.

Fixes rdar://108001491 (SIL verification failed: Found mutating or
consuming use of an in_guaranteed parameter?!:
!ImmutableAddressUseVerifier().isMutatingOrConsuming(fArg))
2023-05-01 23:24:29 -07:00
John McCall
157be3420c Implement the callee side of returning a tuple containing a pack expansion.
This required quite a bit of infrastructure for emitting this kind of
tuple expression, although I'm not going to claim they really work yet;
in particular, I know the RValue constructor is going to try to explode
them, which it really shouldn't.

It also doesn't include the caller side of returns, for which I'll need
to teach ResultPlan to do the new abstraction-pattern walk.  But that's
next.
2023-03-06 04:26:18 -05:00
Joe Groff
8db31d5804 SILGen: Complete initialization of FinalContext in ConversionInitialization::tryPeephole
The callers to ConversionInitialization::tryPeephole assume that, if the conversion peephole
succeeded, that the peepholed result was fully emitted into the initialization. However, if
the ConversionInitialization sat on top of an in-memory initialization, then tryPeephole would
only set the value of the ConversionInitialization, without forwarding the value into the underlying
initialization, causing code generation to proceed leaving the underlying memory uninitialized.
This problem becomes exposed now when literal closures are emitted with a return value that is
indirectly returned and also reabstracted, and the return expression undergoes a ping-pong reabstraction
pair: we see through the conversions and peephole away the reabstractions, but fail to emplace the
result in the indirect return slot.

Fixes rdar://92654098
2022-05-27 09:07:16 -07:00
Holly Borla
6e6ca13268 [Type System] Use the constraint type of an existential type in
various places that expect ProtocolType or ProtocoolCompositionType.
2022-01-13 19:30:44 -08:00
Joe Groff
fdc0e08d60 SILGen: Emit literal closures at the abstraction level of their context.
Literal closures are only ever directly referenced in the context of the expression they're written in,
so it's wasteful to emit them at their fully-substituted calling convention and then reabstract them if
they're passed directly to a generic function. Avoid this by saving the abstraction pattern of the context
before emitting the closure, and then lowering its main entry point's calling convention at that
level of abstraction. Generalize some of the prolog/epilog code to handle converting arguments and returns
to the correct representation for a different abstraction level.
2021-09-09 13:42:02 -07:00
Joe Groff
3abe16f40f Revert "SILGen: Emit literal closures at the abstraction level of their context. [take 2]" (#39228) 2021-09-09 11:53:43 -05:00
Joe Groff
0829f5b30c Merge pull request #39080 from jckarter/emit-closure-literal-at-context-abstraction-2
SILGen: Emit literal closures at the abstraction level of their context. [take 2]
2021-09-09 09:51:29 -07:00
Andrew Trick
8f53a927b0 SILGen OSSA support for switch_enum/checked_cast_br, related cleanup
Use APIs for creating terminator results that handle forwarding
ownership consistently.

Add ManagedValue::forForwardedRValue(SILValue) to handle cleanups
consistently based on ownership forwarding.

Add SILGenBuilder::createForwardedTermResult(SILType type) for
creating termator results with the correct ownership and cleanups.

Add SILGenBuilder::createTermResult(SILType type, ValueOwnershipKind
ownership) that handles cleanup based on terminator result ownership.

Add SILGenBuilder::createOptionalSomeResult(SwitchEnumInst) so a lot
of code doesn't need to deal with unwrapping Optional types,
terminator results, and ownership rules.

Replace the existing "phi" APIs with a single
SILGenBuilder::createPhi(SILType, ValueOwnershipKind) that handles
cleanup based on phi ownership.

Phis and terminator results are fundamentally different and need to be handled differently everywhere. Remove the confusion where terminator results were generated with a "phi argument" API.
2021-09-07 22:50:46 -07:00
Joe Groff
43506a29a2 SILGen: Emit literal closures at the abstraction level of their context.
Literal closures are only ever directly referenced in the context of the expression they're written in,
so it's wasteful to emit them at their fully-substituted calling convention and then reabstract them if
they're passed directly to a generic function. Avoid this by saving the abstraction pattern of the context
before emitting the closure, and then lowering its main entry point's calling convention at that
level of abstraction. Generalize some of the prolog/epilog code to handle converting arguments and returns
to the correct representation for a different abstraction level.
2021-09-07 11:55:29 -07:00
Rintaro Ishizaki
49547a5378 [NFC][Basic] Import llvm::isa_and_nonnull to 'swift' namespace
Just for convenicence.

* Replace `llvm::isa_and_nonnull` with imported `isa_and_nonnull`
* Repalce some `EXPR && isa<T>(EXPR)` with `isa_and_nonnull<T>(EXPR)`
2021-08-27 11:36:21 -07:00
Holly Borla
86e1014399 Revert " SILGen: Emit literal closures at the abstraction level of their context." 2021-08-18 09:03:23 -07:00
Joe Groff
309500d4bf SILGen: Emit literal closures at the abstraction level of their context.
Literal closures are only ever directly referenced in the context of the expression they're written in,
so it's wasteful to emit them at their fully-substituted calling convention and then reabstract them if
they're passed directly to a generic function. Avoid this by saving the abstraction pattern of the context
before emitting the closure, and then lowering its main entry point's calling convention at that
level of abstraction. Generalize some of the prolog/epilog code to handle converting arguments and returns
to the correct representation for a different abstraction level.
2021-08-16 09:39:19 -07:00
Ben Barham
c54c9c7079 [Gardening] Extract basic source info structs from RawComment.h 2021-04-14 10:05:27 +10:00
Erik Eckstein
ec64f2a255 SILLocation: replace CleanupLocation::get(loc) with CleanupLocation(loc)
No need to have a static get function - the constructor can be used directly.
NFC
2021-01-29 20:28:21 +01:00
Michael Gottesman
c026e95cce [ownership] Extract out SILOwnershipKind from ValueOwnershipKind into its own type and rename Invalid -> Any.
This makes it easier to understand conceptually why a ValueOwnershipKind with
Any ownership is invalid and also allowed me to explicitly document the lattice
that relates ownership constraints/value ownership kinds.
2020-11-10 14:29:11 -08:00
Slava Pestov
47e32d1e0f SILGen: Peephole Conversion::OrigToSubst / Conversion::SubstToOrig 2020-10-11 12:48:30 -04:00
Brent Royal-Gordon
745dbef3ef Use file IDs in generated code
Such as force unwraps, as! casts, etc.
2020-07-13 14:05:13 -07:00
Brent Royal-Gordon
0e569f5d9e Add support for #fileID
This temporarily breaks -enable-experimental-concise-pound-file.

fixup adding #fileID
2020-07-13 14:05:13 -07:00
Brent Royal-Gordon
7f91145efc [NFC] Rename “MagicFileString” -> “FileID”
Doing this NFC renaming first helps clarify the functional changes to come.
2020-07-13 14:05:13 -07:00
Owen Voorhees
45bc578ae5 [SourceManager] Rename line and column APIs for clarity 2020-05-21 12:54:07 -05:00
Michael Gottesman
f3df836652 [ownership] Treat open_existential_box as an interior pointer producting instruction.
This means that it can only have a guaranteed object as an operandand that we
validate that all uses of the result address of open_existential_box occur only
within the lifetime of said object's borrow scope.
2020-03-15 23:21:45 -07:00
John McCall
585c28d0c3 Plumb a result SILType through SILGen's emitTransformedValue.
This fixes an immediate bug with subst-to-orig conversion of
parameter functions that I'm surprised isn't otherwise tested.
More importantly, it preserves valuable information that should
let us handle a much wider variety of variant representations
that aren't necessarily expressed in the AbstractionPattern.
2020-03-12 00:23:13 -04:00
Brent Royal-Gordon
0f476284d1 Use #file string for force-unwrap and force-try
This ensures that -enable-experimental-concise-pound-file affects more of the file names that might be automatically embedded in a binary.
2020-01-10 13:48:45 -08:00
Michael Gottesman
1ddb916b0e [gardening] Eliminate dead variable. 2019-12-18 13:54:11 -08:00