Commit Graph

2037 Commits

Author SHA1 Message Date
swift-ci
da3824acd9 Merge pull request #39662 from meg-gupta/fixbeginapplyinl 2021-10-08 20:58:58 -07:00
Meghana Gupta
2658cbec9b Fix begin_apply inlining when there are no yields
In this PR, preFixUp function in SILCloner is added which can be
overidden by implementations so that the SIL is cleaned for `commonFixup` processing.
For begin_apply inlining, blocks split due to end_apply and abort_apply
are fixed when no yields are found.
2021-10-08 14:45:08 -07:00
Alex Hoppen
6e07ee8f90 Fix a couple of build warning
Fixes a couple of compiler warnings that occur frequently when building the compiler:
- Copy the nullability annotation definitions from `Visibility.h` to `BridgedSwiftObject.h` and wrap all code that contains nullability annotations in `SWIFT_BEGIN_NULLABILITY_ANNOTATIONS` and `SWIFT_END_NULLABILITY_ANNOTATIONS` (supressing the warning `type nullability specifier '_Nullable' is a Clang extension [-Wnullability-extension]`)
- Suppress warnings about using `$` (mangling prefix) as an identifier using pragmas (supressing the warning `'$' in identifier [-Wdollar-in-identifier-extension]`)
- Change the macro condition of `SWIFT_NODISCARD` from `__cplusplus >= 201402l` (which checked for >= C++14) to `__cplusplus > 201402l`. This appears to have been a copy-paste error from `LLVM_NODISCARD` (supressing the warning `use of the 'nodiscard' attribute is a C++17 extension [-Wc++17-extensions]`)
2021-10-08 10:11:33 +02:00
Andrew Trick
8ba105f5cb Use AddressOwnership in OSSA RAUW. Improves optimization.
This mainly simplifies the utility, but also improves optimization as
a side effect.

Update OSSA RAUW after replacing BorrowedAddress with AddressOwnership.

InteriorPointer is no longer needed. This simplifies the fixup
context. Eventually the fixup context will be very lightweight. This
is just the first step.
2021-10-07 15:48:25 -07:00
swift-ci
60dc24b9f5 Merge pull request #39577 from atrick/liveness-boundary 2021-10-06 13:02:21 -07:00
Andrew Trick
1bb27f6318 ValueLifetime: add a TODO cross-referencing a new utility 2021-10-06 09:23:17 -07:00
Andrew Trick
0bc30e6f49 Add ValueLifetimeBoundary::visitInsertionPoints
Given a computed ValueLifetimeBoundary, visit all the points at which
the lifetime needs to be terminated, e.g. via and end_borrow or
destroy_value.

Especially useful for creating a borrow scope over guaranteed uses.

This completely decouples the DeadBlocks analysis from the liveness
analysis.

It will allow phasing out the complex and bug-prone
ValueLifetimeAnalysis::Frontier API.
2021-10-06 09:23:17 -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
Meghana Gupta
2d7e20e599 Remove unused mode in OME 2021-10-05 14:19:58 -07:00
Andrew Trick
5928958fd1 NFC: Remove an unused JointPostDominanceSetComputer forward decl. 2021-10-03 19:49:57 -07:00
Nate Chandler
cac03a6e77 [SIL] Let addArgumentToBranch accept plural args.
Previously, the addArgumentToBranch only allowed one to add a single
additional argument to a branch.  It then verified the argument count.
That is a problem if multiple arguments have to be added to arrive at
the correct argument count.

Specifically, that was a problem when running Mem2Reg on a lexical
alloc_stack, where three new phi arguments are added.

