Commit Graph

6319 Commits

Author SHA1 Message Date
Michael Gottesman
aaffd9aef7 [mem2reg] Make style consistently new swift style before adding support for borrows.
This is code that was written at the very beginning of Swift and has some early
style remaining interspirsed with newer swift style code. Since I am going to be
touching this and I don't expect other people to touch it for a while, I am
fixing up the formatting/reorganizing rather than leaving the style inconsistent.
2021-04-09 13:40:47 -07:00
Andrew Trick
7205e46f41 Disable -O copy propagation (lifetime shortening) by default
Problem: We continue to uncover code that assumes either precise local
variable lifetimes (to the end of the lexical scope) or extended
temporary lifetimes (to the end of the statement). These bugs require
heroic debugging to find the root cause. Because they only show up in
Release builds, they often manifest just before the affected project
“ships” under an impending deadline.

We now have enough information from projects that have been tested
with copy propagation that we can both understand common patterns and
identify some specific APIs that may cause trouble. We know what API
annotations the compiler will need for helpful warnings and can begin
adding those annotations.

Disabling copy propagation now is only a temporary deferral, we will
still need to bring it back by default. However, by then we should
have:

- LLDB and runtime support for debugging deinitialized objects

- A variant of lifetime sortening that can run in Debug builds to
  catch problems before code ships

- Static compiler warnings for likely invalid lifetime assumptions

- Source annotations that allow those warnings to protect programmers
  against existing dangerous APIs

In the meantime...

Projects can experiment with the behavior and gradually migrate.

Copy propagation will automatically be enabled in -enable-ossa-modules
mode. It is important to work toward a single performance
target. Supporting full OSSA and improving ARC performance without
copy propagation would be prohibitively complicated.

rdar://76438920 (Temporarily disable -O copy propagation by default)
2021-04-09 00:12:09 -07:00
John McCall
efeb818161 Clean up the TaskGroup ABI:
- stop storing the parent task in the TaskGroup at the .swift level
- make sure that swift_taskGroup_isCancelled is implied by the parent
  task being cancelled
- make the TaskGroup structs frozen
- make the withTaskGroup functions inlinable
- remove swift_taskGroup_create
- teach IRGen to allocate memory for the task group
- don't deallocate the task group in swift_taskGroup_destroy

To achieve the allocation change, introduce paired create/destroy builtins.

Furthermore, remove the _swiftRetain and _swiftRelease functions and
several calls to them.  Replace them with uses of the appropriate builtins.
I should probably change the builtins to return retained, since they're
working with a managed type, but I'll do that in a separate commit.
2021-04-09 03:06:31 -04:00
Slava Pestov
17e84c2776 Merge pull request #36795 from slavapestov/lazily-emit-alwaysEmitIntoClient
Lazily emit @_alwaysEmitIntoClient functions at -Onone
2021-04-08 17:58:00 -04:00
Arnold Schwaighofer
d4246b904d hop_to_executor should have no affect if we inline a [noasync] apply into a non async function.
rdar://76230423
2021-04-08 07:41:13 -07:00
eeckstein
df8627152e Merge pull request #36798 from eeckstein/fix-diagnose-weak
DiagnoseLifetimeIssues: handle called functions.
2021-04-08 07:47:59 +02:00
Slava Pestov
1e8ce52736 SIL: Strip [serialized] flag from functions even at -Onone
While the comment is correct to state that this won't enable any
new optimizations with -Onone, it does enable IRGen's lazy
function emission, which is important for 'reasync' functions,
which we don't want to emit at all even at -Onone.

This fixes debug stdlib builds with the new reasync versions
of the &&, || and ?? operators.
2021-04-08 01:47:27 -04:00
Erik Eckstein
99eb0f39f1 DiagnoseLifetimeIssues: handle called functions.
This

1. fixes a bug, where we didn't consider that an object can escape via a function call. The pass issued a false warning in this case.

rdar://76115467

2. improves the accuracy by doing a simple form of interprocedural analysis. E.g. it now can see if a weak store is done in a called function.

