Commit Graph

53 Commits

Author SHA1 Message Date
Robert Widmann
ab44a07045 Convert DeclContext Parameters to their Associated Generic Signatures Instead 2022-03-07 22:54:23 -08:00
Robert Widmann
d6186c9cfb Add a DeclContext Parameter to Opened Archetype Construction
This ensures that opened archetypes always inherit any outer generic parameters from the context in which they reside. This matters because class bounds may bind generic parameters from these outer contexts, and without the outer context you can wind up with ill-formed generic environments like

<τ_0_0, where τ_0_0 : C<T>, τ_0_0 : P>

Where T is otherwise unbound because there is no entry for it among the generic parameters of the environment's associated generic signature.
2022-03-07 22:54:22 -08:00
Holly Borla
a7fa4695b2 [GenericSignature] Don't allow conformance requirements with explicit
existential types.
2022-01-13 19:30:44 -08:00
Pavel Yaskevich
4860f90fd7 [SIL] Add new flag to SILFunction - IsDistributed
Determines whether given SILFunction represents a distributed
method or its thunk.
2021-12-17 10:52:52 -08:00
Robert Widmann
22405cefea Plumb the "Is Type Sequence" Bit Through the Surface AST 2021-11-08 13:48:30 -08:00
Slava Pestov
f38f25a3de AST: Factor out AbstractGenericSignatureRequest into a new buildGenericSignature() function
This is slightly cleaner.
2021-10-30 00:35:59 -04:00
Robert Widmann
1329f3cfbd [NFC] Lift getGenericEnvironment() into GenericSignature 2021-07-22 23:33:02 -07:00
Robert Widmann
d86551de67 Lift Requirement and Parameter Accessors up to GenericSignature
Start treating the null {Can}GenericSignature as a regular signature
with no requirements and no parameters. This not only makes for a much
safer abstraction, but allows us to simplify a lot of the clients of
GenericSignature that would previously have to check for null before
using the abstraction.
2021-07-22 23:27:05 -07:00
Erik Eckstein
6ec788ff09 SIL: remove the SILOpenedArchetypesTracker
Instead, put the archetype->instrution map into SIlModule.

SILOpenedArchetypesTracker tried to maintain and reconstruct the mapping locally, e.g. during a use of SILBuilder.
Having a "global" map in SILModule makes the whole logic _much_ simpler.

I'm wondering why we didn't do this in the first place.