Here, the function name is changed to addArgumentsToBranch (plural
arguments) and the function accepts a SmallVector<SILValue> rather than
a single SILValue, allowing one to add all the arguments that are
necessary in order to verify that the resulting number of arguments is
correct.
2021-09-27 20:29:45 -07:00
Nate Chandler
4ff34aab31 [SIL] Enabled printing canonical module.
To print the module, use the new llvm flag -sil-print-canonical-module
which parallels the existing flag -sil-view-canonical-cfg.  When that
flag is passed, the new pass ModulePrinter is added to the diagnostic
pass pipeline after mandatory diagnostics have run.  The new pass just
prints the module to stdout.
2021-09-22 12:35:41 -07:00
Andrew Trick
e460a7db84 Merge pull request #39389 from atrick/access-representation
Add AccessBase abstraction as OSSA helper
2021-09-22 08:58:07 -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
Robert Widmann
e545d7f760 Lift getCanonicalTypeInContext up to GenericSignature 2021-09-20 15:43:07 -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
Min-Yih Hsu
b769654305 Merge pull request #39082 from mshockwave/dev-deprecate-debug-val-addr
[SIL][DebugInfo] PATCH 3/3: Deprecate debug_value_addr SIL instruciton
2021-09-01 09:14:29 -07:00
Meghana Gupta
6c74c0ff2b Merge pull request #39097 from meg-gupta/rlefix
Fix an edge case in OSSA RLE for loops
2021-08-31 14:15:11 -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
Meghana Gupta
5b3c687bf1 Fix an edge case in OSSA RLE for loops
In OSSA RLE for loops, in certain cases SSAUpdater will not create a new
SILPhiArgument to be used as the forwarding value. Based on dominator info
it may return the newly copied available value as the forwarding value.
This newly copied available value in the dominating predecessor
will have destroy values at leaking blocks.

Rename makeNewValueAvailable to makeValueAvailable and handle users so that only
additional required destroy_values are inserted.
2021-08-31 09:47:42 -07:00
Erik Eckstein
8be0ca07c2 SIL optimizer: remove unbalanced retains/releases from immortal objects
ARC operations don't have an effect on immortal objects, like the empty array singleton or statically allocated arrays.
Therefore we can freely remove and retain/release instructions on such objects, even if there is no paired balanced ARC operation.

This optimization can only be done with a minimum deployment target of Swift 5.1, because in that version we added immortal ref count bits.

The optimization is implemented in libswift. Additionally, the remaining logic of simplifying strong_retain and strong_release is also ported to libswift.

