Commit Graph

1699 Commits

Author SHA1 Message Date
swift-ci
64ec60bbd4 Merge pull request #34370 from nate-chandler/concurrency/irgen/partial-apply 2020-10-22 13:54:37 -07:00
Nate Chandler
506473dfba [Async CC] Supported partial application.
The majority of support comes in the form of emitting partial
application forwarders for partial applications of async functions.
Such a partial application forwarder must take an async context which
has been partially populated at the apply site.  It is responsible for
populating it "the rest of the way".  To do so, like sync partial
application forwarders, it takes a second argument, its context, from
which it pulls the additional arguments which were capture at
partial_apply time.

The size of the async context that is passed to the forwarder, however,
can't be known at the apply site by simply looking at the signature of
the function to be applied (not even by looking at the size associated
with the function in the special async function pointer constant which
will soon be emitted).  The reason is that there are an unknown (at the
apply site) number of additional arguments which will be filled by the
partial apply forwarder (and in the case of repeated partial
applications, further filled in incrementally at each level).  To enable
this, there will always be a heap object for thick async functions.
These heap objects will always store the size of the async context to be
allocated as their first element.  (Note that it may be possible to
apply the same optimization that was applied for thick sync functions
where a single refcounted object could be used as the context; doing so,
however, must be made to interact properly with the async context size
stored in the heap object.)

To continue to allow promoting thin async functions to thick async
functions without incurring a thunk, at the apply site, a null-check
will be performed on the context pointer.  If it is null, then the async
context size will be determined based on the signature.  (When async
function pointers become pointers to a constant with a size i32 and a
relative address to the underlying function, the size will be read from
that constant.)  When it is not-null, the size will be pulled from the
first field of the context (which will in that case be cast to
<{%swift.refcounted, i32}>).

To facilitate sharing code and preserving the original structure of
emitPartialApplicationForwarder (which weighed in at roughly 700 lines
prior to this change), a new small class hierarchy, descending from
PartialApplicationForwarderEmission has been added, with subclasses for
the sync and async case.  The shuffling of arguments into and out of the
final explosion that was being performed in the synchronous case has
been preserved there, though the arguments are added and removed through
a number of methods on the superclass with more descriptive names.  That
was necessary to enable the async class to handle these different
flavors of parameters correctly.

To get some initial test coverage, the preexisting
IRGen/partial_apply.sil and IRGen/partial_apply_forwarder.sil tests have
been duplicated into the async folder.  Those tests cases within these
files which happened to have been crashing have each been extracted into
its own runnable test that both verifies that the compiler does not
crash and also that the partial application forwarder behaves correctly.
The FileChecks in these tests are extremely minimal, providing only
enough information to be sure that arguments are in fact squeezed into
an async context.
2020-10-22 12:21:56 -07:00
Andrew Trick
6f2cda1390 Add AccessUseVisitor and cleanup related APIs.
Add AccesssedStorage::compute and computeInScope to mirror AccessPath.

Allow recovering the begin_access for Nested storage.

Adds AccessedStorage.visitRoots().
2020-10-16 15:00:10 -07:00
Andrew Trick
cc0aa2f8b8 Add an AccessPath abstraction and formalize memory access
Things that have come up recently but are somewhat blocked on this:

- Moving AccessMarkerElimination down in the pipeline
- SemanticARCOpts correctness and improvements
- AliasAnalysis improvements
- LICM performance regressions
- RLE/DSE improvements

Begin to formalize the model for valid memory access in SIL. Ignoring
ownership, every access is a def-use chain in three parts:

object root -> formal access base -> memory operation address

AccessPath abstracts over this path and standardizes the identity of a
memory access throughout the optimizer. This abstraction is the basis
for a new AccessPathVerification.

With that verification, we now have all the properties we need for the
type of analysis requires for exclusivity enforcement, but now
generalized for any memory analysis. This is suitable for an extremely
lightweight analysis with no side data structures. We currently have a
massive amount of ad-hoc memory analysis throughout SIL, which is
incredibly unmaintainable, bug-prone, and not performance-robust. We
can begin taking advantage of this verifably complete model to solve
that problem.

The properties this gives us are:

Access analysis must be complete over memory operations: every memory
operation needs a recognizable valid access. An access can be
unidentified only to the extent that it is rooted in some non-address
type and we can prove that it is at least *not* part of an access to a
nominal class or global property. Pointer provenance is also required
for future IRGen-level bitfield optimizations.

