Commit Graph

554 Commits

Author SHA1 Message Date
Michael Gottesman
5590c7b526 [sil] Add a move_value instruction.
This is a new instruction that can be used by SILGen to perform a semantic move
in between two entities that are considered separate variables at the AST
level. I am going to use it to implement an experimental borrow checker.

This PR contains the following:

1. I define move_value, setup parsing, printing, serializing, deserializing,
   cloning, and filled in all of the visitors as appropriate.
2. I added createMoveValue and emitMoveValueOperation SILBuilder
   APIs. createMoveValue always creates a move and asserts is passed a trivial
   type. emitMoveValueOperation in contrast, will short circuit if passed a
   trivial value and just return the trivial value.
3. I added IRGen tests to show that we can push this through the entire system.

This is all just scaffolding for the instruction to live in SIL land and as of
this PR doesn't actually do anything.
2021-09-12 11:07:42 -07:00
eeckstein
c0485b81be Merge pull request #39203 from eeckstein/fix-serialization
Serialization: include global variables in the worklist-processing
2021-09-09 07:26:16 +02:00
Erik Eckstein
fa8d7828b3 Serialization: include global variables in the worklist-processing
It's not sufficient to first serialize all functions and then serialize all globals, because a function can be referenced from the initializer expression of a global.
Therefore the worklist processing must include both, functions and globals.

This fixes a crash in the serializer, which is exposed through cross-module-optimization.

https://bugs.swift.org/browse/SR-15162
rdar://82827256
2021-09-08 17:10:33 +02:00
Andrew Trick
33fecc9b21 Serialize SIL forwarding ownership on terminators. 2021-09-07 10:20:14 -07:00
Min-Yih Hsu
343d842394 [SIL][DebugInfo] PATCH 3/3: Deprecate debug_value_addr SIL instruciton
This patch removes all references to DebugValueAddrInst class and
debug_value_addr instruction in textual SIL files.
2021-08-31 12:01:04 -07:00
Nate Chandler
f3b7706329 [SIL] Added defined flag to begin_borrow.
The new flag will be used to track whether a borrow scope corresponds to
a source-level lexical scope.  Here, the flag is just added to the
instruction and represented in textual and serialized SIL.
2021-08-25 16:41:49 -07:00
Azoy
20cc067844 [AST] Introduce BuiltinProtocolConformance 2021-07-27 23:49:27 -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
Andrew Trick
c4f1f56ea7 Add Builtin.hopToActor
SILGen this builtin to a mandatory hop_to_executor with an actor type
operand.

e.g.

    Task.detached {
      Builtin.hopToActor(MainActor.shared)
      await suspend()
    }

Required to fix a bug in _runAsyncMain.
2021-06-13 23:44:30 -07:00
Saleem Abdulrasool
25f437e17d mark some switches as covered (NFCI)
Unfortunately, MSVC does not detect covered switches as clang.  Mark
some of the switches as covered to avoid an unnecessary warning from
MSVC.
2021-06-05 15:30:25 -07:00
Doug Gregor
e77a27e8ed [Concurrency] Introduce runtime detection of data races.
Through various means, it is possible for a synchronous actor-isolated
function to escape to another concurrency domain and be called from
outside the actor. The problem existed previously, but has become far
easier to trigger now that `@escaping` closures and local functions
can be actor-isolated.

Introduce runtime detection of such data races, where a synchronous
actor-isolated function ends up being called from the wrong executor.
Do this by emitting an executor check in actor-isolated synchronous
functions, where we query the executor in thread-local storage and
ensure that it is what we expect. If it isn't, the runtime complains.
The runtime's complaints can be controlled with the environment
variable `SWIFT_UNEXPECTED_EXECUTOR_LOG_LEVEL`:

  0 - disable checking
  1 - warn when a data race is detected
  2 - error and abort when a data race is detected

At an implementation level, this introduces a new concurrency runtime
entry point `_checkExpectedExecutor` that checks the given executor
(on which the function should always have been called) against the
executor on which is called (which is in thread-local storage). There
is a special carve-out here for `@MainActor` code, where we check
against the OS's notion of "main thread" as well, so that `@MainActor`
code can be called via (e.g.) the Dispatch library's
`DispatchQueue.main.async`.