rdar://81482156
2021-08-23 10:23:59 +02:00
Erik Eckstein
90c71ad002 libswift: improve and simplify pass invocation
* unify FunctionPassContext and InstructionPassContext
* add a modification API: PassContext.setOperand
* automatic invalidation notifications when the SIL is modified
2021-08-23 10:21:12 +02:00
Andrew Trick
b5b6dc6a7f Merge pull request #38864 from meg-gupta/fixinvalidrauwbug
Fix ownership rauw to not leave behind stale ownership fixup context
2021-08-16 18:19:33 -07:00
Meghana Gupta
5d6659cd6c Merge pull request #38875 from meg-gupta/fixcanonicalizesilcombine
Fix borrow canonicalization bugs
2021-08-16 11:28:29 -07:00
Meghana Gupta
883d145f06 Handle nil BorrowedValue during canonicalization 2021-08-13 13:06:51 -07:00
Meghana Gupta
d40c915489 Fix ownership rauw to not leave behind stale ownership fixup context
Ownership rauw uses a shared ownership fixup context to maintain state.
When ownership rauw fails, due to some invalid condition, we leave
behind stale data in this shared ownership fixup context.
This stale context can indvertantly affect the next rauw on addresses.
In addition to setting the ownership fixup context to nullptr, we
should also clear it so that it's internal data structures are
cleared.
2021-08-12 16:46:20 -07:00
Meghana Gupta
6bafc8498d Remove end_lifetime being considered as an end of scope marker (#38851)
OSSA rauw cleans up end of scope markers before rauw'ing.
This can lead to inadvertant deleting of end_lifetime, later
resulting in an ownership verifier error indicating a leak.

This PR stops treating end_lifetime scope ending like end_borrow/end_access.
2021-08-12 13:49:06 -07:00
Min-Yih Hsu
9a8f2ed642 [SILOptimizer][DebugInfo] Preliminary support for DIExpression in SROA and Mem2Reg
SROA and Mem2Reg now can leverage DIExpression -- op_fragment, more
specifically -- to generate correct debug info for optimized SIL. Some
important highlights:
 - The new swift::salvageDebugInfo, similar to llvm::salvageDebugInfo,
   tries to restore / transfer debug info from a deleted instruction.
   Currently I only implemented this for store instruction whose
   destination is an alloc_stack value.
 - Since we now have source-variable-specific SIL location inside a
   `debug_value` instruction (and its friends), this patch teaches
   SILCloner and SILInliner to remap the debug scope there in addition
   to debug scope of the instruction.
 - DCE now does not remove `debug_value` instruction whose associating
   with a function argument SSA value that is not used elsewhere. Since
   that SSA value will not disappear so we should keep the debug info.
2021-08-05 17:27:45 -07:00
Michael Gottesman
fa54b111b2 [siloptimizer] Add support for replaceAllInstUsesPairwiseWith to InstModCallbacks.
NOTE: Just like with RAUW, if setUseValueFunc is nullptr, we call
SILInstruction::replaceALlInstUsesPairwiseWith to ensure good performance.
2021-07-22 16:06:49 -07:00
Andrew Trick
8e4c27daaa BasicBlockCloner: support for updating DeadEndBlocks.
DeadEndBlocks is used by low-level OSSA utilities. It needs to be
valid whenever OSSA transformations is being done.
2021-07-17 18:31:25 -07:00
Andrew Trick
74e928b39e Add -enable-ossa-simplifycfg and -enable-ossa-jumpthread-simplifycfg
as temporary flags to gradually stage in OSSA tests.
2021-07-17 18:31:25 -07:00
Andrew Trick
cd55abba2c Merge pull request #38220 from atrick/rewrite-borrow-forward
Copy propagation redesign and the CanonicalizeBorrowScopes utility
2021-07-11 19:05:56 -07:00
Erik Eckstein
2385a97c79 SILSSAUpdater: use the InstructionDeleter utility for deleting branch instructions.
the SSA updater replaces branch instructions when adding phi arguments. For deleting the old instruction use the InstructionDeleter utility.
2021-07-08 15:29:14 +02: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
Andrew Trick
78dbe2b4bc Add a comment to ValueLifetimeBoundary
Explaining a footgun that I've forgotten to check for more than once.
2021-07-01 20:37:08 -07:00
Andrew Trick
d0443be70e Expose the InstructionDeleter's callbacks
so they don't need to be passed around on the side everywhere.
2021-07-01 20:36:02 -07:00
Andrew Trick
b734bb3a92 Expose hasOnlyEndOfScopeOrDestroyUses as a utility
for cross-file use.
2021-07-01 20:34:48 -07:00
Andrew Trick
825185de84 Move PtrWorklist into DAGNodeWorklist.h for use across files. 2021-07-01 20:32:06 -07:00
Andrew Trick
803d96f952 Allow NonLocalAccessBlockAnalysis verification to be conservative.
It's fine to allow some optimization of access markers without
invalidating this simple analysis.
2021-07-01 20:04:21 -07:00
Erik Eckstein
7ed04c3ba3 libswift: add CalleeAnalysis
Bridging to BasicCalleeAnalysis
2021-07-01 17:30:56 +02:00
Erik Eckstein
e096b2f14a BasicCalleeAnalysis: make the callee list datastructure more efficient
This avoids copying a SmallVector in case of multiple callees in the list.
Instead, just reference the callee list in the cache.
2021-07-01 17:16:47 +02:00
Erik Eckstein
20c63cc3f5 libswift: add AliasAnalysis 2021-07-01 17:16:47 +02:00
Michael Gottesman
18670fc389 [assembly-vision] Rename opt remark generator to assembly vision remark generator.
TLDR: The reason why I am doing this is that often times people confuse assembly
vision remarks for normal opt remarks. I want to accentuate that this is
actually trying to do something different than a traditional opt remark. To that
end I renamed things in the compiler and added a true attribute
`@_assemblyVision` to trigger the compiler to emit these remarks to help
everyone remember what this is in their ontology. I explain below the
difference.

----

Normal opt remarks work by the optimizer telling you if it succeeded or failed
to perform an optimization. Another way of putting this is that opt remarks is
trying to give back feedback to the user from an expert system about why it did
or not do something. There is inherently an act of interpretation in the
optimizer about whether or not to report an 'action' that it perpetrated to the
user.

Assembly Vision Remarks is instead trying to be an expert tool that acts like an
xray. Instead of telling the user about what the optimizer did, it is instead a
simple visitor that visits the IR and emits SourceLocations for where specific
hazards ending up in the program. In this sense it is just telling the user
where certain instructions ended up and using heuristics to relate this to
information at the IR level. To a get a sense of this difference, consider the
following Swift Code:

```
public class Klass {
    func doSomething() {}
}

var global: Klass = Klass()

@inline(__always)
func bar() -> Klass { global }

@_assemblyVision
@inline(never)
func foo() {
  bar().doSomething()
}
```

In this case, we will emit the following remarks:

```
test.swift:16:5: remark: begin exclusive access to value of type 'Klass'
    bar().doSomething()
    ^
test.swift:7:5: note: of 'global'
var global: Klass = Klass()
    ^
test.swift:16:9: remark: end exclusive access to value of type 'Klass'
    bar().doSomething()
        ^
test.swift:7:5: note: of 'global'
var global: Klass = Klass()
    ^
test.swift:16:11: remark: retain of type 'Klass'
    bar().doSomething()
          ^
test.swift:7:5: note: of 'global'
var global: Klass = Klass()
    ^
test.swift:16:23: remark: release of type 'Klass'
    bar().doSomething()
                      ^
test.swift:7:5: note: of 'global'
var global: Klass = Klass()
    ^
```

Notice how the begin/end exclusive access are marked as actually being before
the retain, release of global. That seems weird since exclusive access to memory
seems like something that should not escape an exclusivity scope... but in fact
this corresponds directly to what we eventually see in the SIL:

```
// test.sil
sil hidden [noinline] [_semantics "optremark"] @$ss3fooyyF : $@convention(thin) () -> () {
bb0:
  %0 = global_addr @$ss6globals5KlassCvp : $*Klass
  %1 = begin_access [read] [dynamic] [no_nested_conflict] %0 : $*Klass
  %2 = load %1 : $*Klass
  end_access %1 : $*Klass
  %4 = class_method %2 : $Klass, #Klass.doSomething : (Klass) -> () -> (), $@convention(method) (@guaranteed Klass) -> ()
  strong_retain %2 : $Klass
  %6 = apply %4(%2) : $@convention(method) (@guaranteed Klass) -> ()
  strong_release %2 : $Klass
  %8 = tuple ()
  return %8 : $()
} // end sil function '$ss3fooyyF'
```

and assembly,

```
// test.S
_$ss3fooyyF:
	pushq	%rbp
	movq	%rsp, %rbp
	pushq	%r13
	pushq	%rbx
	subq	$32, %rsp
	leaq	_$ss6globals5KlassCvp(%rip), %rdi
	leaq	-40(%rbp), %rsi
	xorl	%edx, %edx
	xorl	%ecx, %ecx
	callq	_swift_beginAccess
	movq	_$ss6globals5KlassCvp(%rip), %r13
	movq	(%r13), %rax
	movq	80(%rax), %rbx
	movq	%r13, %rdi
	callq	_swift_retain
	callq	*%rbx
	movq	%r13, %rdi
	callq	_swift_release
	addq	$32, %rsp
	popq	%rbx
	popq	%r13
	popq	%rbp
	retq
```

so as one can see what we are trying to do is inform the user of hazards in the
code without trying to reason about it, automated a task that users often have
to perform by hand: inspection of assembly to determine where runtime calls and
other hazards ended up.
2021-06-12 15:09:46 -07:00
Erik Eckstein
e8d408d036 libswift: implement SILCombine's global_value optimization as instruction pass in libswift.
But keeping the old visit function as legacy
2021-06-09 11:33:41 +02:00
Erik Eckstein
1010f1e2ae libswift: infrastructure to define "instruction" passes.
Instruction passes are basically visit functions in SILCombine for a specific instruction type.
With the macro SWIFT_INSTRUCTION_PASS such a pass can be declared in Passes.def.
SILCombine then calls the run function of the pass in libswift.
2021-06-09 11:33:41 +02:00
Erik Eckstein
6fe719624a libswift: implement the MergeCondFail pass in libswift
But keeping the old pass as legacy pass
2021-06-09 11:33:41 +02:00
Erik Eckstein
9c363fb807 libswift: add an example SILPrinter pass.
SILPrinter prints the SIL of a function.
It's and example pass which demonstrates the basic SIL API of libswift.
2021-06-09 11:33:41 +02:00
Erik Eckstein
14422cdb50 libswift: Add the StackList data structure
StackList is a very efficient data structure for worklist type things.
This is a port of the C++ utility with the same name.

Compared to Array, it does not require any memory allocations.
2021-06-09 11:33:41 +02:00
Erik Eckstein
81f5e2f467 libswift: Infrastructure to call libswift function passes from the SILOptimizer's PassManager
With the macro SWIFT_FUNCTION_PASS a new libswift function pass can be defined in Passes.def.
The SWIFT_FUNCTION_PASS_WITH_LEGACY is similar, but it allows to keep an original C++ “legacy” implementation of the pass, which is used if the compiler is not built with libswift.
2021-06-09 11:30:59 +02:00
Erik Eckstein
8ad3a89cc6 SILOptimizer: remove a few unused includes and declarations
NFC
2021-06-04 19:48:48 +02:00