Access analysis must be complete over address users: for an identified
object root all memory accesses including subobjects must be
discoverable.

Access analysis must be symmetric: use-def and def-use analysis must
be consistent.

AccessPath is merely a wrapper around the existing accessed-storage
utilities and IndexTrieNode. Existing passes already very succesfully
use this approach, but in an ad-hoc way. With a general utility we
can:

- update passes to use this approach to identify memory access,
  reducing the space and time complexity of those algorithms.

- implement an inexpensive on-the-fly, debug mode address lifetime analysis

- implement a lightweight debug mode alias analysis

- ultimately improve the power, efficiency, and maintainability of
  full alias analysis

- make our type-based alias analysis sensistive to the access path
2020-10-16 15:00:10 -07:00
Robert Widmann
9c879c008e Resolve Virtual Inheritance By Dominance By Being Explicit
Since the alternative is name lookup selecting members from a pure virtual base, it's probably best to be explicit here.
2020-10-14 13:27:21 -07:00
nate-chandler
c9115dc7c5 Merge pull request #34277 from nate-chandler/concurrency/irgen/thread-emission-through-emit-polymorphic
[Async CC] Pull polymorphic parameters from entry point emission.
2020-10-12 14:13:03 -07:00
Nate Chandler
6fce6d9363 [Async CC] Pull poly params from entry point emission.
Previously, EmitPolymorphicParameters dealt directly with an Explosion
from which it pulled values.  In one place, there was a conditional
check for async which handled some cases.  There was however another
place where the polymorphic parameter was pulled directly from the
explosion.  That missed case resulted in attempting to pull a
polymorphic parameter directly from an Explosion which contains only a
%swift.context* per the async calling convention.

Here, those parameters are now pulled from an EntryPointArgumentEmission
subclasses of which are able to provide the relevant definition of what
pulling a parameter means.

rdar://problem/70144083
2020-10-12 10:52:23 -07:00
nate-chandler
d32b9350b2 Merge pull request #34211 from nate-chandler/concurrency/irgen/protocol-witness-methods
[Async CC] Support for protocol witness methods.
2020-10-07 14:37:47 -07:00
Nate Chandler
0a5df673ed [NFC] Deduped async entry point emission code.
Previously the same code was used for loading values from the async
context.  Here, that same code is extracted into a private method.
2020-10-06 17:03:03 -07:00
Nate Chandler
7d74a8614d [Concurrency] Async CC supports witness methods.
Previously, the AsyncContextLayout did not make space for the trailing
witness fields (self metadata and self witness table) and the
AsyncNativeCCEntryPointArgumentEmission could consequently not vend
these fields.  Here, the fields are added to the layout.
2020-10-06 17:03:03 -07:00
Nate Chandler
d5d65b0dff [NFC] Removed unused method. 2020-10-06 12:05:01 -07:00
Nate Chandler
f6bfd416ab [NFC] Use TypeInfo for indirect return storage.
Previously a raw CreateLoad was used, which happened to be fine.  Here,
a TI is used, explicitly clarifying that the indirect return is taken.
2020-10-06 11:58:35 -07:00
Nate Chandler
b90cab6f1b [NFC] Made indexing on AsyncContextLayout private.
Previously the methods for getting the index into the layout were public
and were being used to directly access the underlying buffer.  Here,
that abstraction leakage is fixed and field access is forced to go
through the appropriate methods.
2020-10-06 11:58:27 -07:00
nate-chandler
515f0db4ed Merge pull request #34141 from nate-chandler/concurrency/irgen/signature
[Concurrency] Async CC, part 1.
2020-10-06 07:43:02 -07:00
Nate Chandler
ee88152d6b [Concurrency] First steps towards async CC.
Here, the following is implemented:
- Construction of SwiftContext struct with the fields needed for calling
  functions.
- Allocating and deallocating these swift context via runtime calls
  before calling async functions and after returning from them.
- Storing arguments (including bindings and the self parameter but not
  including protocol fields for witness methods) and returns (both
  direct and indirect).
- Calling async functions.

