Commit Graph

116 Commits

Author SHA1 Message Date
Erik Eckstein
45dc83bcd8 SemanticARCOpts: don't ignore dead-end blocks in the liverange analysis
This can result in wrong ARC optimizations in dead-end blocks.
Fixes a SIL verification error.

rdar://154356277
2025-06-26 16:06:32 +02:00
Meghana Gupta
6c2d3eb27d Bailout of CopyValueOpts when there is a pointer escape
Copy propagation does these optimizations more generally. It should be
able to replace this optimization. Fixing it and not just deleting CopyValueOpts
because it happens to be called in the mandatory pipeline.
2025-03-07 10:40:37 -08:00
Erik Eckstein
51e3e5ed80 Optimizer: rename BorrowArgumentsUpdater -> GuaranteedPhiUpdater
NFC
2024-11-12 09:26:59 +01:00
Erik Eckstein
7bf0010c92 SIL: remove computeIsReborrow
This API computes the re-borrow flags for guaranteed phis based on the presence of forwarding instructions in the incoming values.
This is not correct in all cases, because optimizations can optimize away forwarding instructions.

Fixes a verifier crash: rdar://139280579
2024-11-12 09:26:59 +01:00
Erik Eckstein
6b8c6a3c3b SIL: rename updateBorrowedFrom to updateBorrowArguments
NFC
2024-11-12 09:26:58 +01:00
Erik Eckstein
b8026d74e6 Revert "Revert "Optimizer: improve the load-copy-to-borrow optimization and implement it in swift""
This reverts commit 0666c446ec.
2024-10-22 08:40:18 +02:00
Erik Eckstein
0666c446ec Revert "Optimizer: improve the load-copy-to-borrow optimization and implement it in swift"
This reverts commit eed8645610.
2024-10-18 10:36:06 +02:00
Erik Eckstein
eed8645610 Optimizer: improve the load-copy-to-borrow optimization and implement it in swift
The optimization replaces a `load [copy]` with a `load_borrow` if possible.

```
  %1 = load [copy] %0
  // no writes to %0
  destroy_value %1
```
->
```
  %1 = load_borrow %0
  // no writes to %0
  end_borrow %1
```

The new implementation uses alias-analysis (instead of a simple def-use walk), which is much more powerful.

rdar://115315849
2024-10-11 09:41:37 +02:00
Erik Eckstein
656e6cd4bb SemanticARCOpts: update borrowed-from instructions when changes are made
Fixes a SIL verifier error

rdar://134728428
2024-08-27 13:28:40 +02: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
Erik Eckstein
e14c1d1f62 SIL, Optimizer: update and handle borrowed-from instructions
Compute, update and handle borrowed-from instruction in various utilities and passes.
Also, used borrowed-from to simplify `gatherBorrowIntroducers` and `gatherEnclosingValues`.
Replace those utilities by `Value.getBorrowIntroducers` and `Value.getEnclosingValues`, which return a lazily computed Sequence of borrowed/enclosing values.
2024-04-10 13:38:10 +02:00
Erik Eckstein
ac4bc89c9a SIL: add the borrowed-from instruction.
It declares from which enclosing values a guaranteed phi argument is borrowed from.
2024-04-10 13:38:10 +02:00
Nate Chandler
9f6c30919b [NFC] SIL: Typed begin_borrow's isLexical. 2024-03-08 22:27:50 -08:00
Michael Gottesman
11f0ff6e32 [sil] Ensure that all SILValues have a parent function by making it so that SILUndef is uniqued at the function instead of module level.
For years, optimizer engineers have been hitting a common bug caused by passes
assuming all SILValues have a parent function only to be surprised by SILUndef.
Generally we see SILUndef not that often so we see this come up later in
testing. This patch eliminates that problem by making SILUndef uniqued at the
function level instead of the module level. This ensures that it makes sense for
SILUndef to have a parent function, eliminating this possibility since we can
define an API to get its parent function.

rdar://123484595
2024-02-27 13:14:47 -08:00
Holly Borla
2c6344f461 [SILOptimizer] Handle FunctionExtractIsolationInst in the mandatory passes. 2024-02-26 17:59:27 -08:00
Ben Barham
f292ec9784 Use the new template deduction guides rather than makeArrayRef
LLVM has removed `make*ArrayRef`, migrate all references to their
constructor equivalent.
2024-02-23 20:04:51 -08: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
Andrew Trick
2b70d2dad8 Fix SemanticARCOpts LoadCopyToBorrowOpt for ObjC closure thunk
This fixes a use-after-free miscompile.

