Commit Graph

300 Commits

Author SHA1 Message Date
Ravi Kandhadai
8b217afcaf [Const Evaluator] Fix a minor bug in the copy constructor deletion of
`ConstExprStepEvaluator`.
2019-05-14 12:09:57 -07:00
Andrew Trick
aa6347c832 Merge pull request #24153 from atrick/fix-let-exclusivity
Add a SILGenCleanup pass and CanonicalizeInstruction utility.
2019-05-06 22:51:19 -07:00
Andrew Trick
ece096d91e Fix eraseFromParentWithdebugInsts to call a callback.
The recursivelyDeleteTriviallyDeadInstructions utility takes a
callBack to be called for every deleted instruction. However, it
wasn't passing this callBack to eraseFromParentWithdebugInsts. The
callback was used to update an iterator in some cases, so not calling
it resulted in iterator invalidation.

Doing this also cleans up the both APIs:
recursivelyDeleteTriviallyDeadInstructions and eraseFromParentWithdebugInsts.
2019-05-06 17:23:08 -07:00
ravikandhadai
a282b4513d Merge pull request #24488 from ravikandhadai/inliner-refactoring
[SIL Inlining] Extract out a reusable code snippet in PerformanceInliner into a utility function in SILInliner.
2019-05-06 15:13:23 -07:00
Andrew Trick
9aa2523393 Add a CanonicalizeInstruction utility.
CanonicalizeInstruction will be a superset of
simplifyInstruction (once all the transforms are fixed for ownership
SIL). Additionally, it will also include simple SSA-based
canonicalization that requires new instruction creation. It may not
perform any optimization that interferes with diagnostics or increases
compile time.

Canonicalization replaces simplifyInstruction in SILCombine so we can
easily factor some existing SILCombine transforms into canonicalization.
2019-05-06 09:36:07 -07:00
Ravi Kandhadai
bed34d65ad [SIL Inlining] Extract out a reusable code snippet in PerformanceInliner
into a utility function in SILInliner.
2019-05-03 15:00:41 -07:00
Arnold Schwaighofer
a5036a97df Fix generic specialization that can result in noreturn apply without unreachable
rdar://50393169
2019-05-02 16:12:21 -07:00
ravikandhadai
d912e3312e Merge pull request #24113 from ravikandhadai/constexpr-skip
[Const evaluator] Add support to "skip" instructions in step-wise evaluation
2019-05-02 15:52:05 -07:00
Ravi Kandhadai
b0e56f70f9 [Const evaluator] Enable stepwise constant evaluator to skip
instructions without evaluating them while conservatively accounting
for the effects of the skipped instructions on the interpreter state.
2019-04-30 15:36:29 -07:00
Slava Pestov
16d5716e71 SIL: Use the best resilience expansion when lowering types
This is a large patch; I couldn't split it up further while still
keeping things working. There are four things being changed at
once here:

- Places that call SILType::isAddressOnly()/isLoadable() now call
  the SILFunction overload and not the SILModule one.

- SILFunction's overloads of getTypeLowering() and getLoweredType()
  now pass the function's resilience expansion down, instead of
  hardcoding ResilienceExpansion::Minimal.

- Various other places with '// FIXME: Expansion' now use a better
  resilience expansion.

- A few tests were updated to reflect SILGen's improved code
  generation, and some new tests are added to cover more code paths
  that previously were uncovered and only manifested themselves as
  standard library build failures while I was working on this change.
2019-04-26 22:47:59 -04:00
Ravi Kandhadai
55e82004a2 [const evaluator] Expose the step-wise constant evaluation mode
(also referred to as flow-sensitive mode) so that the evaluator
can be used by clients to constant evaluate instructions in a
SILFunction body one by one following the flow of control.
2019-04-17 18:12:17 -07:00
swift-ci
c6f7f97ba1 Merge pull request #23981 from gottesmm/pr-d8251fee09379fbd0cee5696f7b97a85ca886cb2 2019-04-12 12:17:36 -07:00
Michael Gottesman
f7b014b95c [cast-opt] Rename CastOptimizer member vars to match the rest of the CastOptimizer.
Done using Xcode's refactoring engine.
2019-04-12 11:09:29 -07:00
ravikandhadai
28efe03fab Merge pull request #23456 from ravikandhadai/constexpr-local-allocation
[const evaluator] Parameterize allocation of symbolic values in the constant interpreter.
2019-04-11 15:14:09 -07:00
Erik Eckstein
8f47439148 PerformanceInliner: disable shortest-path-analysis for huge functions.
As the complexity of the analysis is more than linear with the number of blocks, disable it for functions with > 2000 basic blocks.
In this case inlining will be less aggressive.

