Commit Graph

85 Commits

Author SHA1 Message Date
Meghana Gupta
e4b60db09a Merge pull request #80956 from meg-gupta/cposlog
[6.2] Reland #79707
2025-04-22 21:00:05 -07:00
Meghana Gupta
d295bf96c0 Fix crash in OSLogOptimization
A metatype need not always come from a metatype instruction. It can come from
a SILArgument. Fix the invalid cast operation in OSLogOptimization.

Fixes rdar://146160325
2025-04-21 12:03:16 -07:00
Meghana Gupta
adb809369f Reland #79707
Revert "Merge pull request #80767 from meg-gupta/reverttransparent"

This reverts commit 198a802719, reversing
changes made to 8eb43af590.
2025-04-21 11:23:00 -07:00
Meghana Gupta
c22acc530e [6.2] Revert #79707
Revert "Merge pull request #79707 from DougGregor/transparent-integer-conversions"

This reverts commit 9c2c4ea07f, reversing
changes made to 829e03c104.
2025-04-11 10:57:14 -07:00
Ravi Kandhadai
cbf804e9f3 [SILOpt][OSLog] Skip constant folding StaticString in the
OSLogOptimization pass

The OSLogOptimization pass constant evaluates and folds SIL instructions
that are inlined from the construction of the string interpolations passed
to the log calls, which enables replacing the dynamic format string construction
with a static format string. In addition to folding constant strings, it also folds
constant integers and arrays whose elements are constants. This change makes it
skip folding static strings, since they are already efficiently represented.

rdar://146028438
2025-03-12 07:40:07 -07:00
Slava Pestov
977b444eb3 AST: Add a new overload of getContextSubstitutionMap() 2024-07-10 13:28:26 -04:00
Slava Pestov
fae01d9776 AST: Remove ModuleDecl parameter from more places 2024-07-06 12:05:46 -04: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
Meghana Gupta
0fc2e1343e Create mark_dependence for array allocation in OSLogOptimization
With #70242 mark_dependence was added while emitting uninitialized array allocation
between the unsafe pointer and the array value returned.
Without it, we can end up with use after free of the unsafe pointer if the array's lifetime
is shortened. Along with this change, pattern matching of all array optimizations was updated to include
mark_dependence.

This change adds mark_dependence for uninitialized array allocation in OSLogOptimization which was left out previously.
With this, potential use-after-free of the unsafe pointer is prevented and all updated array optimizations apply
to the array created by OSLogOptimization.

