Commit Graph

43 Commits

Author SHA1 Message Date
Andrew Trick
e705a6d7c3 Temporarily introduce AnyInteriorPointer operand ownership.
This is necessary to fix a recent OSSA bug that breaks common occurrences on
mark_dependence [nonescaping]. Rather than reverting that change above, we make
forward progress toward implicit borrows scopes, as was the original intention.

In the near future, all InteriorPointer instructions will create an implicit
borrow scope. This means we have the option of not emitting extraneous
begin/end_borrow instructions around intructions like ref_element_addr,
open_existential, and project_box. After that, we can also migrate
GuaranteedForwarding instructions like tuple_extract and struct_extract.
2025-02-05 16:23:02 -08:00
Nate Chandler
6dd45a70f9 [OSSACanonicalizeGuaranteed] Don't copy MO values.
When visiting a consuming use of a move-only value (which can be
produced by a forwarding operation), the inner rewriter must bail out.
Otherwise, it would produce a copy of that move-only value.

rdar://142520491
2025-01-10 10:14:21 -08:00
Nate Chandler
3b4803028d [NFC] OSSACanonicalizeGuaranteed: Args can bail.
Allow rewriting of arguments to bail out.  This is necessary because not
all forwarding instructions allow rewriting of forward(copy) as
copy(forward) (e.g. when forward produces a move-only value).
2025-01-10 10:14:21 -08:00
Nate Chandler
8803b612ac [NFC] OSSACanonicalizeGuaranteed: Flip condition.
Replace large nested condition with early exit.
2025-01-10 10:14:20 -08:00
Nate Chandler
0f6283c5dd [Gardening] OSSACanGuaranteed: Tweak comment. 2025-01-10 10:14:20 -08:00
Nate Chandler
fb56178481 [Test] Underscored canonicalize_borrow_scope.
Use underscores rather than hyphens so that text editors understand the
name as a single word.
2024-07-25 13:52:21 -07: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
Nate Chandler
29d046fa42 [SIL] Add BorrowedValueKind::BeginApplyToken.
The token is a guaranteed value introduced by the begin_apply and
consumed by its end_apply, abort_apply, and end_borrow users.
2024-04-25 17:03:43 -07:00
Andrew Trick
d7b9149ee5 Fix visitNonEscapingLifetimeEnds to handle mark_dependence uses
Now it visits unknown uses separately rather than asserting.
2024-03-22 14:29:57 -07: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
Nate Chandler
9ca6b9ac1f [Test] Print to stdout.
In the C++ sources it is slightly more convenient to dump to stderr than
to print to stdout, but it is rather more unsightly to print to stderr
from the Swift sources.  Switch to stdout.  Also allows the dump
functions to be marked debug only.
2023-10-10 08:19:44 -07:00
Nate Chandler
ec120e41e7 [Test] Ensourced canonicalize-borrow-scope.
Moved the test next to the code it calls.
2023-07-04 11:52:13 -07: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
16c300c2af Remove OwnershipForwardingConversionInst, ConversionInst.
Add new ConversionOperation abstraction, use this in place of ConversionInst
2023-06-15 10:53:28 -07:00
Meghana Gupta
6df7ebbb4e Update and add new apis on ForwardingInstruction 2023-06-15 10:53:06 -07:00
Meghana Gupta
0e27cd18d7 Remove FirstArgOwnershipForwardingSingleValueInst, GuaranteedFirstArgForwardingSingleValueInst, OwnedFirstArgForwardingSingleValueInst, AllArgForwardingSingleValueInst
Replace their uses with OwnershipForwardingSingleValueInstruction.
2023-06-14 12:04:58 -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
Nate Chandler
ea10281db6 [CanonGuaranteedValue] Don't insert fwd destroy.
When rewriting forwards, don't fix the lifetime which results in
spurious lifetime ends.
2023-05-04 20:12:16 -07:00
Nate Chandler
e5e1481add [CanonGuaranteedValue] Rewrite fwds in place. 2023-05-04 20:12:16 -07:00
Nate Chandler
3e08f5141b [CanonicalizeBorrowScope] Adopted BitfieldRef. 2023-05-02 11:51:53 -07:00
Nate Chandler
8882c92f82 [CanonicalizeBorrowScope] Removed spurious call.
When canonicalizing an argument, liveness is not used (it being the full
body of the function), so there's no need to invalidate it.
2023-05-02 11:51:52 -07:00
Nate Chandler
78d0660597 [CanonBorrowScope] Allow inner val without outer.
When rewriting outer uses of the borrow, `recursivelyRewriterOuterUses`
is called recursively.  First, it is called with the borrow itself.
Subsequently, it is called with forwarding users of the borrow.  Such a
user may not be rewriteable as outer uses.  If it isn't
`innerToOuterMap` won't have an entry for it.