SR-10209
rdar://problem/49522869
2019-04-10 10:37:37 -07:00
Ravi Kandhadai
bb7363da2e [const evaluator] Parameterize allocation of symbolic values in the
constant interpreter. Based on this, change to a short-lived bump
allocator for storing symbolic values in the pass that checks #assert.
2019-04-09 13:56:21 -07:00
Erik Eckstein
00599eeb3c Check for completeness of the SwiftOnoneSupport library
When compiling SwiftOnoneSupport, issue errors for missing functions which are expected in the module.
This ensures ABI compatibility.

rdar://problem/48924409
2019-03-25 14:57:03 -07:00
Slava Pestov
e9bd15f7fc SILOptimizer: More generic specializer plumbing for using the right resilience expansion
Also NFC for now.
2019-03-13 02:21:53 -04:00
Slava Pestov
8915f96e3e SIL: Replace SILType::isTrivial(SILModule) with isTrivial(SILFunction) 2019-03-12 01:16:04 -04:00
Slava Pestov
00b4662ab9 SILOptimizer: Clean up the generic specializer a bit 2019-03-12 01:16:04 -04:00
Slava Pestov
c791c4a137 SIL: SILUndef must be aware of the resilience expansion
The ownership kind is Any for trivial types, or Owned otherwise, but
whether a type is trivial or not will soon depend on the resilience
expansion.

This means that a SILModule now uniques two SILUndefs per type instead
of one, and serialization uses two distinct sentinel IDs for this
purpose as well.

For now, the resilience expansion is not actually used here, so this
change is NFC, other than changing the module format.
2019-03-12 00:30:35 -04:00
Michael Gottesman
ee02174f71 [cast-opt] Change optimize{Swift,ObjC}to{ObjC,Swift} to use SILDynamicCastInst.
I also debrided dead variables that resulted from eliminating the trampoline
argument code in optimizeBridgedCasts().
2019-03-04 10:48:13 -08:00
Michael Gottesman
fa4c38bf0c [cast-opt] Now that all users of optimizeBridgedCasts use the SILDynamicCastInst entrypoint, delete the old entrypoint and inline its body into the new entrypoint. 2019-03-03 16:33:12 -08:00
Slava Pestov
c5cf5c2c4b SILOptimizer: Remove isSimpleType()
This was checking if the type is a trivial type that is not a
class. However this was redundant because class types are not
trivial anyway.
2019-02-28 22:56:03 -05:00
Slava Pestov
112d1bd561 SILOptimizer: Small cleanups for devirtualizer
Where possible, pass around a ClassDecl or a CanType instead of a
SILType that might wrap a metatype; the unwrapping logic was
repeated in several places.

Also add a FIXME for a bug I found by inspection.
2019-02-28 22:40:54 -05:00
Michael Gottesman
98ed241ce5 [cast-optimizer] Add an "ApplySite" like data structure "SILDynamicCastInst" that abstracts over all dynamic cast instructions.
I am going to use this to refactor a bunch of the goop in the cast optimizer. At
a high level, we are really just performing a giant switch over the casts to
grab different state. We then take that state and we pass it into the bridge
cast optimizer.

To make such code more compact/easier to understand, I am adding in this commit
a type erased dynamic cast instruction type called "SILDynamicCastInst". In
subsequent commits, I wire up each of the individual instructions to it one at a
time.