Fixes rdar://122922902
2024-02-27 00:39:09 -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
Arnold Schwaighofer
edd7eaa0d7 OSLog: os_log strings should be in the __oslogstring section on machO
rdar://121384422
2024-01-26 08:30:56 -08:00
Nate Chandler
88a0bd7015 [OSLogOpt] Fix move_value handling. 2023-12-14 09:09:58 -08:00
Evan Wilde
309aed4925 Add SmallSetVector replacement
llvm::SmallSetVector changed semantics
(https://reviews.llvm.org/D152497) resulting in build failures in Swift.
The old semantics allowed usage of types that did not have an
`operator==` because `SmallDenseSet` uses `DenseSetInfo<T>::isEqual` to
determine equality. The new implementation switched to using
`std::find`, which internally uses `operator==`. This type is used
pretty frequently with `swift::Type`, which intentionally deletes
`operator==` as it is not the canonical type and therefore cannot be
compared in normal circumstances.

This patch adds a new type-alias to the Swift namespace that provides
the old semantic behavior for `SmallSetVector`. I've also gone through
and replaced usages of `llvm::SmallSetVector` with the
`Swift::SmallSetVector` in places where we're storing a type that
doesn't implement or explicitly deletes `operator==`. The changes to
`llvm::SmallSetVector` should improve compile-time performance, so I
left the `llvm::SmallSetVector` where possible.
2023-07-25 12:28:27 -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
Nate Chandler
8d8577e5b0 [SIL] Removed Indirect_In_Constant convention.
It is no different from @in.

Continue parse @in_constant in textual and serialized SIL, but just as
an alias for @in.
2022-12-09 21:54:00 -08:00
Nate Chandler
04471ffb46 [OSLogOpt] Fixed duplicated condition. 2022-12-09 16:11:29 -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
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
Erik Eckstein
97b2354be6 SIL: add needsStackProtection flags for address_to_pointer and index_addr instructions.
Also add new "unprotected" variants of the `addressof` builtins:
* `Builtin.unprotectedAddressOf`
* `Builtin.unprotectedAddressOfBorrow`
2022-09-08 08:42:22 +02: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
Ikko Ashimine
61e525e975 Fix typo in OSLogOptimization.cpp
initalize -> initialize
2022-05-05 01:15:52 +09:00
Erik Eckstein
6a020f8f15 Stabilize and simplify SIL linkage and serialization
The main point of this change is to make sure that a shared function always has a body: both, in the optimizer pipeline and in the swiftmodule file.
This is important because the compiler always needs to emit code for a shared function. Shared functions cannot be referenced from outside the module.
In several corner cases we missed to maintain this invariant which resulted in unresolved-symbol linker errors.

As side-effect of this change we can drop the shared_external SIL linkage and the IsSerializable flag, which simplifies the serialization and linkage concept.
2022-03-09 15:28:05 +01:00
Josh Learn
b376658b4a Refactor OSLogOptimization utility functions into a separate file 2022-01-13 12:16:32 -08:00
Andrew Trick
f9d31ca116 InstructionDeleter ctor moves callbacks to fix iterator invalidation
The InstructionDeleter needs to move the callbacks during construction
to prevent the client code from using the old callbacks.

Fixes iterator invalidation bugs.
2021-11-18 11:38:08 -08:00
Andrew Trick
c86d112891 Update #include for InstructionDeleter.h 2021-11-18 11:38:08 -08:00
Andrew Trick
dc867e4f3c Comment OSLogOptimization: add a FIXME to handle OSSA correctly 2021-10-03 19:49:58 -07:00
Kuba (Brecka) Mracek
87cc490c57 Allow identification of OSLogMessage by a @_semantics attribute instead of just name (#39455) 2021-09-27 13:54:40 -07:00
Andrew Trick
0f88e0f3cc Rewrite instruction deletion logic in many passes
Fix innumerable latent bugs with iterator invalidation and callback invocation.

Removes dead code earlier and chips away at all the redundant copies the compiler generates.
2021-06-02 07:38:27 -07:00
Michael Gottesman
7b55cbc669 [sil-optimizer] Make InstructionDeleter and related APIs to use an InstModCallback instead of a notification callback.
I recently have been running into the issue that many of these APIs perform the
deletion operation themselves and notify the caller it is going to delete
instead of allowing the caller to specify how the instruction is deleted. This
causes interesting semantic issues (see the loop in deleteInstruction I
simplified) and breaks composition since many parts of the optimizer use
InstModCallbacks for this purpose.

To fix this, I added a notify will be deleted construct to InstModCallback. In a
similar way to the rest of it, if the notify is not set, we do not call any code
implying that we should have good predictable performance in loops since we will
always skip the function call.

I also changed InstModCallback::deleteInst() to notify before deleting so we
have a default safe behavior. All previous use sites of this API do not care
about being notified and the only new use sites of this API are in
InstructionDeleter that perform special notification behavior (it notifies for
certain sets of instructions it is going to delete before it deletes any of
them). To work around this, I added a bool to deleteInst to control this
behavior and defaulted to notifying. This should ensure that all other use sites
still compose correctly.
2021-04-26 16:37:43 -07:00
Azoy
9ed732f0ab Introduce isDecl and getDeclType
fix enum logic issue

fix tests

guard against null types
2021-04-20 02:22:16 -04:00
Slava Pestov
7ccc41a7b7 SIL: Preliminary support for 'apply [noasync]' calls
Refactor SILGen's ApplyOptions into an OptionSet, add a
DoesNotAwait flag to go with DoesNotThrow, and sink it
all down into SILInstruction.h.

Then, replace the isNonThrowing() flag in ApplyInst and
BeginApplyInst with getApplyOptions(), and plumb it
through to TryApplyInst as well.

Set the flag when SILGen emits a sync call to a reasync
function.

When set, this disables the SIL verifier check against
calling async functions from sync functions.

Finally, this allows us to add end-to-end tests for
rdar://problem/71098795.
2021-03-04 22:41:46 -05:00
Erik Eckstein
fe10f98cf0 SIL: rename the SILBitfield.h header file to BasicBlockBits.h
NFC
2021-02-12 11:15:55 +01:00
Josh Learn
b4a7475d8e [os_log][SIL Optimizer] Modify OSLogOptimization pass to skip folding on evaluation failure of non-strings and mark array.finalize_intrinsic as not foldable 2021-02-01 15:18:49 -08:00
Erik Eckstein
f48191966c SILOptimizer: use BasicBlockSet instead of SmallPtrSet in various transformations.
It reduces compile time.
2021-01-27 10:31:17 +01:00
Erik Eckstein
3e8612b0d3 SILOptimizer: use the BasicBlockFlag utility in ValueLifetimeAnalysis 2021-01-21 21:31:41 +01:00
Michael Gottesman
c026e95cce [ownership] Extract out SILOwnershipKind from ValueOwnershipKind into its own type and rename Invalid -> Any.
This makes it easier to understand conceptually why a ValueOwnershipKind with
Any ownership is invalid and also allowed me to explicitly document the lattice
that relates ownership constraints/value ownership kinds.
2020-11-10 14:29:11 -08:00
Erik Eckstein
79913b9595 Don't "finalize" the empty-array singleton.
Array literals only need to be finalized, if the array is really allocated.
In case of zero elements, no allocation is done, but the empty-array singleton is used.
"Finalization" means to emit an end_cow_mutation instruction on the array.
As the empty-array singleton is a read-only and shared object, it's not legal to do a end_cow_mutation on it.
2020-07-03 15:56:50 +02:00
Erik Eckstein
9168b81a17 Don't require the stdlib to contain the _finalizeUninitializedArray intrinsic function.
Prevent SILGen to crash if the compiler is used with a stdlib which does not have the _finalizeUninitializedArray intrinsic function.

rdar://problem/64195028
2020-06-10 13:26:16 +02:00
Erik Eckstein
1559fe333f SIL: a new library intrinsic to "finalize" array literals
For COW support in SIL it's required to "finalize" array literals.
_finalizeUninitializedArray is a compiler known stdlib function which is called after all elements of an array literal are stored.
This runtime function marks the array literal as finished.

  %uninitialized_result_tuple = apply %_allocateUninitializedArray(%count)
  %mutable_array = tuple_extract %uninitialized_result_tuple, 0
  %elem_base_address = tuple_extract %uninitialized_result_tuple, 1
  ...
  store %elem_0 to %elem_addr_0
  store %elem_1 to %elem_addr_1
  ...
  %final_array = apply %_finalizeUninitializedArray(%mutable_array)

In this commit _finalizeUninitializedArray is still a no-op because the COW support is not used in the Array implementation yet.
2020-06-08 10:24:29 +02:00
Anthony Latsis
9fd1aa5d59 [NFC] Pre- increment and decrement where possible 2020-06-01 15:39:29 +03:00
Ravi Kandhadai
2e0457ab0d [OSLog Diagnostics] Improve diagnostics emitted in the SIL and Sema diagnostic passes
for the os log APIs. These improvements are aimed at covering some rare corner cases.
2020-04-18 15:29:22 -07:00
Ravi Kandhadai
a17b069075 [OSLogOptimization] Fix a use-after-free bug in the function
suppressGlobalStringTablePointerError of OSLogOptimization pass
that happens because of eagerly deleting instructions while
iterating on them. This was fixed using the InstructionDeleter
utility.
2020-04-18 13:23:08 -07:00
Ravi Kandhadai
2e4977f65f [OSLogOptimization] Improve SIL-level diagnostics generated for the
os log APIs, based on the fact that there is already a Sema check for
enforcing the user model.

Suppress the errors generated by for the _globalStringTablePointerBuiltin
when the OSLogOptimization pass emits diagnostics. This elimiantes the
cryptic error that always accompanies the diagnostics emitted by the
OSLogOptimization pass.
2020-04-17 23:30:17 -07:00
Ravi Kandhadai
fb943cca8a [OSLogOptimization] Make emitCodeForSymbolicValue function generate
code for closures iff the closure is not created by the caller function
where the code is generated. Otherwise, when the closure is created
by the caller, just reuse it after copying and extending its lifetime.

Before this change new closures were created as long as all captures
of the closures were symbolic constants. This patch updates it so that
even if all captures are symbolic constants no code is generated for
closures that are already available in the caller. This avoids doing
needless work and also fixes the following bug.

<rdar://problem/61465764>
2020-04-08 11:53:52 -07:00
Michael Gottesman
47e74473f1 [ownership] Rename BorrowScopeIntroducingValue -> BorrowedValue and BorrowScopeOperand -> BorrowingOperand.
Andy and I for some time have been discussing the right name for these two
"ownership concepts". What we realized is that the "ing" on
BorrowScopeIntroducingValue is very unfortunate since this value is the result
of a new borrow scope being introduced. So the name should be really:
BorrowScopeIntroducedValue. Given that is sort of unsatisfying, we settled on
the name BorrowedValue.

Once we found the name BorrowedValue, we naturally realized that
BorrowScopeOperand -> BorrowingOperand followed. This is because the operand is
the operand of the instruction that is creating the new borrow scope. So in a
sense the Operand is the "Use" that causes the original value to become
borrowed. So a BorrowingOperand is where the action is and is "active".
2020-03-18 19:43:30 -07:00
Ravi Kandhadai
e3a8a96469 [OSLogOptimization] Fix the symbolic closure folding code to only create
new closures when all captures of the symbolic closure, including address-typed
captures, are symbolic constants. For other closures, they must have been
autoclosures passed to the log call and therefore they need not be duplicated
but reused as such.

This eliminates the need to copy_value the non-constant captured values of
closures. Instead the closure itself is copied as a whole.

Fixes <rdar://problem/60344043>
2020-03-12 12:42:43 -07:00
Ravi Kandhadai
36deac4fbe [OSLogOptimization] Fix a crash in OSLogOptimization pass that happens
when a SIL address is captured in a closure passed to the log calls.

<rdar://problem/60015040>
2020-03-10 21:42:27 -07:00
Ravi Kandhadai
020c8281c2 [OSLogOptimization] Prevent the OSLogOptimization pass from crashing
when the log calls are invoked in unreachable code.

<rdar://problem/60014600>
2020-03-10 15:48:56 -07:00
Michael Gottesman
6e5f036bda [ownership] Create a single introducer version of getUnderlyingBorrowIntroducingValues and rename it to getAllBorrowIntroducingValues(...).
I also added a comment to getAllBorrowIntroducingValues(...) that explained the
situations where one could have multiple borrow introducing values:

1. True phi arguments.
2. Aggregate forming instructions.
2020-03-01 17:30:53 -08:00
Joe Groff
bdece4bae5 OSLogOptimization: Codegen array elements according to the correct maximally-abstracted element type 2020-02-24 12:14:21 -08:00