This requires that opened archetypes must be unique in a module - which makes sense. This was the case anyway, except for keypath accessors (which I fixed in the previous commit) and in some sil test files.
2021-04-14 08:36:10 +02:00
Meghana Gupta
ad02d91f50 Fix a minor issue in ExistentialSpecializer for OSSA (#36180)
While cloning arguments for existential specializer, do not create copy
for object types. Currently, for guaranteed parameter types it
unnecessarily creates a copy and cleans it up with a destroy. The
discrepency is seen when cloning an instruction like open_existential_ref
which was previously using guaranteed operand and had guaranteed
forwarding ownership, is now replaced to have the owned copy as its
operand during cloning.
2021-03-24 15:43:09 -07:00
Andrew Trick
f24658fe9e Fix ExistentialSpecializer to detect repeated specialization.
Add handling for repeated specialization and remove an incorrect
assertion in
ExistentialTransform::createExistentialSpecializedFunctionName():
assert(!F->getModule().hasFunction(MangledName));

The ExistentialSpecializer replaces the original function with a thunk
to a newly specialized function. Repeated attempts to specialize the
same function bail out because the pass avoids reoptimizing thunks.

Ultimately, the intention is that the thunks will all be inlined into
their callers. Dead function elimination will then remove the
thunks. If the original function was itself a specialization, then the
GenericSpecialize may regenerate the original again in non-thunk form.

Consider the pipeline:
- GenericSpecializer
- ExistentialSpecializer
- Inliner
- DeadFunctionElimination
- GenericSpecializer
- ExistentialSpecializer

This is not a problem with the ExistentialSpecializer itself. In fact,
it may respecialize the same function in different ways, for example
specializing more of the arguments each time. Each different
specialization transforms the original function into a thunk, that
thunk is inlined, and the newly specialized code is called directly.

Of course, the ExistentialSpecializer may also decide to respecialize
a function the same way as before. When doing this, it still needs to
produce the thunk, which was dead function eliminated since last
specialization of the same function. However, it can simply reuse the
previous specialization by performing a name lookup first.

The design problem is that the SILModule makes assumptions about
duplicate symbols when managing symbol memory but does not provide a
robust way to protect against such duplicate symbols. That will be
improved in a separate commit.

Minimal fix for: rdar://72135512 The ExistentialSpecializer crashes
2020-12-14 16:15:23 -08: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
Nate Chandler
94b5f76654 Revert "[SIL] Add SILFunctionType flag for async."
This reverts commit 9b8828848d.
2020-08-25 13:37:26 -07:00
Nate Chandler
9b8828848d [SIL] Add SILFunctionType flag for async. 2020-08-19 11:29:58 -07:00
Michael Gottesman
6017ef5d2e [ownership] Begin updating existential specializer.
I can not update all of the tests until I fix SILCombine and we move the
ownership lowering to right before the existential specializer (the sil tests
depend on the former and the swift tests depend on both). But this at least
begins updating the tests and ensures that the updates do not break the pass
when we run it on non-ossa code.
2020-08-04 14:36:24 -07:00
Luciano Almeida
59add19684 Merge pull request #32056 from LucianoPAlmeida/minor-typos
[NFC][test] Minor typo corrections on test messages
2020-06-17 07:14:27 -03:00
Luciano Almeida
6d3f53a417 [NFC][test] Minor corrections on test messages 2020-06-05 06:36:09 -03:00
Meghana Gupta
4804616fc1 Fix an edge case in ExistentialSpecializer
ExistentialSpecializer could be building the function type from a
witness_method. We cannot attach a witnessProtocolConformance to the
newly specialized thin function.
2020-06-02 10:13:28 -07:00
Arnold Schwaighofer
147144baa6 SIL: Thread type expansion context through to function convention apis
This became necessary after recent function type changes that keep
substituted generic function types abstract even after substitution to
correctly handle automatic opaque result type substitution.

Instead of performing the opaque result type substitution as part of
substituting the generic args the underlying type will now be reified as
part of looking at the parameter/return types which happens as part of
the function convention apis.

rdar://62560867
2020-05-04 13:53:30 -07:00
Erik Eckstein
0c3e6e2291 FunctionSignatureOpts: fix a crash due to a missing argument declaration
The existential -> generic transformation in FSO didn't preserve the argument declaration.
This caused an assert to hit in a later FSO transformation.

rdar://problem/61206439
https://bugs.swift.org/browse/SR-12487
2020-04-15 20:52:30 +02:00
John McCall
ceff414820 Distinguish invocation and pattern substitutions on SILFunctionType.
In order to allow this, I've had to rework the syntax of substituted function types; what was previously spelled `<T> in () -> T for <X>` is now spelled `@substituted <T> () -> T for <X>`.  I think this is a nice improvement for readability, but it did require me to churn a lot of test cases.

Distinguishing the substitutions has two chief advantages over the existing representation.  First, the semantics seem quite a bit clearer at use points; the `implicit` bit was very subtle and not always obvious how to use.  More importantly, it allows the expression of generic function types that must satisfy a particular generic abstraction pattern, which was otherwise impossible to express.

As an example of the latter, consider the following protocol conformance:

```
protocol P { func foo() }
struct A<T> : P { func foo() {} }
```

The lowered signature of `P.foo` is `<Self: P> (@in_guaranteed Self) -> ()`.  Without this change, the lowered signature of `A.foo`'s witness would be `<T> (@in_guaranteed A<T>) -> ()`, which does not preserve information about the conformance substitution in any useful way.  With this change, the lowered signature of this witness could be `<T> @substituted <Self: P> (@in_guaranteed Self) -> () for <A<T>>`, which nicely preserves the exact substitutions which relate the witness to the requirement.

When we adopt this, it will both obviate the need for the special witness-table conformance field in SILFunctionType and make it far simpler for the SILOptimizer to devirtualize witness methods.  This patch does not actually take that step, however; it merely makes it possible to do so.

As another piece of unfinished business, while `SILFunctionType::substGenericArgs()` conceptually ought to simply set the given substitutions as the invocation substitutions, that would disturb a number of places that expect that method to produce an unsubstituted type.  This patch only set invocation arguments when the generic type is a substituted type, which we currently never produce in type-lowering.

My plan is to start by producing substituted function types for accessors.  Accessors are an important case because the coroutine continuation function is essentially an implicit component of the function type which the current substitution rules simply erase the intended abstraction of.  They're also used in narrower ways that should exercise less of the optimizer.
2020-03-07 16:25:59 -05:00
Michael Gottesman
68960005f6 [gardening] Remove unused variable. 2019-12-18 13:54:11 -08:00
Andrew Trick
7d0a772542 Fix ExistentialSpecializer: inherited conformance
The ExistentialSpecializer incorrectly assumed that an existential's conformances match an opened archetype. They don't. Opened archetypes strip inherited conformances per the ABI for generic argument passing. Existential values retain those inherited conformances (for some inexplicable reason).

- Rename ASTContext::getExistentialSignature() to
  getOpenedArchetypeSiganture() because it was doing exactly the wrong
  thing for existentials.

- Fix ConcreteExistentialInfo to produce the correct SubstitutionMap.

- Fix ExistentialSpecializer to generate the correct conformances for
  init_existential by adding a collectExistentialConformances() helper.

Fixes <rdar://problem/57025861> "Assertion failed: (conformances.size() == numConformanceRequirements)" in ExistentialSpecializer on inlined code
2019-11-22 01:56:20 -08:00
Arnold Schwaighofer
8aaa7b4dc1 SILOptimizer: Pipe through TypeExpansionContext 2019-11-11 14:21:52 -08:00
Robert Widmann
37e82a6133 [NFC] getWitnessMethodConformanceOrNone -> getWitnessMethodConformanceOrInvalid 2019-10-29 16:56:20 -07:00
Joe Groff
03c7919b4a SIL: Add fields to SILFunctionType for substituted function types.
https://forums.swift.org/t/improving-the-representation-of-polymorphic-interfaces-in-sil-with-substituted-function-types/29711

This prepares SIL to be able to more accurately preserve the calling convention of
polymorphic generic interfaces by letting the type system represent "substituted function types".
We add a couple of fields to SILFunctionType to support this:

- A substitution map, accessed by `getSubstitutions()`, which maps the generic signature
  of the function to its concrete implementation. This will allow, for instance, a protocol
  witness for a requirement of type `<Self: P> (Self, ...) -> ...` for a concrete conforming
  type `Foo` to express its type as `<Self: P> (Self, ...) -> ... for <Foo>`, preserving the relation
  to the protocol interface without relying on the pile of hacks that is the `witness_method`
  protocol.

- A bool for whether the generic signature of the function is "implied" by the substitutions.
  If true, the generic signature isn't really part of the calling convention of the function.
  This will allow closure types to distinguish a closure being passed to a generic function, like
  `<T, U> in (*T, *U) -> T for <Int, String>`, from the concrete type `(*Int, *String) -> Int`,
  which will make it easier for us to differentiate the representation of those as types, for
  instance by giving them different pointer authentication discriminators to harden arm64e
  code.

This patch is currently NFC, it just introduces the new APIs and takes a first pass at updating
code to use them. Much more work will need to be done once we start exercising these new
fields.

This does bifurcate some existing APIs:

- SILFunctionType now has two accessors to get its generic signature.
  `getSubstGenericSignature` gets the generic signature that is used to apply its
  substitution map, if any. `getInvocationGenericSignature` gets the generic signature
  used to invoke the function at apply sites. These differ if the generic signature is
  implied.
- SILParameterInfo and SILResultInfo values carry the unsubstituted types of the parameters
  and results of the function. They now have two APIs to get that type. `getInterfaceType`
  returns the unsubstituted type of the generic interface, and
  `getArgumentType`/`getReturnValueType` produce the substituted type that is used at
  apply sites.
2019-10-25 13:38:51 -07:00
Jordan Rose
171ff440fc Remove swift::reversed in favor of llvm::reverse (#27610)
The former predates the latter, but we don't need it anymore! The
latter has more features anyway.

No functionality change.
2019-10-10 17:16:09 -07:00
Andrew Trick
bddc69c8a6 Organize SILOptimizer/Utils headers. Remove Local.h.
The XXOptUtils.h convention is already established and parallels
the SIL/XXUtils convention.

New:
- InstOptUtils.h
- CFGOptUtils.h
- BasicBlockOptUtils.h
- ValueLifetime.h

Removed:
- Local.h
- Two conflicting CFG.h files

This reorganization is helpful before I introduce more
utilities for block cloning similar to SinkAddressProjections.

Move the control flow utilies out of Local.h, which was an
unreadable, unprincipled mess. Rename it to InstOptUtils.h, and
confine it to small APIs for working with individual instructions.
These are the optimizer's additions to /SIL/InstUtils.h.

Rename CFG.h to CFGOptUtils.h and remove the one in /Analysis. Now
there is only SIL/CFG.h, resolving the naming conflict within the
swift project (this has always been a problem for source tools). Limit
this header to low-level APIs for working with branches and CFG edges.

Add BasicBlockOptUtils.h for block level transforms (it makes me sad
that I can't use BBOptUtils.h, but SIL already has
BasicBlockUtils.h). These are larger APIs for cloning or removing
whole blocks.
2019-10-02 11:34:54 -07:00
Robert Widmann
5a8d0744c3 [NFC] Adopt TypeBase-isms for GenericSignature
Structurally prevent a number of common anti-patterns involving generic
signatures by separating the interface into GenericSignature and the
implementation into GenericSignatureBase.  In particular, this allows
the comparison operators to be deleted which forces callers to
canonicalize the signature or ask to compare pointers explicitly.
2019-09-30 14:04:36 -07:00
Adrian Prantl
5b92814a0e Debug Info: Add missing debug info propagation to SILCloner.
While tightening the requirements of the debug info generator in
IRGenSIL I noticed that SILCloner didn't correctly transfer variable
debug info on alloc_box and alloc_stack instructions. In order to make
these mistakes easier to find I added an assertion to SILBuilder and
fixed all issues uncovered by that assertion, too.

The result is a moderate increase in debug info coverage in optimized code.

On stdlib/public/core/OSX/x86_64/Swift.o "variables with location"
increases from 60134 to 60299.
2019-09-24 14:10:25 -07:00
Slava Pestov
d434188157 SIL: Refactor TypeConverter to not require a SILModule
This mostly requires changing various entry points to pass around a
TypeConverter instead of a SILModule. I've left behind entry points
that take a SILModule for a few methods like SILType::subst() to
avoid creating even more churn.
2019-09-06 21:50:15 -04:00
Slava Pestov
1e94466bcc AST: Replace GenericSignature::createGenericEnvironment() with getGenericEnvironment()
This memoizes the result, which is fine for all callers; the only
exception is open existential types where each new open existential
now explicitly gets a unique generic environment, allocated by
calling GenericEnvironment::getIncomplete().
2019-09-06 17:16:03 -04:00
Doug Gregor
0e2bb0fbe2 Prune includes of GenericSignatureBuilder.h. 2019-08-26 09:54:20 -07:00
Doug Gregor
25fc798fb6 [Existential specializer] Switch to abstract generic signature request. 2019-08-26 09:54:19 -07:00
Joe Groff
89b334e488 Handle indirect class-constrained arguments in the existential specializer.
The code previously assumed that arguments of class constrained existential type were always passed
directly, causing crashes when they weren't. Fixes rdar://problem/54322849.
2019-08-20 13:26:11 -07:00
Andrew Trick
daa82bc783 Fix ExistentialSpecializer to correctly cleanup storage.
Handle calling conventions and cleanups in all the places (hopefully).
- when ExistentialSpecializer copies the specialized concrete arg into the
original existential value
- when ExistentialSpecializer generates a think
- when SILCombine substitutes concrete values in place of the opened
existential.

One particularly nasty problem is the existential boxes need to be
destroyed. It is not ok to simply destroy their value. The "leaks"
tool does not catch this problem.

Ownership SIL will make this all much more robust.

Fixes <rdar://problem/50595630> Multiple leaks detected - Swift Perf
2019-05-23 17:20:34 -07:00
Andrew Trick
a003afbdae [NFC] Run clang-format on ExistentialTransform.
This reindented a lot of the code. It only ran on the function that I
modified.
2019-05-23 17:20:34 -07:00
Andrew Trick
dddfef1fc8 [NFC] Cleanup ExistentialSpecializerCloner.
Factor the code a bit and follow some best practices so that it's
easier for me to work with in preparation for a bug fix.
2019-05-23 17:20:34 -07:00
Andrew Trick
1ada10817b ExistentialSpecializer debug info accuracy.
Minor drive-by fix. Use best practice when generating debug locations.

Use the scope and location from the insertion point. But since we
can't attach a return location to a normal instruction, use a compiler
generated placeholder.
2019-05-23 17:20:34 -07:00
Slava Pestov
472787bab7 SIL: isNonThrowing parameter of SILBuilder::create{Begin,}Apply() defaults to false
Also remove the overload of createApply() that does not take a SubstitutionMap.
It accomplishes nothing except creating ambiguity.
2019-04-25 22:27:38 -04:00
Slava Pestov
8915f96e3e SIL: Replace SILType::isTrivial(SILModule) with isTrivial(SILFunction) 2019-03-12 01:16:04 -04:00
Slava Pestov
1944254253 SIL: Use SILFunction type lowering APIs in various places 2019-03-01 02:07:16 -05:00
Raj Barik
0070730e5a Perform ExistentialSpecializer when SoleConformingType is known 2019-01-07 14:47:39 -08:00
Michael Gottesman
23378cc16f [sil] Rename QualifiedOwnership => Ownership.
Done using Xcode's refactoring engine.
2018-12-16 15:21:52 -08:00
Joe Groff
89979137fc Push ArchetypeType's API down to subclasses.
And clean up code that conditionally works only with certain kinds of archetype along the way.
2018-12-12 19:45:40 -08:00
Raj Barik
c4df82baa8 ExistentialTransform fixes for swiftpm bugs and enable existential-specializer in sil-opt 2018-11-30 14:29:54 -08:00
Arnold Schwaighofer
7e32c68e1d Add new SIL instruction for calling dynamically_replaceable funtions
%0 = dynamic_function_ref @dynamically_replaceable_function
  apply %0()
  Calls a [dynamically_replaceable] function.

  %0 = prev_dynamic_function_ref @dynamic_replacement_function
  apply %0
  Calls the previous implementation that dynamic_replacement_function
  replaced.
2018-11-06 09:53:22 -08:00
Arnold Schwaighofer
5f4e183302 Add [dynamically_replacable] to SILFunctions
'dynamic' functions are marked as [dynamically_replaceable].
2018-11-06 09:53:21 -08:00
Andrew Trick
c6865c0dff Merge pull request #19786 from atrick/silcloner-cleanup
SILCloner and SILInliner rewrite.
2018-10-11 14:23:32 -07:00
Raj Barik
97e9dde6d7 Fix ExistentialSpecializer for cases when the argument is an ArchetypeType 2018-10-09 16:31:52 -07:00