-
Notifications
You must be signed in to change notification settings - Fork 46
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
DRAFT: Fast paths for large, native strings #646
Draft
milseman
wants to merge
10
commits into
swiftlang:main
Choose a base branch
from
milseman:large_native_machinery
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
208740e
Align availability macro with OS versions
milseman 8e2f609
short-circuit Character.isASCII checks
milseman 8ac8313
Make benchmark try a few more times before giving up
milseman fe2795d
wip: General ASCII fast-paths for builtin character classes
milseman e43c2e3
WIP: sink some metrics
milseman 2ac070a
wip: refactor metrics out, and void their storage
milseman d5db3a6
wip: string internals
milseman 1c19f90
wip: set fastUTF8
milseman 9827389
wip: more of the fastUTF8 fast path work
milseman fe7352b
wip
milseman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -35,7 +35,7 @@ struct Processor { | |
/// of the search. `input` can be a "supersequence" of the subject, while | ||
/// `input[subjectBounds]` is the logical entity that is being searched. | ||
let input: Input | ||
|
||
/// The bounds of the logical subject in `input`. | ||
/// | ||
/// `subjectBounds` represents the bounds of the string or substring that a | ||
|
@@ -46,7 +46,7 @@ struct Processor { | |
/// `subjectBounds` is always equal to or a subrange of | ||
/// `input.startIndex..<input.endIndex`. | ||
let subjectBounds: Range<Position> | ||
|
||
/// The bounds within the subject for an individual search. | ||
/// | ||
/// `searchBounds` is equal to `subjectBounds` in some cases, but can be a | ||
|
@@ -62,7 +62,7 @@ struct Processor { | |
let instructions: InstructionList<Instruction> | ||
|
||
// MARK: Resettable state | ||
|
||
/// The current search position while processing. | ||
/// | ||
/// `currentPosition` must always be in the range `subjectBounds` or equal | ||
|
@@ -81,16 +81,15 @@ struct Processor { | |
|
||
var wordIndexCache: Set<String.Index>? = nil | ||
var wordIndexMaxIndex: String.Index? = nil | ||
|
||
var state: State = .inProgress | ||
|
||
var failureReason: Error? = nil | ||
|
||
// MARK: Metrics, debugging, etc. | ||
var cycleCount = 0 | ||
var isTracingEnabled: Bool | ||
let shouldMeasureMetrics: Bool | ||
var metrics: ProcessorMetrics = ProcessorMetrics() | ||
var metrics: ProcessorMetrics | ||
|
||
/// Set if the string has fast contiguous UTF-8 available | ||
let fastUTF8: UnsafeRawPointer? | ||
} | ||
|
||
extension Processor { | ||
|
@@ -116,15 +115,21 @@ extension Processor { | |
self.subjectBounds = subjectBounds | ||
self.searchBounds = searchBounds | ||
self.matchMode = matchMode | ||
self.isTracingEnabled = isTracingEnabled | ||
self.shouldMeasureMetrics = shouldMeasureMetrics | ||
|
||
self.metrics = ProcessorMetrics( | ||
isTracingEnabled: isTracingEnabled, | ||
shouldMeasureMetrics: shouldMeasureMetrics) | ||
|
||
self.currentPosition = searchBounds.lowerBound | ||
|
||
// Initialize registers with end of search bounds | ||
self.registers = Registers(program, searchBounds.upperBound) | ||
self.storedCaptures = Array( | ||
repeating: .init(), count: program.registerInfo.captures) | ||
|
||
// print(MemoryLayout<Processor>.size) | ||
self.fastUTF8 = input._unsafeFastUTF8?.baseAddress | ||
|
||
_checkInvariants() | ||
} | ||
|
||
|
@@ -144,8 +149,8 @@ extension Processor { | |
|
||
self.state = .inProgress | ||
self.failureReason = nil | ||
if shouldMeasureMetrics { metrics.resets += 1 } | ||
|
||
metrics.addReset() | ||
_checkInvariants() | ||
} | ||
|
||
|
@@ -156,6 +161,16 @@ extension Processor { | |
assert(subjectBounds.upperBound <= input.endIndex) | ||
assert(currentPosition >= searchBounds.lowerBound) | ||
assert(currentPosition <= searchBounds.upperBound) | ||
|
||
assert({ | ||
guard let utf8 = self.fastUTF8 else { return true } | ||
var copy = input | ||
return copy.withUTF8 { | ||
let base = UnsafeRawPointer($0.baseAddress!) | ||
return utf8 == base | ||
} | ||
}()) | ||
|
||
} | ||
} | ||
|
||
|
@@ -186,7 +201,7 @@ extension Processor { | |
currentPosition = idx | ||
return true | ||
} | ||
|
||
// Advances in unicode scalar view | ||
mutating func consumeScalar(_ n: Distance) -> Bool { | ||
guard let idx = input.unicodeScalars.index( | ||
|
@@ -265,11 +280,41 @@ extension Processor { | |
return true | ||
} | ||
|
||
@inline(never) | ||
@_effects(releasenone) | ||
func loadScalar() -> Unicode.Scalar? { | ||
currentPosition < end ? input.unicodeScalars[currentPosition] : nil | ||
guard currentPosition < end else { return nil } | ||
// if let utf8 = self.fastUTF8 { | ||
// let firstByte = utf8[currentPosition.encodedOffset] | ||
// if firstByte < 0x80 { | ||
// let returnValue = Unicode.Scalar(firstByte) | ||
// // TODO: More comprehensive assertion framework to test before and after | ||
// // TODO: unsafe-ish optimizations | ||
// assert(returnValue == input.unicodeScalars[currentPosition]) | ||
// | ||
// return returnValue | ||
// } | ||
// | ||
// } | ||
return input.unicodeScalars[currentPosition] | ||
} | ||
|
||
func _doMatchScalar(_ s: Unicode.Scalar, _ boundaryCheck: Bool) -> Input.Index? { | ||
guard currentPosition < end else { return nil } | ||
|
||
if s.isASCII, let utf8 = self.fastUTF8 { | ||
let nextByteIdx = input.utf8.index(after: currentPosition) | ||
if utf8.loadByte(currentPosition) == s.value { | ||
// TODO: comprehensive assertion framework | ||
assert(s == input.unicodeScalars[currentPosition]) | ||
if (!boundaryCheck || input.isOnGraphemeClusterBoundary(nextByteIdx)) { | ||
return nextByteIdx | ||
} | ||
} | ||
return nil | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TODO: add assertion to check fast-path produces same result as slow path |
||
} // 13-22ms, after: 22-25ms ??? | ||
// Now down to 3ms | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TODO: remove |
||
|
||
if s == loadScalar(), | ||
let idx = input.unicodeScalars.index( | ||
currentPosition, | ||
|
@@ -281,7 +326,7 @@ extension Processor { | |
return nil | ||
} | ||
} | ||
|
||
mutating func matchScalar(_ s: Unicode.Scalar, boundaryCheck: Bool) -> Bool { | ||
guard let next = _doMatchScalar(s, boundaryCheck) else { | ||
signalFailure() | ||
|
@@ -355,7 +400,7 @@ extension Processor { | |
_uncheckedForcedConsumeOne() | ||
return true | ||
} | ||
|
||
// Matches the next scalar if it is not a newline | ||
mutating func matchAnyNonNewlineScalar() -> Bool { | ||
guard let s = loadScalar(), !s.isNewline else { | ||
|
@@ -401,8 +446,8 @@ extension Processor { | |
storedCaptures = capEnds | ||
registers.ints = intRegisters | ||
registers.positions = posRegisters | ||
if shouldMeasureMetrics { metrics.backtracks += 1 } | ||
|
||
metrics.addBacktrack() | ||
} | ||
|
||
mutating func abort(_ e: Error? = nil) { | ||
|
@@ -436,23 +481,13 @@ extension Processor { | |
// TODO: What should we do here? | ||
fatalError("Invalid code: Tried to clear save points when empty") | ||
} | ||
|
||
mutating func cycle() { | ||
_checkInvariants() | ||
assert(state == .inProgress) | ||
|
||
#if PROCESSOR_MEASUREMENTS_ENABLED | ||
if cycleCount == 0 { | ||
trace() | ||
measureMetrics() | ||
} | ||
defer { | ||
cycleCount += 1 | ||
trace() | ||
measureMetrics() | ||
_checkInvariants() | ||
} | ||
#endif | ||
startCycleMetrics() | ||
defer { endCycleMetrics() } | ||
|
||
let (opcode, payload) = fetch().destructure | ||
switch opcode { | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TODO: investigate re-enabling this code, or even consider looking at all potential callers of
loadScalar
.