LoadCopyToBorrowOpt alias analysis was wrong in
visitArgumentAccess. inout_aliasable does not give you exclusive
access to an address.

This resulted in removal of a retain before calling an ObjC block
after converting it from a Swift closure.

@_silgen_name("foreign")
func foreign(block: @escaping @convention(block) () -> Void)

public func doit(closure: @escaping () -> ()) {
  foreign { [closure] in closure() }
}

Fixes rdar://121268094
2024-01-25 22:13:15 -08:00
Allan Shortlidge
d55c28b81a NFC: Fix use of LLVM_LIBRARY_VISIBILITY in Transforms.h. 2024-01-12 18:21:42 -08:00
nate-chandler
680c737ddb Merge pull request #64789 from nate-chandler/more-move-values
[SILGen] Used move_value for more lexical values.
2023-12-15 07:07:54 -08:00
Nate Chandler
5513dd1e32 [SAO] Redundant move elimination is mandatory. 2023-12-14 13:35:26 -08:00
Meghana Gupta
24aa3296dc [NFC] Add debug msgs in copy value opts 2023-12-13 10:38:12 -08: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
Meghana Gupta
28df449d38 Merge pull request #66723 from meg-gupta/improvefindpointerescape
Refactor swift::findPointerEscape and handle additional cases
2023-06-21 21:04:21 -07:00
Meghana Gupta
031255c2d8 Rename hasPointerEscape -> findPointerEscape 2023-06-20 21:13:55 -07:00
Meghana Gupta
7cb3733e29 Rename OwnershipForwardingMixin -> ForwardingInstruction 2023-06-14 10:40:32 -07:00
Meghana Gupta
5d401fb70a Remove select_value SIL instruction 2023-06-13 14:13:43 -07:00
Meghana Gupta
1dc713e2f7 Add new flags "reborrow" and "escaping" to SILArgument.
"reborrow" flag on the SILArgument avoids transitive walk over the phi operandsi
to determine if it is a reborrow in multiple utilities.
SIL transforms must keep the flag up-to-date by calling SILArgument::setReborrow.
SILVerifier checks to ensure the flag is not invalidated.

Currently "escaping" is not used anywhere.
2023-05-11 12:31:37 -07:00
Nate Chandler
2163269f88 [SemanticARCOpts] Check uses in moved load range.
In https://github.com/apple/swift/pull/65417 , support for promoting
moved-from `load [copy]`s was added.  At that time, the existing logic
was generalized so that the check for whether writes the loaded-from
address occurred: rather than checking whether the writes occurred in
the live-range of the `load [copy]`, it was generalized to check whether
writes occurred in the live range of the "original" value which was
either the `load [copy]` or the `move_value`.  That opened a hole for
writes that occurred between the `load [copy]` and the `move_value`:

```
%v = load [copy] %a
%u = load [take] %a
%m = move_value %v
```

Here, this is fixed by checking both the live-range of the "original"
and also (supposing the original is different from the `load [copy]`)
also the live range of the `load [copy]`.

This required changing the list of consuming uses passed to the
`LinearLifetimeChecker::usesNotContainedWithinLifetime` to include not
just the `destroy_value`s but also the "unknown" consuming uses (i.e.
those that are not forwarding).

