Commit Graph

64 Commits

Author SHA1 Message Date
Andrew Trick
b4a47b6463 Fix findInnerTransitiveUsesForAddress; add AddressUseKind
findInnerTransitiveUsesForAddress was incorrectly returning true for
pointer escapes.

Introduce enum AddressUseKind { NonEscaping, PointerEscape, Unknown };

Clients need to handle each of these cases differently.
2021-10-12 19:58:11 -07:00
Andrew Trick
014b155b14 Temporarily disable addresseses in findInnerGuaranteedUses
Because not all OSSA utility fixes have been committed yet.
2021-10-12 19:58:11 -07:00
Andrew Trick
52e1fc2418 Fix findTransitiveGuaranteedUses to only record leaf uses.
Recording uses is now optional. This utility is also used simply to
check for PointerEscape. When uses are recorded, they are used to
extend a live range. There could be a large number of transitive uses
that we don't want to pass back to the caller.
2021-10-12 19:58:11 -07:00
Andrew Trick
a336bcdea9 Fix findTransitiveUses to only record leaf uses.
Recording uses is now optional. This utility is also used simply to
check for PointerEscape. When uses are recorded, they are used to
extend a live range. There could be a large number of transitive uses
that we don't want to pass back to the caller.
2021-10-12 19:58:10 -07:00
Andrew Trick
1678354332 Fix an obvious bug in InteriorPointerOperand::findTransitiveUses().
The return value was inverted, meaning the OSSA utilities simply
bailed out in most cases.

Fixing this means potentially exposing other OSSA bugs.
2021-10-12 19:58:10 -07:00
Andrew Trick
767e094cfe Add AddressOwnership OSSA utility
This replaces the recent BorrowedAddress utility (the address may not
be borrowed!)

APIs:

AddressOwnership::hasLocalOwnershipLifetime() - convenience on top of
AccessBase::hasLocalOwnershipLifetime().

AddressOwnership::getOwnershipReferenceRoot() - convenience on top of
AccessBase::getOwnershipReferenceRoot().

AddressOwnership::findTransitiveUses() - wrapper API over the internal
helper findTransitiveUsesForAddress()

AddressOwnership::areUsesWithinLifetime() - wrapper adds a quick check
on top of BorrowedValue::areUsesWithinLifetime()
2021-10-07 15:34:09 -07:00
Andrew Trick
b1352b490b Rename visitExtendedLocalScopeEndingUses
To visitExtendedScopeEndingUses.

We need to talk about the "local" scope, which does not cross
reborrows, in contrast to the extended scope. So the name was a
contradiction that could cause confusion elsewhere.
2021-10-07 14:32:40 -07:00
Andrew Trick
ac2f7b75ec Add BorrowingOperand::hasEmptyRequiredEndingUses()
Temporary check for malformed borrow scopes. Def-use traversals expect
at least one scope-ending use. Otherwise we can end up missing the
borrow entirely and miscompiling. SIL should guarantee scope-ending
uses on all paths, but that isn't fully enforced yet.
2021-10-07 14:32:32 -07:00
Andrew Trick
8996fb8af2 Add functionality to the OSSA BorrowedValue utility.
This abstraction is heavily used to ask about the current borrow scope
enclosing some uses. Give it the functionality it needs.

Add BorrowedValue::computeLiveness(PrunedLiveness). Get the borrow
scope's live range. A trivial 4-line implementation.

Cleanup BorrowedValue::areUsesWithinScope(). Quick check to see if a set
of uses known to be dominated by the borrow are within the borrow scope.

Add BorrowedValue::hasReborrow(). Is this local borrow scope
reborrowed? If not, then it's local scope-ending operations are the
end of its required lifetime.

Simplify BorrowedValue::gatherReborrows() to use OperandOwnership::Reborrow.
2021-10-06 15:48:08 -07: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
Andrew Trick
add3406cfe Move PrunedLiveness so it can be used as a lightweight OSSA helper.
For use in OwnershipUtils.
2021-10-06 09:23:02 -07:00
Andrew Trick
e85228491d Rename AccessedStorage to AccessStorage
to be consistent with AccessPath and AccessBase.