rdar://76297286
2021-04-07 16:09:07 +02:00
Nate Chandler
d765434e2b [IRGen] Restored non-constant async function calls in PAFs.
Previously, because partial apply forwarders for async functions were
not themselves fully-fledged async functions, they were not able to
handle dynamic functions.  Specifically, the reason was that it was not
possible to produce an async function pointer for the partial apply
forwarder because the size to be used was not knowable.

Thanks to https://github.com/apple/swift/pull/36700, that cause has been
eliminated.  With it, partial apply forwarders are fully-fledged async
functions and in particular have their own async function pointers.
Consequently, it is again possible for these partial apply forwarders to
handle non-constant function pointers.

Here, that behavior is restored, by way of reverting part of
ee63777332 while preserving the ABI it
introduced.

rdar://76122027
2021-04-06 15:51:32 -07:00
Stephen Canon
511b50e511 Implement shufflevector builtin. (#36650)
This isn't _terribly_ useful as-is, because the only constant mask you can get at from Swift at present is the zeroinitializer, but even that is quite useful for optimizing the repeating: intializer on SIMD. At some future point we should wire up generating constant masks for the .even, .odd, .high and .low properties (and also eventually make shufflevector take non-constant masks in LLVM). But this is enough to be useful, so let's get it in.
2021-04-04 23:23:53 -04:00
Andrew Trick
b1b2eff075 Disable mandatory-copy-propagation (-Onone only)
This feature degrades the debugging experience and causes a large
number of unit test failures.

These were both known issues, but our planned debugger improvements
won't be ready for a while. Until then, we'll leave the feature under
a compiler option, and developers can adopt it at there own speed for
now when they are ready to fix lifetime issues in their code.

rdar://76177280 (Disable mandatory-copy-propagation (-Onone only))
2021-04-02 22:33:50 -07:00
swift-ci
d67461770f Merge pull request #36717 from eeckstein/main 2021-04-02 15:03:58 -07:00
Michael Gottesman
10b4e7ac83 Merge pull request #36684 from gottesmm/pr-415ff46ebe84945d134a5e051190270946699427
[simplify-instruction] When eliminating extracts from an aggregate we  just constructed, look through ownership insts.
2021-04-02 11:43:48 -07:00
Erik Eckstein
f3d1c34eb5 StringOptimization: don't constant fold dynamic Self type names.
This wrongly results in "Self" instead of the real type name.

rdar://76113269
2021-04-02 08:41:01 +02:00
Michael Gottesman
2e32a7cd64 Merge pull request #36632 from gottesmm/opt_remark_runtime_cast_remark
[opt-remark] Add support for emitting remarks about runtime casts.
2021-03-31 18:30:28 -07:00
Michael Gottesman
c834520b88 [simplify-instruction] When eliminating extracts from an aggregate we just constructed, look through ownership insts.
Just an oversight. When used with -enable-ossa-modules, this eliminates the
reported ARC traffic issue in:

SR-12377
rdar://60832825
2021-03-31 18:30:03 -07:00
John McCall
434454183e Merge pull request #36643 from rjmccall/lower-hop-to-actor
Require that hop_to_executor eventually actually takes an executor
2021-03-31 16:31:36 -04:00
Slava Pestov
48b729d2f2 Merge pull request #36641 from slavapestov/more-reasync-fixes
More 'reasync' fixes
2021-03-31 15:43:59 -04:00
Michael Gottesman
753f7ab8f3 [opt-remark] Add remarks for casts that go through the runtime and aren't optimized away.
Now we get opt-remarks like the following:

```
public func condCast5<NS, T>(_ ns: NS) -> T? {
  // Make sure the colon info is right so that the arrow is under the a.
  //
  // Today, we lose that x was assigned.
  if let x = ns as? T {  // expected-remark @:17 {{conditional runtime cast of value with type 'NS' to 'T'}}
    return x             // expected-note @-5:32 {{of 'ns'}}
  }
  return nil
}
```
2021-03-30 18:58:27 -07:00
John McCall
4f6f8b3377 Rewrite hop_to_executor so that it takes a Builtin.Executor in IRGen
The comment in LowerHopToActor explains the design here.
We want SILGen to emit hops to actors, ignoring executors,
because it's easier to fully optimize in a world where deriving
an executor is a non-trivial operation.  But we also want something
prior to IRGen to lower the executor derivation because there are
useful static optimizations we can do, such as doing the derivation
exactly once on a dominance path and strength-reducing the derivation
(e.g. exploiting static knowledge that an actor is a default actor).

There are probably phase-ordering problems with doing this so late,
but hopefully they're restricted to situations like actors that
share an executor.  We'll want to optimize that eventually, but
in the meantime, this unblocks the executor work.
2021-03-30 20:08:41 -04:00
Slava Pestov
3cc0d36c3a Mandatory Inlining: Look through convert_function recursively 2021-03-29 23:52:44 -04:00
Slava Pestov
e465a10655 Mandatory Inlining: Turn skipFuncConvert() lambda into a top-level stripFunctionConversions() function 2021-03-29 23:52:44 -04:00
Michael Gottesman
85de7c9970 [semantic-arc] Add a comment dexplaining that isSingleInitAllocStack does not necessarily contain operands of destroy_addr now that it handles checked_cast_addr_br, unchecked_checked_cast_addr. 2021-03-29 12:16:49 -07:00
Michael Gottesman
8750b404f3 [opt-remark] Extract out DebugValue inference from a Value's uses into a helper struct to enable code reuse.
I am doing this so I can use the same code with alloc_stack.
2021-03-29 12:10:37 -07:00
Erik Eckstein
479517f71d AccessSummaryAnalysis: relax the verification of expected no-escape partial_apply uses
* add is_escaping_closure as allowed instruction
* don't restrict the uses of copy_value to be a store

Fixes a verification crash (only in assert builds).

https://bugs.swift.org/browse/SR-14394
rdar://75740622
2021-03-29 13:21:43 +02:00
Michael Gottesman
360e32bfbd Merge pull request #36622 from gottesmm/pr-f547a5b1d52f9b19efd84b124f089c7df498f07f
[opt-remark-gen] Teach OptRemarkGen how to emit diagnostics about exclusivity.
2021-03-28 18:20:00 -07:00
Michael Gottesman
1227693d29 [opt-remark-gen] Teach OptRemarkGen how to emit diagnostics about exclusivity.
For example, now we get the following diagnostic on globals:

 public func getGlobal() -> Klass {
     return global // expected-remark @:5 {{retain of type 'Klass'}}
                   // expected-note @-5:12 {{of 'global'}}
+                  // expected-remark @-2:12 {{begin exclusive access to value of type 'Klass'}}
+                  // expected-note @-7:12 {{of 'global'}}
+                  // expected-remark @-4 {{end exclusive access to value of type 'Klass'}}
+                  // expected-note @-9:12 {{of 'global'}}
+
 }

and for classes when we can't eliminate the access:

+func simpleInOut() -> Klass {
+    let x = Klass() // expected-remark @:13 {{heap allocated ref of type 'Klass'}}
+                    // expected-note @-1:9 {{of 'x'}}
+    simpleInOutUser(&x.next) // expected-remark @:5 {{begin exclusive access to value of type 'Optional<Klass>'}}
+                             // expected-note @-3:9 {{of 'x.next'}}
+                             // expected-remark @-2:28 {{end exclusive access to value of type 'Optional<Klass>'}}
+                             // expected-note @-5:9 {{of 'x.next'}}
+    return x
+}
2021-03-28 13:39:13 -07:00
John McCall
98711fd628 Revise the continuation ABI.
The immediate desire is to minimize the set of ABI dependencies
on the layout of an ExecutorRef.  In addition to that, however,
I wanted to generally reduce the code size impact of an unsafe
continuation since it now requires accessing thread-local state,
and I wanted resumption to not have to create unnecessary type
metadata for the value type just to do the initialization.

Therefore, I've introduced a swift_continuation_init function
which handles the default initialization of a continuation
and returns a reference to the current task.  I've also moved
the initialization of the normal continuation result into the
caller (out of the runtime), and I've moved the resumption-side
cmpxchg into the runtime (and prior to the task being enqueued).
2021-03-28 12:58:16 -04: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
Erik Eckstein
9b16a94e8d TempRValueOpt: small fixes/improvements for extending access scopes
Don't move an end_access over a (non-aliasing) end_access. This would destroy the proper nesting of accesses.
Also, add some comments, asserts and tests.
2021-03-24 12:51:30 +01:00
Erik Eckstein
67ce72cebb MemBehavior: fix minor bugs for `begin_access and end_access`.
* ``begin_access [modify]`` returned MayWrite, but "modify" means, it can be a read as well.
Instead, return MayReadWrite. Only for ``begin_access [init]`` return MayWrite.
This is more or less cosmetic - probably this bug had no real impact on any optimization.

* ``begin_access [deinit]`` needs to return MayReadWrite for the same reason ``destroy_addr`` returns MayReadWrite (see SILInstruction::MemoryBehavior).
2021-03-24 12:16:07 +01:00
Erik Eckstein
8828d8e6bf tests: clean-up MemBehavior tests
Add more relevant instructions to dump in MemBehaviorDumper.
Therefore the -enable-mem-behavior-dump-all option can be removed.
Also mem-behavior-all.sil into mem-behavior.sil, because the sil-opt command lines don't differ anymore.
2021-03-24 11:19:00 +01:00
Erik Eckstein
7c454e3eed TempRValueOpt: extend access scopes
Try to move an end_access down to extend the access scope over all uses of the temporary.
For example:

   %a = begin_access %src
   copy_addr %a to [initialization] %temp : $*T
   end_access %a
   use %temp

We must not replace %temp with %a after the end_access. Instead we try to move the end_access after "use %temp".

This fixes generation of invalid SIL and/or the invalid removal of access checks.
2021-03-22 21:54:41 +01:00
Doug Gregor
cfa07b60ee Merge pull request #36477 from jckarter/executor-hop-back
Concurrency: Hop back to the previous executor after actor calls.
2021-03-19 10:17:20 -07:00
Doug Gregor
52096a640e SE-0302: Rename ConcurrentValue/@concurrent to Sendable/@Sendable. 2021-03-18 23:48:21 -07:00
Joe Groff
79fb05b362 Concurrency: Hop back to the previous executor after actor calls.
Tasks shouldn't normally hog the actor context indefinitely after making a call that's bound to
that actor, since that prevents the actor from potentially taking on other jobs it needs to
be able to address. Set up SILGen so that it saves the current executor (using a new runtime
entry point) and hops back to it after every actor call, not only ones where the caller context
is also actor-bound.

The added executor hopping here also exposed a bug in the runtime implementation while processing
DefaultActor jobs, where if an actor job returned to the processing loop having already yielded
the thread back to a generic executor, we would still attempt to make the actor give up the thread
again, corrupting its state.

rdar://71905765
2021-03-18 11:47:50 -07:00
Andrew Trick
e9d0b08706 Add utilities to support OSSA update after running SSAUpdater.
This directly adds support to BasicBlockCloner for updating OSSA.

It also adds a much more general-purpose GuaranteedPhiBorrowFixup
utility which can be used for more complicated SSA updates, in which
multiple phis need to be created. More generally, it handles adding
nested borrow scopes for guaranteed phis even when that phi is used by
other guaranteed phis.
2021-03-18 00:14:13 -07:00
Andrew Trick
2f34014ffc Rescue the ValueLifetimeAnalysis utility.
This is a basic SSA-based liveness algorithm. It should just do what
it says. This change rescues the core logic from the nonsense that's
been hacked in. There are now two APIs:

(1) computeLifetimeBoundary (new) only does lifetime analysis.  It
provides a new API that always succeeds and provides the last use
points so clients can do the right thing based on the user. I need
this for OSSA utilities.

(2) computeFrontier (old) emulates the original API with a simplified
version of the original logic.

Next steps:

- replace the old API with a separate utility that computes destroy
  insertion points. Completely remove DeadEndBlocks from lifetime
  analysis, because it simply has nothing to do with liveness.

- Gradually migrate clients to either the new lifetime API provided
  here or the new destroy insertion API to be provided later.
2021-03-17 23:08:11 -07:00
eeckstein
97ed11fa54 Merge pull request #36449 from eeckstein/fix-rawinstsillowering
Don't crash in RawSILInstLowering if DI produced an error.
2021-03-16 19:49:17 +01:00
eeckstein
129fca6f0a Merge pull request #36447 from eeckstein/main
SILOptimizer: fix a compiler crash when optimizing a global variable with an empty tuple.
2021-03-16 17:24:51 +01:00
eeckstein
898cdc0fc1 Merge pull request #36439 from eeckstein/lookup-table-opt
Remove unnecessary retain/release/initialization overhead from lookup table Arrays.
2021-03-16 15:11:13 +01:00
Erik Eckstein
b12b4e95b9 Don't crash in RawSILInstLowering if DI produced an error.
In case DI doesn't classify assign_by_wrapper (because of another error), make sure that RawSILInstLowering can handle this.

rdar://75433096
2021-03-16 13:28:52 +01:00
Erik Eckstein
28a5eee217 SILMem2Reg: don't create an "undef" as a replacement of a load of an empty tuple.
Instead create the empty tuple value.
In general, it's not a good idea to create undef values in SIL.
2021-03-16 11:26:54 +01:00
nate-chandler
179a707352 Merge pull request #36284 from nate-chandler/concurrency/irgen/rdar72105841
[IRGen] Fix ABI for thick async functions.
2021-03-15 18:36:55 -07:00
Andrew Trick
b85b7f12b6 Merge pull request #36408 from atrick/enable-mandatory-copyprop
Enable mandatory copy propagation (shortens -Onone lifetimes)
2021-03-15 16:56:18 -07:00
Nate Chandler
ee63777332 [IRGen] Fix ABI for thick async functions.
Previously, thick async functions were represented sometimes as a pair
of (AsyncFunctionPointer, nullptr)--when the thick function was produced
via a thin_to_thick_function, e.g.--and sometimes as a pair of
(FunctionPointer, ThickContext)--when the thick function was produced by
a partial_apply--with the size stored in the slot of the ThickContext.

That optimized for the wrong case: partial applies of dynamic async
functions; in that case, there is no appropriate AsyncFunctionPointer to
form when lowering the partial_apply instruction.  The far more common
case is to know exactly which function is being partially applied.  In
that case, we can form the appropriate AsyncFunctionPointer.

Furthermore, the previous representation made calling a thick function
more complex: it was always necessary to check whether the context was
in fact null and then proceed along two different paths depending.

Here, that behavior is corrected by creating a thunk in a mandatory
IRGen SIL pass in the case that the function that is being partially
applied is dynamic.  That new thunk is then partially applied in place
of the original partial_apply of the dynamic function.
2021-03-15 13:37:40 -07:00
Erik Eckstein
ea8f43a8ba SILCombine: remove unneeded reference counting instructions from global_value
Delete all reference count instructions on a global_value if the only other uses are projections (ref_element_addr and ref_tail_addr).
2021-03-15 11:54:23 +01:00
eeckstein
35cc53ea7e Merge pull request #36384 from eeckstein/memory-lifetime
improvements/fixes in RawSILInstLowering and MemoryLifetimeVerifier
2021-03-14 10:03:27 +01:00
Michael Gottesman
19dd90674d Merge pull request #36167 from gottesmm/pr-761936430320990a32c8dfb2f85d27f171f186ba
[simplify-cfg] Only check if we can remove releases by performing simple jump threading if our block argument is not a trivial type.
2021-03-13 13:00:03 -08:00
Erik Eckstein
b9c8e57d7a MemoryLifetimeVerifier: also verify locations with trivial types.
It helps to catch more problems
2021-03-13 10:41:30 +01:00