Additional things that still need to be done:
- protocol extension methods
- protocol witness methods
- storing yields
- partial applies
2020-10-05 20:43:51 -07:00
Joe Groff
a664a33b52 SIL: Add instructions to represent async suspend points.
`get_async_continuation[_addr]` begins a suspend operation by accessing the continuation value that can resume
the task, which can then be used in a callback or event handler before executing `await_async_continuation` to
suspend the task.
2020-10-01 14:21:52 -07:00
Nate Chandler
4cfadfae00 [NFC] Documented IRGenFunction::IndirectReturn. 2020-09-30 18:57:47 -07:00
Andrew Trick
5ae231eaab Rename getFieldNo() to getFieldIndex().
Do I really need to justify this?
2020-09-24 22:44:13 -07:00
Kuba (Brecka) Mracek
afde159521 Drop assert(Atomicity::Atomic) from visitRetainValueAddrInst+visitReleaseValueAddrInst (#33913) 2020-09-11 14:49:55 -07:00
Dan Zheng
bf2ef3934d [AutoDiff] NFC: make LinearFunctionExtractInst inherit UnaryInstructionBase. (#33418)
Remove ad-hoc operand list and operand getters.
2020-08-11 22:20:58 -07:00
zoecarver
5c3ccf5050 [cxx-interop] Temporarily disable emitting debug info for C++ types.
When we try to emit debug info from C++ types we crash because we can't deserialize them. This is a temporary fix to circumnavigate the crash before a real fix can be created.
2020-07-23 12:10:06 -07:00
Michael Gottesman
5e36ae1c7c [sil] Add a forwarding cast called unchecked_value_cast.
Today unchecked_bitwise_cast returns a value with ObjCUnowned ownership. This is
important to do since the instruction can truncate memory meaning we want to
treat it as a new object that must be copied before use.

This means that in OSSA we do not have a purely ossa forwarding unchecked
layout-compatible assuming cast. This role is filled by unchecked_value_cast.
2020-07-09 21:14:32 -07:00
Erik Eckstein
67605553df SIL: a new instruction 'base_addr_for_offset' for field offset calculations.
The ``base_addr_for_offset`` instruction creates a base address for offset calculations.
The result can be used by address projections, like ``struct_element_addr``, which themselves return the offset of the projected fields.
IR generation simply creates a null pointer for ``base_addr_for_offset``.
2020-07-01 15:10:08 +02:00
Vedant Kumar
60ec3f1b90 Fix debug description for cases with multiple items (#32282)
* [SILGenFunction] Don't create redundant nested debug scopes

Instead of emitting:

```
sil_scope 4 { loc "main.swift":6:19 parent 3 }
sil_scope 5 { loc "main.swift":7:3 parent 4 }
sil_scope 6 { loc "main.swift":7:3 parent 5 }
sil_scope 7 { loc "main.swift":7:3 parent 5 }
sil_scope 8 { loc "main.swift":9:5 parent 4 }
```

Emit:

```
sil_scope 4 { loc "main.swift":6:19 parent 3 }
sil_scope 5 { loc "main.swift":7:3 parent 4 }
sil_scope 6 { loc "main.swift":9:5 parent 5 }
```

* [IRGenSIL] Diagnose conflicting shadow copies

If we attempt to store a value with the wrong type into a slot reserved
for a shadow copy, diagnose what went wrong.

* [SILGenPattern] Defer debug description of case variables

Create unique nested debug scopes for a switch, each of its case labels,
and each of its case bodies. This looks like:

```
  switch ... { // Enter scope 1.
    case ... : // Enter scope 2, nested within scope 1.
      <body-1> // Enter scope 3, nested within scope 2.

    case ... : // Enter scope 4, nested within scope 1.
      <body-2> // Enter scope 5, nested within scope 4.
  }
```

Use the new scope structure to defer emitting debug descriptions of case
bindings. Specifically, defer the work until we can nest the scope for a
case body under the scope for a pattern match.

This fixes SR-7973, a problem where it was impossible to inspect a case
binding in lldb when stopped at a case with multiple items.

Previously, we would emit the debug descriptions too early (in the
pattern match), leading to duplicate/conflicting descriptions. The only
reason that the ambiguous description was allowed to compile was because
the debug scopes were nested incorrectly.

rdar://41048339

* Update tests
2020-06-10 13:31:10 -07:00
Dan Zheng
d3b6b89de6 [AutoDiff] Support multiple differentiability result indices in SIL. (#32206)
`DifferentiableFunctionInst` now stores result indices.
`SILAutoDiffIndices` now stores result indices instead of a source index.

`@differentiable` SIL function types may now have multiple differentiability
result indices and `@noDerivative` resutls.

`@differentiable` AST function types do not have `@noDerivative` results (yet),
so this functionality is not exposed to users.

Resolves TF-689 and TF-1256.

Infrastructural support for TF-983: supporting differentiation of `apply`
instructions with multiple active semantic results.
2020-06-05 16:25:17 -07:00
David Zarzycki
eab7cb7d38 [IRGen] NFC: Clean up Alignment type
1) Shrink from 4 bytes to 1 byte.
2) Assert that alignments are power-of-two at run time.
3) Assert that alignments are power-of-two at compile time when possible.
4) Eliminate "isZero"/"no alignment" from the type. Use llvm::Optional.
2020-05-26 10:36:33 -04:00
Joe Groff
f05e063cdb Merge pull request #31799 from jckarter/simple-partial-apply-arm64e
IRGen: "Simple" partial_apply still needs to re-sign the entry point pointer.
2020-05-15 13:28:30 -07:00
Joe Groff
a16c485d28 IRGen: "Simple" partial_apply still needs to re-sign the entry point pointer.
Fixes rdar://problem/63184042
2020-05-15 10:43:09 -07:00
Erik Eckstein
f5a8f600ea SIL: new instructions for copy-on-write support
* a new [immutable] attribute on ref_element_addr and ref_tail_addr
* new instructions: begin_cow_mutation and end_cow_mutation