Otherwise, the arbitrary name difference adds constant friction.
2021-09-21 23:18:24 -07:00
Andrew Trick
ffb7ecc1f7 Add a BorrowedLifetimeExtender utility.
Handle SSA update (phi creation) when extending an owned lifetime over
a borrowed lifetime.

This is a layer of logic above BorrowedValue but below
OwnershipLifetimeExtender and other higher-level utilities.
2021-09-17 20:09:58 -07:00
Andrew Trick
0cfe74bba3 SIL API for OSSA terminator results.
Add OwnershipForwardingTermInst::createResult(SILBasicBlock, SILType)

Add SwitchEnumInst::createDefaultResult()

Add SwitchEnumInst::createOptionalSomeResult(), which handles most
compiler-generated switches.

Basic API for creating terminator results with consistent
ownership. This allows enabling OSSA verification on terminator
results. It fixes current issues, but is also a prerequisite for OSSA
simplify-cfg.

For switch_enum, this ensures that the default argument consistently
either forwards the original value, or handles the payload of the
unique case (the unique payload was already being inferred for
ownership, but the block argument was inconsistent with that fact).

switch_enum and checked_cast_br specify their forwarding
ownership. This can differ from their operand ownership.

For example:

    %e = enum $Optional<AnyObject>, #Optional.none!enumelt
    switch_enum %e : $Optional<AnyObject>,
                     case #Optional.some!enumelt: bb2...
  bb2(%arg : @owned T):