The new SIL instruction `extract_executor` performs the lowering of an
actor down to its executor, which is implicit in the `hop_to_executor`
instruction. Extend the LowerHopToExecutor pass to perform said
lowering.
2021-04-12 15:19:51 -07:00
Slava Pestov
4769f215e3 Merge pull request #36224 from slavapestov/reasync-sil-codegen
SIL: Preliminary support for 'apply [noasync]' calls
2021-03-05 12:46:55 -05:00
Slava Pestov
7ccc41a7b7 SIL: Preliminary support for 'apply [noasync]' calls
Refactor SILGen's ApplyOptions into an OptionSet, add a
DoesNotAwait flag to go with DoesNotThrow, and sink it
all down into SILInstruction.h.

Then, replace the isNonThrowing() flag in ApplyInst and
BeginApplyInst with getApplyOptions(), and plumb it
through to TryApplyInst as well.

Set the flag when SILGen emits a sync call to a reasync
function.

When set, this disables the SIL verifier check against
calling async functions from sync functions.

Finally, this allows us to add end-to-end tests for
rdar://problem/71098795.
2021-03-04 22:41:46 -05:00
Andrew Trick
e0a440c036 Add a poison flag to SIL destroy_value.
When the IRGen side is implemented, this will overwrite shadow debug
variables with a poison sentinel for all references within the value.
2021-03-04 17:26:18 -08:00
Richard Wei
e494df2ee6 [AutoDiff] Add differentiability kind to differentiability witnesses and mangle them.
Differentiability witnesses are now keyed by the original function name, the differentiability kind, and the autodiff config.

Updated SIL syntax:
```
differentiability-kind ::= 'forward' | 'reverse' | 'normal' | 'linear'
sil-differentiability-witness ::=
    'sil_differentiability_witness'
    sil-linkage?
    '[' differentiability-kind ']'
    '[' 'parameters' sil-differentiability-witness-function-index-list ']'
    '[' 'results' sil-differentiability-witness-function-index-list ']'
    generic-parameter-clause?
    sil-function-name ':' sil-type
    sil-differentiability-witness-body?
sil-instruction ::=
    'differentiability_witness_function'
    '[' sil-differentiability-witness-function-kind ']'
    '[' differentiability-kind ']'
    '[' 'parameters' sil-differentiability-witness-function-index-list ']'
    '[' 'results' sil-differentiability-witness-function-index-list ']'
    generic-parameter-clause?
    sil-function-name ':' sil-type
```
```console
sil_differentiability_witness [reverse] [parameters 0 1] [results 0] <T where T: Differentiable> @foo : <T> $(T) -> T
differentiability_witness_function [vjp] [reverse] [parameters 0] [results 0] <T where T: Differentiable> @foo : $(T) -> T
```

New mangling:
```swift
  global ::= global generic-signature? 'WJ' DIFFERENTIABILITY-KIND INDEX-SUBSET 'p' INDEX-SUBSET 'r' // differentiability witness
```
```console
$s13test_mangling3fooyS2f_S2ftFWJrSpSr ---> reverse differentiability witness for test_mangling.foo(Swift.Float, Swift.Float, Swift.Float) -> Swift.Float with respect to parameters {0} and results {0}
```

Resolves rdar://74380324.
2021-02-17 18:27:42 -05:00
Erik Eckstein
542a378436 SIL: add FunctionRefInst::getReferencedFunction()
If we know that we have a FunctionRefInst (and not another variant of FunctionRefBaseInst), we know that getting the referenced function will not be null (in contrast to FunctionRefBaseInst::getReferencedFunctionOrNull).