These new instructions are intended to be used for the stdlib's COW containers, e.g. Array.
They allow more aggressive optimizations, especially for Array.
2020-05-14 08:39:54 +02:00
Joe Groff
1df1f664c9 IRGen: Restore handling of "simple" partial_apply instructions.
Methods and closures use the same convention for the self/context argument, so when a
partial_apply applies a single argument to a method implementation, the closure can be formed
by simply tupling the implementation and self argument together. This doesn't yet cover a lot
of situations the compiler generates, but it prepares IRGen for an IRGen SIL pass that can
take the heavy lifting of partial_apply lowering off of IRGen by reducing more complex closures
into these "simple" cases, eventually reducing the number of partial_apply forwarding thunks and
extra closure allocations generated.
2020-05-11 15:58:46 -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
marcrasi
d067e7e18c [AutoDiff upstream] more IRGen for @differentiable functions (#30688) 2020-03-28 12:27:08 -07:00
ematejska
75691d641e [AutoDiff upstream] Add linear function SIL instructions (#30638)
Add `linear_function` and `linear_function_extract` instructions.

`linear_function` creates a `@differentiable(linear)` function-typed value from
an original function operand and a transpose function operand (optional).

`linear_function_extract` extracts either the original or transpose function
value from a `@differentiable(linear)` function.

Resolves TF-1142 and TF-1143.
2020-03-26 09:41:14 -07:00
Dan Zheng
cc7e9fc39e [AutoDiff upstream] [SIL] Add differentiable function instructions.
Add `differentiable_function` and `differentiable_function_extract`
instructions.

`differentiable_function` creates a `@differentiable` function-typed
value from an original function operand and derivative function operands
(optional).

`differentiable_function_extract` extracts either the original or
derivative function value from a `@differentiable` function.

The differentiation transform canonicalizes `differentiable_function`
instructions, filling in derivative function operands if missing.

Resolves TF-1139 and TF-1140.
2020-03-22 23:53:43 -07:00
Kuba (Brecka) Mracek
ab6533a40f Merge branch 'master' into mracek/arm64e 2020-03-06 15:07:01 -08:00
Andrew Trick
0bbc44c976 Disable !invariant metadata for 'let' variables.
I enabled this recently by piggybacking it in the mega-commit:

commit badc5658bb
Author: Andrew Trick <atrick@apple.com>
Date:   Mon Mar 2 16:23:53 2020

    Fix SIL MemBehavior queries with access markers.

It miscompiles SwiftNIO's NIOPerformanceTester benchmark causing it to
segfault immediately.

We may consider debugging this to reenable it in the future...
<rdar://60068448> Teach IRGen to emit !invariant metadata for 'let' variables

Fixes <rdar://60038603> Swift CI: SwiftNIO_macOS NIOHTTP2_macOS fails
2020-03-04 19:19:04 -08:00
Kuba (Brecka) Mracek
0d400ca310 Merge branch 'master' into mracek/arm64e 2020-03-04 09:36:25 -08:00
Andrew Trick
badc5658bb Fix SIL MemBehavior queries with access markers.
This is in prepration for other bug fixes.

Clarify the SIL utilities that return canonical address values for
formal access given the address used by some memory operation:

- stripAccessMarkers
- getAddressAccess
- getAccessedAddress

These are closely related to the code in MemAccessUtils.

Make sure passes use these utilities consistently so that
optimizations aren't defeated by normal variations in SIL patterns.

Create an isLetAddress() utility alongside these basic utilities to
make sure it is used consistently with the address corresponding to
formal access. When this query is used inconsistently, it defeats
optimization. It can also cause correctness bugs because some
optimizations assume that 'let' initialization is only performed on a
unique address value.

Functional changes to Memory Behavior:

- An instruction with side effects now conservatively still has side
  effects even when the queried value is a 'let'. Let values are
  certainly sensitive to side effects, such as the parent object being
  deallocated.

- Return the correct MemBehavior for begin/end_access markers.
2020-03-03 09:24:18 -08:00
Kuba Mracek
84c4864911 [arm64e] Add Swift compiler support for arm64e pointer authentication 2020-02-27 16:10:31 -08:00
Dan Zheng
a49428ca7c [AutoDiff upstream] Add differentiability_witness_function instruction. (#29765)
The `differentiability_witness_function` instruction looks up a
differentiability witness function (JVP, VJP, or transpose) for a referenced
function via SIL differentiability witnesses.

Add round-trip parsing/serialization and IRGen tests.

Notes:
- Differentiability witnesses for linear functions require more support.
  `differentiability_witness_function [transpose]` instructions do not yet
  have IRGen.
- Nothing currently generates `differentiability_witness_function` instructions.
  The differentiation transform does, but it hasn't been upstreamed yet.

Resolves TF-1141.
2020-02-13 16:55:46 -08:00
Slava Pestov
836a0b9722 IRGen: Remove IRGenModule::CurSourceFile 2020-02-11 18:59:21 -05:00
swift-ci
227485bf02 Merge remote-tracking branch 'origin/master' into master-rebranch 2020-02-10 07:14:14 -08:00
Mishal Shah
f53b1a7ba1 Revert "Emit debug info for generic type aliases. …" 2020-02-09 21:38:45 -08:00
swift-ci
8b58328bc6 Merge remote-tracking branch 'origin/master' into master-rebranch 2020-02-07 17:04:27 -08:00
Adrian Prantl
e932580c8e Emit debug info for generic type aliases.
Before comparing the potential sugared type for equality is needs to be mapped
into the context to resolve generic type parameters to primary archetypes.

<rdar://problem/59238327>
2020-02-07 14:06:08 -08:00
swift-ci
bc5eca8388 Merge remote-tracking branch 'origin/master' into master-rebranch 2020-01-10 16:43:42 -08:00
Vedant Kumar
a83bfabc8b [DebugInfo] Stop relying on asm gadgets to extend variable ranges (#29029)
The 'fake use' asm gadget does not always keep variables alive. E.g., in
rdar://57754659, llvm was unable to preserve two local variables despite
the use of these gadgets. These variables were backed by a LoadInst and
an ExtractValueInst respectively. Instead of emitting shadow copies for
just those kinds of instructions, use shadow copies exclusively. This
may cause more variables to appear in the debugger window before they
are initialized, but should result in fewer variables being dropped.

rdar://57754659
2020-01-10 16:31:51 -08:00
Jonas Devlieghere
4db7f40686 Update for upstream intrinsics change (NFC)
The Intrinsic ID is now an opaque typedef to facilitate splitting up
the enum into target-specific enums.
2020-01-03 10:53:22 -08:00
Raphael Isemann
6ae6447239 Adapt calls to CreateMemSet to LLVM API change
In 1b2842bf902a8b52acbef2425120533b63be5ae3 this API was changed.
It seems the right thing to do is turn this into the new alignment
type by doing MaybeAlign(alignment) which is what this patch does.
2019-12-11 18:28:51 +01:00
Slava Pestov
c8da1583cf IRGen: Correctly use formal type for class downcasts
Fixes <https://bugs.swift.org/browse/SR-11818>, <rdar://problem/57369535>.
2019-11-22 16:39:17 -05:00