As an additional advantage it will enable us to take advantage of covered
switches when ever in the future we introduce new casts.
2019-02-26 13:23:54 -08:00
Slava Pestov
23f7c4f6ee SILOptimizer: Fix potential crashes with uses of replaceLoadSequence()
This utility is generally a horrible idea but even worse the
callers were not doing anything to ensure the required
invariants actually held.

Add a new canReplaceLoadSequence() method and chek it in the
right places.
2019-02-21 23:06:21 -05:00
Michael Gottesman
0cdc2d6a35 [sil] Teach constant folding how to handle destructures and multiple value instructions.
I also ported the constant_propagation.sil tests over for ownership and updated
a few parts of the cast optimizer so that those tests pass with and without
ownership. I purposely only updated the parts of the cast optimizer that crashed
with ownership in the relevant test so that I can add new sil code coverage for
those uncovered code paths.
2019-02-12 20:15:02 -08:00
Michael Gottesman
0c7f5b3064 [cast-opt] Change optimizeMetatypeConversion to return a value and use the new
replace value uses action to make sure that we properly notify passes that we
made the change.

This fixes a latent bug where we were not notifying SILCombine about this
replacement.

Specifically:

-  auto replaceCast = [&](SingleValueInstruction *NewCast) {
-    assert(Ty.getAs<AnyMetatypeType>()->getRepresentation()
-           == NewCast->getType().getAs<AnyMetatypeType>()->getRepresentation());
-    MCI->replaceAllUsesWith(NewCast);
-    EraseInstAction(MCI);
-    return NewCast;
+  auto replaceCast = [&](SILValue newValue) -> SILValue {
+    assert(ty.getAs<AnyMetatypeType>()->getRepresentation() ==
+           newValue->getType().getAs<AnyMetatypeType>()->getRepresentation());
+    ReplaceValueUsesAction(mci, newValue);
+    EraseInstAction(mci);
+    return newValue;
   };

Notice how we use MCI->replaceAllUsesWith instead of one of our replace call
backs. SILCombine hooks these to know if it should re-run users.
2019-02-04 16:13:07 -08:00
Michael Gottesman
21e51edfad [cast-opt] Allow users to pass in a SILBuilderContext to the CastOptimizer.
NOTE: I changed all places that the CastOptimizer is created to just pass in
nullptr for now so this is NFC.

----

Right now the interface of the CastOptimizer is muddled and confused. Sometimes
it is returning a value that should be used by the caller, other times it is
returning an instruction that is meant to be reprocessed by the caller.

This series of patches is attempting to clean this up by switching to the
following model:

1. If we are optimizing a cast of a value, we return a SILValue. If the cast
fails, we return an empty SILValue().

2. If we are optimizing a cast of an address, we return a boolean value to show
success/failure and require the user to use the SILBuilderContext to get the
cast if they need to.
2019-02-04 12:59:44 -08:00
Michael Gottesman
a5b47e127d [cast-opt] Add a new callback: ReplaceValueUsesAction.
This is the first in a series of patches to update the cast optimizer for
ownership and multiple value instructions.

This specific patch is NFC.
2019-02-04 11:26:46 -08:00
Erik Eckstein
767ad5e70a Inliner: fix a stack nesting problem when inlining coroutines
Beside fixing the compiler crash, this change also improves the stack-nesting correction mechanisms in the inliners:

* Instead of trying to correct the nesting after each inlining of a callee, correct the nesting once when inlining is finished for a caller function.
This fixes a potential compile time problem, because StackNesting iterates over the whole function.
In worst case this can lead to quadratic behavior in case many begin_apply instructions with overlapping stack locations are inlined.

* Because we are doing it only once for a caller, we can remove the complex logic for checking if it is necessary.
We can just do it unconditionally in case any coroutine gets inlined.
The inliners iterate over all instruction of a function anyway, so this does not increase the computational complexity (StackNesting is roughly linear with the number of instructions).

rdar://problem/47615442
2019-02-01 08:32:19 -08:00
Erik Eckstein
787c35f165 SILOptimizer: correctly handle unreachable blocks in StackNesting.
Instead of some special treatment of unreachable blocks, model unreachable as implicitly deallocating all alive stack locations at that point.
This requires an additional forward-dataflow pass. But it now correctly models the problem and fixes a compiler crash.

rdar://problem/47402694
2019-01-25 11:29:21 -08:00
Michael Gottesman
671033ac7d [ssa-updater] Allow a user to set the InsertedPHIs list after construction.
I need this API so that I can conditionally handle the inserted phis.
2019-01-22 01:29:45 -08:00
Arnold Schwaighofer
84c17372c0 Add insertDestroyOfCapturedArguments to Local.h 2019-01-15 11:31:57 -08:00
Arnold Schwaighofer
df1eb708fb Fix StackNesting to work with partial_apply [stack] 2019-01-15 11:20:33 -08:00
Erik Eckstein
1072bb6bc6 SILCombine: fix a miscompile caused by dead-apply elimination
SILCombine ended up moving a strong_release past a dealloc_ref.
fixes https://bugs.swift.org/browse/SR-9627
rdar://problem/47153896
2019-01-14 09:00:00 -08:00
Andrew Trick
118a725d96 Generalize and cleanup code for existential specialization.
Generalizes the ConcreteExistentialInfo abstraction so it can be used
both by the ExistentialSpecializer and SILCombine, allowing redundant
code in ExistentialSpecializer.cpp to be deleted.

Splits OpenedArchetypeInfo from ConcreteExistentialInfo. Adds a
ConcreteOpenedArchetypeInfo convenience wrapper around them both, for
use wherever we were originally using ConcreteExistentialInfo.

Splits getAddressOfStackInit into getStackInitInst, This is cleaner and
allows both the ExistentialSpecializer and SILCombine to handle more
interesting cases in the future, like unconditional_checked_cast.

Creates utilities, initializeSubstitutionMap, and
initializeConcreteTypeDef to simplify an generalize
ConcreteExistentialInfo.

While rewriting ExistentialSpecializer to use the new
abstraction, I fixed a latent bug in which is was using a SIL
argument index as a function type parameter index (this would
have broken up if/when we decide to enable calls with indirect
results).
2019-01-02 08:44:37 -08:00
Andrew Trick
83950babc9 Merge pull request #21490 from atrick/fix-getobjc-after-free
Fix SILCombine metatype cast optimization to avoid extending lifetimes.
2018-12-21 11:22:19 -08:00
Andrew Trick
65c95dd840 Fix SILCombine metatype cast optimization to avoid extending lifetimes.
This cannot be correctly done as a SILCombine because it must create
new instructions at a previous location. Move the optimization into
CastOptimizer. Insert the new metatype instructions in the correct
spot. And manually do the replaceAllUsesWith and eraseInstruction
steps.

Fixes <rdar://problem/46746188> crash in swift_getObjCClassFromObject.
2018-12-21 09:52:38 -08:00
Ravi Kandhadai
92260f9a93 [Devirtualizer] Make the getWitnessMethodSubstitutions function of
Devirtualizer.cpp available to other passes.

This will enable the compile-time interpreter to use this functionality.
2018-12-20 12:27:19 -08:00
Adrian Prantl
ff63eaea6f Remove \brief commands from doxygen comments.
We've been running doxygen with the autobrief option for a couple of
years now. This makes the \brief markers into our comments
redundant. Since they are a visual distraction and we don't want to
encourage more \brief markers in new code either, this patch removes
them all.

Patch produced by

      for i in $(git grep -l '\\brief'); do perl -pi -e 's/\\brief //g' $i & done
2018-12-04 15:45:04 -08:00
Andrew Trick
984bd99b40 Fix SILCombine to devirtualize existentials wrapped in enum.
This allows Swift code to implement a fast path via a protocol type
check as follows:

  if let existentialVal = genericVal as? SomeProtocol {
    // do something fast.
  }

Fixes <rdar://problem/46322928> Failure to devirtualize a protocol
method applied to an opened existential blocks implemention of
DataProtocol.

Note: the approach of devirtualization via backward pattern matching
is fundamentally wrong and will never be fully general. It should be a
forward type propagation.
2018-12-02 00:39:55 -08:00
swift-ci
2ef35ac80e Merge pull request #19655 from apple/marcrasi-const-evaluator-part-1 2018-11-29 19:25:14 -08:00
Michael Gottesman
c65c540d71 Merge pull request #20819 from gottesmm/pr-f46c6ad2fee1ea70f7b25a8f6a89ab7af28c1404
[ownership] Ban ValueOwnershipKind::Any in preparation for eliminated ValueOwnershipKind::Trivial
2018-11-28 13:55:10 -08:00
Michael Gottesman
c9bb5161a1 [ownership] Change SILUndef to return Any ownership for trivial values and owned for non-trivial values.
This is in preparation for verifying that when ownership verification is enabled
that only enums and trivial values can have any ownership. I am doing this in
preparation for eliminating ValueOwnershipKind::Trivial.

rdar://46294760
2018-11-27 17:31:08 -08:00
Marc Rasi
44d7cdd4e6 constant interpreter: basic integer operations
Implements a constant interpreter that can deal with basic integer operations.

Summary of the features that it includes:
* builtin integer values, and builtin integer insts
* struct and tuple values, and insts that construct and extract them (necessary to use stdlib integers)
* function referencing and application (necessary to call stdlib integer functions)
* error handling data structures and logic, for telling you why your value is not evaluatable
* metatype values (not necessary for integers, but it's only a few extra lines, so I thought it would be more trouble than it's worth to put them in a separate PR)
* conditional branches (ditto)
2018-11-26 14:27:10 -08:00
Andrew Trick
702981f775 Fix MandatoryInlining to not be quadratic.
Inlining has always been quadratic for no good reason. There was a
special hack for single-block callees that allowed linear inlining.

Instead, the now iterates over blocks and instructions in reverse,
splitting blocks as it inlines. There no longer needs to be special
case for single block callees, and the inliner is linear for all kinds
of callees.

This further simplifies and cleans up the code. There are just a few
basic invariants that the common inliner needs to provide about how
blocks are split and laid out. We can do this if we don't add hacks
for special cases within the inliner. Those invariants allow the
inliner clients to be much simpler and more efficient.

PerformanceInliner still needs to be fixed.

Fixes SR-9223: Inliner exhibits slow compilation time with a large
static array.
2018-11-26 09:41:28 -08:00
Andrew Trick
9c46b2a053 Fix block merging after inlining to help avoid quadratic inlining.
A recent SILCloner rewrite removed a special case hack for single
basic block callee functions:

commit c6865c0dff
Merge: 76e6c4157e 9e440d13a6
Author: Andrew Trick <atrick@apple.com>
Date:   Thu Oct 11 14:23:32 2018

    Merge pull request #19786 from atrick/silcloner-cleanup

    SILCloner and SILInliner rewrite.

Instead, the new inliner simply merges trivial unconditional branches
after inlining the return block. This way, the CFG is always in
canonical state after inlining. This is more robust, and avoids
interfering with subsequent SIL passes when non-single-block callees
are inlined.

The problem is that inlining a series of calls within a large block
could result in interleaved block splitting and merging operations,
which is quadratic in the block size. This showed up when inlining the
tens of thousands of array subscript calls emitted for a large array
initialization.

The first half of the fix is to simply defer block merging until all
calls are inlined. We can't expect SimplifyCFG to run immediately
after inlining, nor would we want to do that, *especially* for
mandatory inlining. This fix instead exposes block merging as a
trivial utility.

Note: by eliminating some unconditional branches, this change could
reduce the number of debug locations emitted. This does not
fundamentally change any debug information guarantee, and I was unable
to observe any behavior difference in the debugger.
2018-11-26 09:41:28 -08:00
Arnold Schwaighofer
7e32c68e1d Add new SIL instruction for calling dynamically_replaceable funtions
%0 = dynamic_function_ref @dynamically_replaceable_function
  apply %0()
  Calls a [dynamically_replaceable] function.

  %0 = prev_dynamic_function_ref @dynamic_replacement_function
  apply %0
  Calls the previous implementation that dynamic_replacement_function
  replaced.
2018-11-06 09:53:22 -08:00