NFC
2021-02-09 19:56:43 +01:00
Dan Zheng
126f1ac6fb [AutoDiff] Disable differentiable_function_extract explicit type as… (#35239)
`differentiability_function_extract` instruction has an optional explicit
extractee type. This is currently used by TypeSubstCloner and the
LoadableByAddress transform to rewrite `differentiability_function_extract`
instructions while preserving `@differentiable` function type invariants.

There is an assertion that `differentiability_function_extract` instructions do
not have explicit extractee types outside of canonical/lowered SIL. However,
this does not handle the SIL deserialization case above: when a function
containing a `differentiable_function_extract` instruction with an explicit type
is deserialized into a raw SIL module (which happens when optimizations are
enabled).

Removing the assertion unblocks this encountered use case.

A more robust longer-term solution may be to change SIL `@differentiable`
function types to explicitly store component original/JVP/VJP function types.

Also fix `differentiable_function_extract` extractee type serialization.

Resolves SR-14004.
2021-01-04 18:40:11 -05:00
Slava Pestov
a2dbdecdab SIL: Refactor get_async_continuation[_addr] to return a RawUnsafeContinuation 2020-12-01 20:04:09 -05:00
Michael Gottesman
611284fcc2 [sil] Element shadowing of SILInstruction::getKind() by renaming MarkUninitializedInst::get{,MarkUninitialized}Kind().
Interestingly this problem can only occur if one invokes
MarkUninitializedInst::getKind() directly. Once our instruction is just a
SILInstruction, we call the appropriate method so we didn't notice it.

I used Xcode's refactoring functionality to find all of the invocation
locations.
2020-11-17 21:25:57 -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
Michael Gottesman
f36e8561f1 [ownership] Use a new ADT SwitchEnumBranch instead of SwitchEnumInstBase for generic operations on SwitchEnum{,Addr}Inst.
I have a need to have SwitchEnum{,Addr}Inst have different base classes
(TermInst, OwnershipForwardingTermInst). To do this I need to add a template to
SwitchEnumInstBase so I can switch that BaseTy. Sadly since we are using
SwitchEnumInstBase as an ADT type as well as an actual base type for
Instructions, this is impossible to do without introducing a template in a ton
of places.

Rather than doing that, I changed the code that was using SwitchEnumInstBase as
an ADT to instead use a proper ADT SwitchEnumBranch. I am happy to change the
name as possible see fit (maybe SwitchEnumTerm?).
2020-11-08 19:52:02 -08:00
Alejandro Alonso
424802fb34 Revert SE-0283 (#34492)
Reverted despite build failures.
2020-10-29 17:32:06 -07:00
Erik Eckstein
f18a9b8ee8 [Concurrency] SIL: add hop_to_executor instruction
This instructions ensures that all instructions, which need to run on the specified executor actually run on that executor.
For details see the description in SIL.rst.
2020-10-28 18:17:43 +01:00
Azoy
f21a306ae5 [AST] Introduce BuiltinProtocolConformance 2020-10-22 18:24:27 -04:00
Alexis Laferrière
e509d6883a Revert "[Sema] Fix availability checking in inlinable code" 2020-10-14 10:52:11 -07:00
Alexis Laferrière
9249186b15 Merge pull request #33855 from xymus/availability-inlinable
[Sema] Fix availability checking in inlinable code
2020-10-13 09:14:57 -07:00
Arnold Schwaighofer
2a2cf91dcd Add support for marking a _specialize attribute as SPI
```
  @_specialize(exported: true, spi: SPIGroupName, where T == Int)
  public func myFunc() { }
```

The specialized entry point is only visible for modules that import
using `_spi(SPIGroupName) import ModuleDefiningMyFunc `.

rdar://64993425
2020-10-12 09:19:29 -07:00
Arnold Schwaighofer
b994bf3191 Add support for _specialize(exported: true, ...)
This attribute allows to define a pre-specialized entry point of a
generic function in a library.

The following definition provides a pre-specialized entry point for
`genericFunc(_:)` for the parameter type `Int` that clients of the
library can call.

```
@_specialize(exported: true, where T == Int)
public func genericFunc<T>(_ t: T) { ... }
```

Pre-specializations of internal `@inlinable` functions are allowed.

```
@usableFromInline
internal struct GenericThing<T> {
  @_specialize(exported: true, where T == Int)
  @inlinable
  internal func genericMethod(_ t: T) {
  }
}
```

There is syntax to pre-specialize a method from a different module.

```
import ModuleDefiningGenericFunc

@_specialize(exported: true, target: genericFunc(_:), where T == Double)
func prespecialize_genericFunc(_ t: T) { fatalError("dont call") }

```

Specially marked extensions allow for pre-specialization of internal
methods accross module boundries (respecting `@inlinable` and
`@usableFromInline`).

```
import ModuleDefiningGenericThing
public struct Something {}

@_specializeExtension
extension GenericThing {
  @_specialize(exported: true, target: genericMethod(_:), where T == Something)
  func prespecialize_genericMethod(_ t: T) { fatalError("dont call") }
}
```

rdar://64993425
2020-10-12 09:19:29 -07:00
Alexis Laferrière
39ee5916bd [SIL] Don't print availability for unreachable/unavailable functions 2020-10-09 10:40:21 -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
Andrew Trick
5ae231eaab Rename getFieldNo() to getFieldIndex().
Do I really need to justify this?
2020-09-24 22:44:13 -07:00
Michael Gottesman
4fa57aef13 [serialization] Refactor from large SILInstruction loop, writeNoOperandLayout handler.
NFC.
2020-09-04 18:03:33 -07:00
Yuta Saito
992c383023 [Serialization] Serialize hasCReferences to keep linkage
hasCReferences is used to determine that the function is externally
available. If a function has @_cdecl and not used from anywhere in Swift
side code, it will be emitted due to its hasCReferences. But if the
attribute is not restored from sib, it won't be emitted even if it's
used externally. So we need to serialize the attribute.
2020-08-29 02:21:49 +09:00
Nate Chandler
4145ef7a12 Revert "[SIL] Add flag to SILFunction to indicate async."
This reverts commit 6b28c2fe89.
2020-08-19 11:29:16 -07:00
Slava Pestov
4b8bbf7434 Merge pull request #33279 from kateinoigakukun/katei/serialize-subclass-scope
[Serialization] Serialize subclassScope to keep linkage
2020-08-12 15:33:20 -04:00
Max Desiatov
f74502ee9d Merge pull request #33325 from kateinoigakukun/katei/sort-diff-wt-serialization
[Serialization] Serialize Differentiability WT index sorted
2020-08-12 17:10:47 +01: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
Yuta Saito
0ce2810144 [Serialization] Serialize subclassScope to keep linkage
subclassScope was always set as NotApplicable when deserialized but we
need to serialize and deserialize it to keep correct linkage when using
SIB

```swift
open class Visitor {
    public func visit() {
        visitExprImpl()
    }
    @_optimize(none)
    private func visitExprImpl() {
    }
}
```

In this case, `visitExprImpl` is private but subclassScope is External.
So it should be lowered as an external function at LLVM IR level.

But once it's serialized into SIB, subclassScope of `visitExprImpl` was
deserialized as NotApplicable because it was not serialized. This
mismatch makes `visitExprImpl` lowered as an internal function at LLVM
IR level.

So `subclassScope` should be serialized.
2020-08-08 14:28:12 +09:00
Yuta Saito
d913e57d84 [Serialization] Serialize Differentiability WT index sorted
When there are sil_property and sil_differentiability_witness at once,
serialized file couldn't be deserialized because it's index table is
serialized un-sortedly but deserializer assumes that contents of table
index are sorted.

This patch fixes the un-sorted serialization and adds test case to
ensure that table index contents can be deserialized
2020-08-07 08:49:26 +09:00
Erik Eckstein
755f6aa2e4 AST, SIL: Remove UTF16 encoding from StringLiteralExpr and StringLiteralInst
The UTF16 encoding is not used (anymore). I think it became obsolete with the switch to the UTF8 String representation.
2020-08-06 19:09:09 +02:00
Nate Chandler
6b28c2fe89 [SIL] Add flag to SILFunction to indicate async.
Includes boilerplate to parse and print as well as to serialize and
deserialize.
2020-08-05 16:22:48 -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
Erik Eckstein
fce7fdc3da SIL: serialization of initializers of global variables.
This is needed for cross-module optimization: it enables constant folding of global let variables which are defined in another module.
2020-06-22 16:49:26 +02:00
Joe Groff
04c8f0df42 IRGen: Don't reify internal vtable entries that are marked overridden.
Private and internal classes shouldn't have ABI constraints on their concrete vtable layout, so if methods
don't have overrides in practice, we can elide their vtable entries.
2020-06-12 11:59:24 -07:00
David Zarzycki
e077b6ffd9 [SIL] NFC: Make SILVTable follow C++ and LLVM best practices
1) Convert the `Entry` type to a class with getters/setters
2) Use llvm::TrailingObjects
3) Use llvm::PointerIntPair
2020-06-11 07:51:42 -04:00
David Zarzycki
017ee7bf04 [SIL] NFC: Simplify SILVTable and save 8 bytes per SILVTable
We were not using the primary benefits of an intrusive list, namely the
ability to insert or remove from the middle of the list, so let's switch
to a plain vector. This also avoids linked-list pointer chasing.
2020-06-10 07:54:23 -04: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
Joe Groff
564c1a5eec Add a [nonoverridden] kind for SILVTable entries.
This will let us track class methods that must exist for pass ordering, interface, or ABI reasons, but which can
be given more efficient runtime representation because they have no overrides.
2020-06-01 12:24:18 -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