Previously, failing to find an entry would raise an assertion.  Here,
the function is made to return a "null" SILValue.  Its caller
RewriteOuterBorrowUses::visitForwardingUse was already written to handle
such a result.
2023-04-26 18:43:17 -07:00
Nate Chandler
8c8b24fc63 [Gardening] Tweaked comment. 2023-04-26 18:18:21 -07:00
Andrew Trick
ae64ff5cb0 Rename PrunedLiveness.clear() to invalidate()
Because SILBitfield cannot be cleared.
2023-03-22 01:36:48 -07:00
Nate Chandler
10e86d6653 [CanonicalizeBorrowScope] Look through moves.
When encountering inside a borrow scope a non-lexical move_value or a
move_value [lexical] where the borrowed value is itself already lexical,
delete the move_value and regard its uses as uses of the moved-from
value.
2023-01-25 16:32:09 -08:00
Meghana Gupta
511739b494 Delete OperandOwnership::GuaranteedForwardingPhi
Use OperandOwnership::GuaranteedForwarding instead.
2022-12-13 12:51:31 -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
786eb94853 Support @guaranteed forwarding phis 2022-10-19 19:54:27 -07:00
Meghana Gupta
b1f719709b Rename ForwardingBorrow -> GuaranteedForwarding 2022-10-19 19:54:27 -07:00
Nate Chandler
4fc42a63a3 [CanonicalizeOSSALifetime] Renamed file.
Matched to the name of the utility.
2022-10-05 17:07:05 -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
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
Andrew Trick
7e66bfb622 Add asserts to CanonicalizeBorrowScope::visitBorrowScopeUses
As suggested in code review.
2022-02-24 22:47:57 -08:00
Andrew Trick
4a30118ce1 Fix an assert in canonicalizeFunctionArgument.
Assertion failed: (succeed && "should be filtered by
FindBorrowScopeUses"), function canonicalizeFunctionArgument, file
CanonicalizeBorrowScope.cpp, line 798

Canonicalization for guaranteed function arguments is triggered by
SILCombine without any up-front analysis. Because the canonicalization
rewrites the function argument's copies in place, it must always
succeed.

Fix the visitBorrowScopeUses utility to be aware that it is being
invoked on a function argument and avoid bailing out.
2022-02-18 16:52:30 -08:00
Andrew Trick
1f725883dc Workaround OSSA dead borrow scope bugs.
More bugs related to dead-end blocks and OSSA lifetimes that aren't
well formed because of that.

Independently, I'm working on prohibiting ill-formed OSSA even in the
presence of dead-end blocks. That makes these workarounds unnecessary,
but we urgently need a narrow fix here.
2021-12-13 13:46:17 -08:00
Andrew Trick
c86d112891 Update #include for InstructionDeleter.h 2021-11-18 11:38:08 -08:00
Erik Eckstein
44001402dc SILOptimizer: remove some unused variables
to fix "unused variable" warnings

rdar://84035249
2021-11-16 17:25:16 +01:00
Andrew Trick
70a14ff61b Rename ForwardingOperand.getOwnershipKind()
to getForwardingOwnershipKind() just to distinguish it from
SILValue.getOwnershipKind() and be able to grep for them each.
2021-10-06 15:48:08 -07:00
Meghana Gupta
883d145f06 Handle nil BorrowedValue during canonicalization 2021-08-13 13:06:51 -07:00
Meghana Gupta
87a7d22ba8 Clear internal data structures after canonicalizing function args
Subsequent calls for borrow canonicalization will see issues if not.
2021-08-13 11:22:42 -07:00
Andrew Trick
2c6d5afd28 Copy propagation redesign
This rewrites functionality that was mostly disabled but is now ready
to be enabled.

Allow lifetime canonicalization of owned values and function arguments
as a simple stand-alone utility. This is now being called from within
SILCombine, so we should only do the kind of canonicalization that
makes sense in that context.

Canonicalizing other borrow scopes should *not* be invoked as a
single-value cleanup because it affects other lifetimes outside the
borrow scope boundary. It is a somewhat complicated process that
hoists and sinks forwarding instructions and can generate surrounding
compensation code. The copy propagation pass knows how to post-process
the related lifetimes in just the right order. So borrow scope
rewriting should only be done in the copy propagation pass.

Similarly, only do simple canonicalization of owned values and
function arguments at -Onone.

The feature to canoncalize borrow scopes is now ready to be
enabled (-canonical-ossa-rewrite-borrows), but flipping the switch
should be a separate commit. So most of the functionality that was
affected is not exposed by this PR.

Changes:

Split canonicalization of owned lifetimes vs. borrowed lifetimes into
separate utilities. The owned lifetime utility is now back to being
the simple utility that I originally envisioned. So not much happened
to it other than removing complexity.

We now have a separate entry point for finding the starting point for
rewriting borrow scopes:
CanonicalizeBorrowScope::getCanonicalBorrowedDef.

We now have a utility that defines forwarding instructions that we can
treat consistently as part of a guaranteed lifetime,
CanonicalizeBorrowScope::isRewritableOSSAForward.

We now have a utility that defines the uses of a borrowed value that
are considered part of its lifetime,
CanonicalizeBorrowScope::visitBorrowScopeUses. This single utility is
used to implement three different parts of the alogrithm:

1. Find any uses of the borrowed value that need to be propagated
outside the borrow scope

2. RewriteInnerBorrowUses for SILFunction arguments and borrow scopes
with no outer uses.

3. RewriteOuterBorrowUses for borrow scopes with outer uses. Handling
these involves creating new copies outside the borrow scope and
hoisting forwarding instructions.

The end result is that a lot of borrow scopes can be eliminated and
owned values can be forwarded to destructures, reducing copies and
destroys.

If we stop generating borrow scopes for all interior pointers, then
we'll need to design a comparable optimization that works on
"implicit" borrow scopes:

  %ownedDef = ...
  %element struct_extract %ownedDef
  %copy = copy_value %element
  apply(@guaranteed %element)
  apply(@owned %copy)
  destroy %ownedDef

Should be:

  %ownedDef = ...
  %borrowedElement = destructure_struct @guaranteed %ownedDef
  apply(@guaranteed %borrowedElement)
  %ownedElement = destructure_struct %ownedDef
  apply(@owned %copy)
2021-07-01 21:17:27 -07:00