This change only affects arguments (and specifically only `@inout`
arguments since promotion for `@in` arguments isn't supported) because a
totally different code path is followed for `alloc_stack`s which regards
`load [take]`s as an "init" of the address (concretely,
`getSingleInitAllocStackUse` returns `truea for the above example if `%a` is
an `alloc_stack`).

rdar://108745323
2023-05-01 18:30:22 -07:00
Nate Chandler
f039d40086 [SemanticARCOpts] Load_borrow moved load [copy]s.
In the context of promoting a `load [copy]` to a `load_borrow`, allow
the value representing the lifetime of the load to differ from the `load
[copy]` itself--it may either be the load or its only user.

If promoting the `load [copy]` to a `load_borrow` with the load itself
as the lifetime representative fails, look for a single `move_value` use
of the load.  If found, attempt the optimization again with the
`move_value` as the lifetime representative.

rdar://108514447
2023-04-25 11:37:30 -07:00
Nate Chandler
8287d2e9ef [SemanticARC] NFC: Extracted opt from visit.
In preparation to attempt two variations of the optimization, added
performLoadCopyToLoadBorrowOptimization and call it from visitLoadInst.
2023-04-25 11:37:30 -07:00
Nate Chandler
b686e81085 [OwnershipUtils] Add move as OwnedValueIntroducer. 2023-04-25 11:37:30 -07:00
Nate Chandler
a4ac481ecb [SemanticARCOpts] Keep owned lexical lifetimes.
Prevent joining lifetimes of copies with destroyed owned lexical values
if there may be deinit barriers between the final consume of the copy
and the destroy of the lexical value.

rdar://108014714
2023-04-13 14:36:37 -07:00
Andrew Trick
26a62645b4 Fix MandatoryARCOpts tryJoiningCopyValueLiveRangeWithOperand.
Fix a miscompile in Debug builds at -Onone.

This optimization ignores uses of owned values that aren't enclosed in
borrow scopes. This is fairly eggregious since project_box
instructions are never borrowed, which means that all local variables
have this problem.

This is a well-known issue that occurs throughout OSSA
optimizations. The reason that we don't see the problem often is that
the optimizations are hidden behind a pile of ad-hoc pattern matching,
so they only kick in for simple cases. This approach to optimization
is great at hiding problems for a long time.

We're attempting to design away this class of problems in the next
release. Until then, it's one miscompile at a time.

Fixes rdar://107420448 (Variable mutation in block isn't reflected
in outer scope: new behavior in swift 5.9)
2023-03-31 20:33:53 -07:00
swift-ci
095d84dc48 Merge pull request #64440 from meg-gupta/disablesemarcoptsedgecase
Disable owned to guaranteed phi transformation when the borrow introducers have a local scope
2023-03-17 12:10:20 -07:00
Meghana Gupta
21e829bace Disable owned to guaranteed phi transformation when the borrow introducers have a local scope
In the absence of this bailout, reborrows can be introduced while replacing the @owned value with
a local borrow introducer. Since lifetime adjustment for this case was not implemented, disable here.

rdar://106757446
2023-03-17 09:43:08 -07:00
Nate Chandler
ceb941d1d1 [NFC] Extracted isRedundantMoveValue.
Extracted the predicate from inline in RedundantMoveValueElimination
into the new function which can now be called from elsewhere
(CopyPropagation).
2023-03-15 07:38:59 -07:00
Nate Chandler
5f561ed596 [SAO] Add RedundantMoveValueElimination.
Adds to SemanticARCOpts a new step of removing move_value instructions
if they are redundant.  A move_value is redundant if it adds no new
information or optimization opportunities.

An example of adding information: a lifetime becoming lexical.  The new
lifetime's destroys cannot be hoisted over deinit barriers.

An example of adding an optimization opportunity: the original value
escapes but the value produced by the move_value does not escape.  So
destroys of the new value can be hoisted more aggressively.
2023-03-10 10:49:53 -08:00
Andrew Trick
103a6fefb8 LinearLifetimeChecker - make DeadEndBlocks optional 2023-03-01 21:41:46 -08:00
Meghana Gupta
b10563909c Update isGuaranteedForwarding api and delete isGuaranteedForwardingPhi api 2022-12-13 12:51:25 -08:00
Andrew Trick
f9861ec9c0 Add APIs for terminator results that forward ownership.
Add TermInst::forwardedOperand.

Add SILArgument::forwardedTerminatorResultOperand. This API will be
moved into a proper TerminatorResult abstraction.

Remove getSingleTerminatorOperand, which could be misused because it's
not necessarilly forwarding ownership.

Remove the isTransformationTerminator API, which is not useful or well
defined.

Rewrite several instances of complex logic to handle block arguments
with the simple terminator result API. This defines away potential
bugs where we don't detect casts that perform implicit conversion.

Replace uses of the SILPhiArgument type and code that explicitly
handle block arguments. Control flow is irrelevant in these
situations. SILPhiArgument needs to be deleted ASAP. Instead, use
simple APIs like SILArgument::isTerminatorResult(). Eventually this
will be replaced by a TerminatorResult type.
2022-12-12 12:37:35 -08:00
Erik Eckstein
ab1b343dad use new llvm::Optional API
`getValue` -> `value`
`getValueOr` -> `value_or`
`hasValue` -> `has_value`
`map` -> `transform`

The old API will be deprecated in the rebranch.
To avoid merge conflicts, use the new API already in the main branch.

rdar://102362022
2022-11-21 19:44:24 +01:00
Meghana Gupta
730b513fad [SemanticARCOpts] Remove unnecessary borrow scope for @guaranteed function arg when used as a phi operand 2022-10-21 22:31:04 -07:00
Meghana Gupta
9b01b87b4b Update SemanticARCOpts for @guaranteed forwarding phi support 2022-10-19 19:54:28 -07:00
Andrew Trick
6346bf55c5 Rename areUsesWithinTransitiveScope to ...ExtendedScope
Start using consistent terminolfy in ownership utils.

A transitive use set follows transitive uses within an ownership
lifetime. It does not rely on complete inner scopes. An extended use
set is not necessarilly transitive but does look across
lifetime-ending uses: copies of owned values and/or reborrows of
guaranteed values. Whether lifetime extension refers to copies or
reborrow is context dependent.
2022-10-04 13:27:48 -07:00
Josh Soref
730b16c569 Spelling siloptimizer
* access
* accessed
* accesses
* accessor
* acquiring
* across
* activated
* additive
* address
* addresses'
* aggregated
* analysis
* and
* appropriately
* archetype
* argument
* associated
* availability
* barriers
* because
* been
* beginning
* belongs
* beneficial
* blocks
* borrow
* builtin
* cannot
* canonical
* canonicalize
* clazz
* cleanup
* coalesceable
* coalesced
* comparisons
* completely
* component
* computed
* concrete
* conjunction
* conservatively
* constituent
* construct
* consuming
* containing
* covered
* creates
* critical
* dataflow
* declaration
* defined
* defining
* definition
* deinitialization
* deliberately
* dependencies
* dependent
* deserialized
* destroy
* deterministic
* deterministically
* devirtualizes
* diagnostic
* diagnostics
* differentiation
* disable
* discipline
* dominate
* dominates
* don't
* element
* eliminate
* eliminating
* elimination
* embedded
* encounter
* epilogue
* epsilon
* escape
* escaping
* essential
* evaluating
* evaluation
* evaluator
* executing
* existential
* existentials
* explicit
* expression
* extended
* extension
* extract
* for
* from
* function
* generic
* guarantee
* guaranteed
* happened
* heuristic
* however
* identifiable
* immediately
* implementation
* improper
* include
* infinite
* initialize
* initialized
* initializer
* inside
* instruction
* interference
* interferes
* interleaved
* internal
* intersection
* intractable
* intrinsic
* invalidates
* irreducible
* irrelevant
* language
* lifetime
* literal
* looks
* materialize
* meaning
* mergeable
* might
* mimics
* modification
* modifies
* multiple
* mutating
* necessarily
* necessary
* needsmultiplecopies
* nonetheless
* nothing
* occurred
* occurs
* optimization
* optimizing
* original
* outside
* overflow
* overlapping
* overridden
* owned
* ownership
* parallel
* parameter
* paths
* patterns
* pipeline
* plottable
* possible
* potentially
* practically
* preamble
* precede
* preceding
* predecessor
* preferable
* preparation
* probably
* projection
* properties
* property
* protocol
* reabstraction
* reachable
* recognized
* recursive
* recursively
* redundant
* reentrancy
* referenced
* registry
* reinitialization
* reload
* represent
* requires
* response
* responsible
* retrieving
* returned
* returning
* returns
* rewriting
* rewritten
* sample
* scenarios
* scope
* should
* sideeffects
* similar
* simplify
* simplifycfg
* somewhat
* spaghetti
* specialization
* specializations
* specialized
* specially
* statistically
* substitute
* substitution
* succeeds
* successful
* successfully
* successor
* superfluous
* surprisingly
* suspension
* swift
* targeted
* that
* that our
* the
* therefore
* this
* those
* threshold
* through
* transform
* transformation
* truncated
* ultimate
* unchecked
* uninitialized
* unlikely
* unmanaged
* unoptimized key
* updataflow
* usefulness
* utilities
* villain
* whenever
* writes

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>
2022-10-03 18:31:33 -04:00
Nate Chandler
46fe0f7128 [Gardening] Tweaked comment grammar. 2022-08-21 21:44:31 -07:00
Nate Chandler
b467319cce [NFC] Removed unused variable. 2022-08-21 21:44:30 -07:00
Michael Gottesman
1e6187c4f4 [sil] Update all usages of old API SILValue::getOwnershipKind() in favor of new ValueBase::getOwnershipKind().
Andy some time ago already created the new API but didn't go through and update
the old occurences. I did that in this PR and then deprecated the old API. The
tree is clean, so I could just remove it, but I decided to be nicer to
downstream people by deprecating it first.
2022-07-26 11:46:23 -07:00