Independent forwarding ownership is only supported with terminators in this
change, but in the near term it will be used for all forwarding
operations to support implicit borrow scopes.
2021-09-07 10:20:14 -07:00
Meghana Gupta
2282160e5e Fix swift::getSingleBorrowIntroducingValue in the case it can encounter .none values in the def-use chain (#39144) 2021-09-02 17:40:06 -07:00
Meghana Gupta
42f339f793 Fix ownership verifier to handle is_unique as a valid use of interior pointer op (#38838) 2021-08-11 14:07:07 -07:00
Andrew Trick
a6cb54511a Add a tiny BorrowedAddress utility.
Determines whether an address might be inside a borrowed scope. If so,
then any address substitution needs to find that scope boundary to
avoid violating its basic guarantee that all uses are within scope.
2021-08-09 11:43:41 -07:00
Andrew Trick
88df7833af Add InteriorPointer::ProjectBox.
InteriorPointer needs to handle all access base kinds that may be borrowed.
2021-08-07 15:26:47 -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
Erik Eckstein
4affa11604 OwnershipUtils: let visitTransitiveEndBorrows work with a BorrowedValue.
... and not only with a begin_borrow
2021-05-18 08:56:22 +02:00
Andrew Trick
4e048a85a6 Expose findInnerTransitiveGuaranteedUses 2021-03-18 00:14:13 -07:00
Andrew Trick
3625a680b5 Fix an infinite loop in the SIL verifier.
This was an obvious thinko that must not have been hit yet in practice.
2021-02-24 21:23:40 -08:00
Michael Gottesman
27cd40b339 [ownership] When looking at an interior pointer's uses, look through store_borrow.
The store_borrow's result is a sub-interior pointer that ensures that any uses
of the interior pointer are within the lifetime of the borrowed value that is
being stored. But fundamentally this is just embedding lifetime ownership on
def-use edges and once ossa is lowered the result is just the destination
address. So it makes sense to include the uses of the result of the store_borrow
as the dest's uses.
2021-02-14 22:06:39 -08:00
Michael Gottesman
b7f5aac731 [ownership] Delete dead code that explicitly handles interior pointers open_existental_box, store_borrow.
These both are already classified as interior pointers. Thus, we would have
already handled them at the top of the loop where we handle interior pointer
operands.
2021-02-14 21:32:12 -08:00
Michael Gottesman
62d554669c [ownership] Rename OwnershipForwardingMixin::{get,set}OwnershipKind() -> {get,set}ForwardingOwnershipKind().
TLDR: This is just an NFC rename in preparation for changing
SILValue::getOwnershipKind() of any forwarding instructions to return
OwnershipKind::None if they have a trivial result despite forwarding ownership
that isn't OwnershipKind::None (consider an unchecked_enum_data of a trivial
payload from a non-trivial enum).

This ensures that one does not by mistake use this routine instead of
SILValue::getOwnershipKind(). The reason why these two things must be
distinguished is that the forwarding ownership kind of an instruction that
inherits from OwnershipForwardingMixin is explicitly not the ValueOwnershipKind
of the result of the instruction. Instead it is a separate piece of state that:

1. For certain forwarding instructions, defines the OwnershipConstraint of the
forwarding instruction.

2. Defines the ownership kind of the result of the value. If the result of the
value is non-trivial then it is exactly the set ownership kind. If the result is
trivial, we use OwnershipKind::None instead. As an example of this, consider an
unchecked_enum_data that extracts from a non-trivial enum a trivial payload:

```
enum Either {
case int(Int)
case obj(Klass)
}

%1 = load_borrow %0 : $*Either
%2 = unchecked_enum_data %1 : $Either, #Either.int!enumelt.1 // Int type
end_borrow %1 : $Either
```

If we were to identify the forwarding ownership kind (guaranteed) of
unchecked_enum_data with the value ownership kind of its result, we would
violate ownership since we would be passing a guaranteed value to the operand of
the unchecked_enum_data that will only accept values with
OwnershipKind::None. =><=.
2021-02-04 16:53:50 -08:00
Meghana Gupta
10492c9efc Merge pull request #35718 from meg-gupta/dceossafixespr
Fixes for OSSA DCE
2021-02-04 15:16:13 -08:00
Meghana Gupta
a78acfe4b0 Disable handling of nested borrows in DCE
Nested borrow handling can be complex in the presence of reborrows. So
it is not handled currently.
2021-02-03 11:38:40 -08:00
Meghana Gupta
9dd3ce5545 Add a new utility findTransitiveReborrowBaseValuePairs
This visits unique pairs of reborrowPhi and its base value.
The code for the utility is mostly refactored from the ReborrowVerifier.

This utility will be used later in DCE.
2021-02-03 11:38:03 -08:00
Michael Gottesman
ed368ab7d9 [sil-combine] Update COWBufferForReading for OSSA.
I was able to use the interior pointer operand API to great effect here.
2021-02-02 15:54:44 -08:00
Michael Gottesman
6684934702 [ownership] Change BorrowedValue::visitInteriorPointerOperand to pass IntPtrOperand as a value, not a const ref.
1. The reason to do this is that an InteriorPointerOperand is a value type.
2. Sometimes one wants to be able to use the IntPtrOperand that is not a const &
   and the value type formulation always works.

Functionality wise, this is NFCI.
2021-02-02 15:54:44 -08:00
Andrew Trick
2095c0cf04 OSSA: Use a public explicit constructor for BorrowedValue. 2021-02-01 18:03:24 -08:00
Andrew Trick
caefb9afaa Centralize and document low-level OSSA utilities
...for handling borrow scopes:

- find[Extended]TransitiveGuaranteedUses

- BorrowingOperand::visit[Extended]ScopeEndingUses

- BorrowedValue BorrowingOperand::getBorrowIntroducingUserResult()

And document the logic.

Mostly NFC in this commit, but more RAUW cases should be correctly
handled now.

Particularly, ensure that we can cleanly handle all manner of
reborrows. This is necessary to ensure both CanonicalizeOSSA and
replace-all-uses higher-level utilities handle all cases.

This generalizes some of the logic in CanonicalizeOSSA so it can be
shared by other high-level OSSA utilities.

These utilities extend the fundamental BorrowingOperand and
BorrowedValue functionality that has been designed recently. It builds
on and replaces a mix of piece-meal functionality that was needed
during bootstrapping. These APIs are now consistent with the more
recently designed code. It should be obvious what they mean and how to
use them, should be very hard to use them incorrectly, and should be
as efficient as possible, since they're fundamental to other
higher-level utilities.

Most importantly, there were several very subtle correctness issues
that were not handled cleanly in a centralized way. There are now a
mix of higher-level utilities trying to use this underlying
functionality, but it was hard to tell if all those higher-level
utilities were covering all the subtle cases:

- checking for PointerEscapes everywhere we need to

- the differences between uses of borrow introducers and other
  guaranteed values

- handling the uses of nested borrow scopes

- transitively handling reborrows

- the difference between nested and top-level reborrows

- forwarding destructures (which can cause exponential explosion)

In short, I was fundamentally confused and getting things wrong before
designing these utilities.
2021-02-01 18:03:24 -08:00
Erik Eckstein
9c225e136d OwnershipUtils: check for SILInstructionKind instead of SILNodeKind
This resolves a FIXME.
Also, use `getDefiningInstruction()` instead of `getRepresentativeSILNodeInObject()`

NFC
2021-01-27 16:40:14 +01:00
Erik Eckstein
ddd0f4d3a9 SIL: replace SmallPtrSet<SILBasicBlock *> with BasicBlockSet in LinearLifetimeChecker
This makes it unnecessary to share a single instance of visited blocks across multiple calls the the checker.
2021-01-27 10:31:17 +01:00
Eric Miotto
8e7f9c9cbd Revert "SIL: let SingleValueInstruction only inherit from a single SILNode." 2021-01-26 10:02:24 -08:00
Erik Eckstein
f812a2a775 OwnershipUtils: check for SILInstructionKind instead of SILNodeKind
This resolves a FIXME.
Also, use `getDefiningInstruction()` instead of `getRepresentativeSILNodeInObject()`

NFC
2021-01-25 09:30:04 +01:00
Andrew Trick
a2fac95f9f OSSA ownership optimization RAUW utility fixes.
Verify that the OwnershipRAUWUtility always preserves the original
borrow scope by exhaustively switching over OperandOwnership.

And related cleanup.
2021-01-23 18:15:58 -08:00
Michael Gottesman
73ba521e56 [ownership] Add a new API to OwnershipFixupContext::replaceAllAddressUsesFixingInteriorPointerOwnership.
In OSSA, we enforce that addresses from interior pointer instructions are scoped
within a borrow scope. This means that it is invalid to use such an address
outside of its parent borrow scope and as a result one can not just RAUW an
address value by a dominating address value since the latter may be invalid at
the former. I foresee that I am going to have to solve this problem and so I
decided to write this API to handle the vast majority of cases.

The way this API works is that it:

1. Computes an access path with base for the new value. If we do not have a base
value and a valid access path with root, we bail.

2. Then we check if our base value is the result of an interior pointer
instruction. If it isn't, we are immediately done and can RAUW without further
delay.

3. If we do have an interior pointer instruction, we see if the immediate
guaranteed value we projected from has a single borrow introducer value. If not,
we bail. I think this is reasonable since with time, all guaranteed values will
always only have a single borrow introducing value (once struct, tuple,
destructure_struct, destructure_tuple become reborrows).

4. Then we gather up all inner uses of our access path. If for some reason that
fails, we bail.

5. Then we see if all of those uses are within our borrow scope. If so, we can
RAUW without any further worry.

6. Otherwise, we perform a copy+borrow of our interior pointer's operand value
at the interior pointer, create a copy of the interior pointer instruction upon
this new borrow and then RAUW oldValue with that instead. By construction all
uses of oldValue will be within this new interior pointer scope.
2021-01-17 20:08:24 -08:00
Michael Gottesman
2ae43f97af [ownership] Eliminate Optional return value APIs from OwnershipUtils in favor of an Invalid enum case.
Should be NFC.
2021-01-14 11:02:10 -08:00
Michael Gottesman
ee17f5e8f6 [ownership] Rename OwnershipForwardingInst -> OwnershipForwardingMixin and eliminate support for isa<> and dyn_cast<>.
Instead, I just added some static helper methods that perform the same
operations without needing to deal with generics/etc on OwnershipForwardingMixin
itself. The reason why I did this is that this Mixin is not part of the SILNode
heirarchy so we shouldn't use utilities tied to the SILNode hierarchy.
2021-01-13 10:43:41 -08:00
Michael Gottesman
31c9d769f9 [ownership] Make ForwardingOperand truly a loose wrapper around an operand.
This implies making -> and * return an Operand * instead of an
OwnershipForwardingInst. So one can thus do:

ForwardingOperand op;
op.myForwardingOperandMethod();
op->myOperandMethod();
2021-01-13 10:43:41 -08:00
Andrew Trick
ab42f753f7 Remove OperandOwnership::NestedBorrow.
Now that OperandOwnership determines the operand constraints, it
doesn't make sense to distinguish between Borrow and NestedBorrow at
this level. We want these uses to automatically convert between the
nested/non-nested state as the operand's ownership changes. The use
does not need to impose any constraint on the ownership of the
incoming value.

For algorithms that need to distinguish nested borrows, it's still
trivial to do so.
2021-01-01 19:22:19 -08:00
Andrew Trick
ce2a7cfe0e Clearly discriminate OperandOwnership::NonUse and TrivialUse.
A NonUse operand does not use the value itself, so it ignores
ownership and does not require liveness. This is for operands that
represent dependence on a type but are not actually passed the value
of that type (e.g. they may refer an open_existential). This could be
used for other dependence-only operands in the future.

A TrivialUse operand has undefined ownership semantics aside from
requiring liveness. Therefore it is only legal to pass the use a value
with ownership None (a trivial value). Contrast this with things like
InstantaneousUse or BitwiseEscape, which just don't care about
ownership (i.e. they have no ownership semantics.

All of the explicitly listed operations in this category require
trivially typed operands. So the meaning is obvious to anyone
adding SIL operations and updating OperandOwnership.cpp, without
needing to decifer the value ownership kinds.
2021-01-01 19:22:10 -08:00
Michael Gottesman
368f8acc4b [sil] Eliminate a confusing optional method result by changing type dependent operands to have OwnershipKind::None instead of returning Optional::None from Operand::getOperandOwnership().
This eliminates when talking about this API an ambiguity in between
Optional::None (the C++ ADT) and OwnershipKind::None (the ownership kind).
2020-12-18 19:33:27 -08:00
Andrew Trick
84768bcdb3 OSSA: Add requirements on Unowned uses.
Clarify which uses are allowed to take Unowned values. Add enforcement
to ensure that Unowned values are not passed to other uses.

Operations that can take unowned are:

- copy_value
- apply/return @unowned argument
- aggregates (struct, tuple, destructure, phi)
- forwarding operations that are arbitrary type casts

Unowned values are currently borrowed within ObjC deinitializers
materialized by the Swift compiler. This will be banned as soon as
SILGen is fixed.
2020-12-17 21:08:56 -08:00
Andrew Trick
b1dba2554e Introduce OperandOwnership to classify OSSA uses.
Migrating to this classification was made easy by the recent rewrite
of the OSSA constraint model. It's also consistent with
instruction-level abstractions for working with different kinds of
OperandOwnership that are being designed.

This classification vastly simplifies OSSA passes that rewrite OSSA
live ranges, making it straightforward to reason about completeness
and correctness. It will allow a simple utility to canonicalize OSSA
live ranges on-the-fly.

This avoids the need for OSSA-based utilities and passes to hard-code
SIL opcodes. This will allow several of those unmaintainable pieces of
code to be replaced with a trivial OperandOwnership check.

It's extremely important for SIL maintainers to see a list of all SIL
opcodes associated with a simple OSSA classification and set of
well-specified rules for each opcode class, without needing to guess
or reverse-engineer the meaning from the implementation. This
classification does that while eliminating a pile of unreadable
macros.

This classification system is the model that CopyPropagation was
initially designed to use. Now, rather than relying on a separate
pass, a simple, lightweight utility will canonicalize OSSA
live ranges.

The major problem with writing optimizations based on OperandOwnership
is that some operations don't follow structural OSSA requirements,
such as project_box and unchecked_ownership_conversion. Those are
classified as PointerEscape which prevents the compiler from reasoning
about, or rewriting the OSSA live range.

Functional Changes:

As a side effect, this corrects many operand constraints that should
in fact require trivial operand values.
2020-12-16 01:58:53 -08:00
Michael Gottesman
259d2bb182 [ownership] Commit a generic replaceAllUsesAndEraseFixingOwnership api and enable SimplifyInstruction on OSSA.
This is a generic API that when ownership is enabled allows one to replace all
uses of a value with a value with a differing ownership by transforming/lifetime
extending as appropriate.

This API supports all pairings of ownership /except/ replacing a value with
OwnershipKind::None with a value without OwnershipKind::None. This is a more
complex optimization that we do not support today. As a result, we include on
our state struct a helper routine that callers can use to know if the two values
that they want to process can be handled by the algorithm.

My moticiation is to use this to to update InstSimplify and SILCombiner in a
less bug prone way rather than just turn stuff off.

Noting that this transformation inserts ownership instructions, I have made sure
to test this API in two ways:

1. With Mandatory Combiner alone (to make sure it works period).

2. With Mandatory Combiner + Semantic ARC Opts to make sure that we can
   eliminate the extra ownership instructions it inserts.

As one can see from the tests, the optimizer today is able to handle all of
these transforms except one conditional case where I need to eliminate a dead
phi arg. I have a separate branch that hits that today but I have exposed unsafe
behavior in ClosureLifetimeFixup that I need to fix first before I can land
that. I don't want that to stop this PR since I think the current low level ARC
optimizer may be able to help me here since this is a simple transform it does
all of the time.
2020-12-09 11:53:56 -08:00
Michael Gottesman
09ae2ef071 [ownership] Centralize all info about SILInstruction forwarding in the SILInstruction class hierarchy itself.
This commit is doing a few things:

1. It is centralizing all decisions about whether an operand's owner instruction
or a value's parent instruction is forwarding in each SILInstruction
itself. This will prevent this information from getting out of sync.

2. This allowed me to hide the low level queries in OwnershipUtils.h that
determined if a SILNodeKind was "forwarding". I tried to minimize the amount of
churn in this PR and thus didn't remove the
is{Owned,Ownership,Guaranteed}Forwarding{Use,Value} checks. Instead I left them
alone but added in asserts to make sure that if the old impl ever returns true,
the neew impl does as well. In a subsequent commit, I am going to remove the old
impl in favor of isa queries.

3. I also in the process discovered that there were some instructions that were
being inconsistently marked as forwarding. All of the asserts in the PR caught
these and I fixed these inconsistencies.
2020-12-01 17:36:19 -08:00
Michael Gottesman
85965ed202 [semantic-arc] Optimize more lifetime joining when a copy_value, destroy_value are in the same block.
Specifically the optimization that is being performed here is the elimination of
lifetimes that hand off ownership in between two regions of code. Example:

```
%1 = copy_value %0
...
destroy_value %0
...
apply %consumingUser(%1)
```

We really want to handle this case since it is a natural thing that comes up in
programs and will let me eliminate the *evil* usage of emitDestroyValueOperation
in TypeLowering without needing to modify huge amounts of tests.
2020-11-25 21:57:24 -08:00
Michael Gottesman
63e43b6b2f [ownership] Rename BorrowingOperand::visitLocalEndScope{Instruction,Use}s(Operand *)
This originally trafficked in Instructions and for some reason the name was
never changed.

I also changed the result type to be a bool and added the ability for the passed
in closure to signal failure (and iteration stop) by returning false. This also
makes it possible to use visitLocalEndScopeUses in if statements which can be
useful.
2020-11-25 21:54:47 -08:00