Skip to content

Commit 9dd4bda

Browse files
committed
help bounds checking to be eliminated for getindex(::Memory, ::Int)
Second try for PR #58741. This moves the `getindex(::Memory, ::Int)` bounds check to Julia, which is how it's already done for `getindex(::Array, ::Int)`, so I guess it's correct. Also deduplicate the bounds checking code while at it.
1 parent 36a4616 commit 9dd4bda

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

base/essentials.jl

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -377,13 +377,26 @@ macro _nospecializeinfer_meta()
377377
return Expr(:meta, :nospecializeinfer)
378378
end
379379

380+
function _checkbounds_array(::Type{Bool}, A::Union{Array, GenericMemory}, i::Int)
381+
@inline
382+
ult_int(bitcast(UInt, sub_int(i, 1)), bitcast(UInt, length(A)))
383+
end
384+
function _checkbounds_array(A::Union{Array, GenericMemory}, i::Int)
385+
@inline
386+
_checkbounds_array(Bool, A, i) || throw_boundserror(A, (i,))
387+
end
388+
380389
default_access_order(a::GenericMemory{:not_atomic}) = :not_atomic
381390
default_access_order(a::GenericMemory{:atomic}) = :monotonic
382391
default_access_order(a::GenericMemoryRef{:not_atomic}) = :not_atomic
383392
default_access_order(a::GenericMemoryRef{:atomic}) = :monotonic
384393

385-
getindex(A::GenericMemory, i::Int) = (@_noub_if_noinbounds_meta;
386-
memoryrefget(memoryrefnew(memoryrefnew(A), i, @_boundscheck), default_access_order(A), false))
394+
function getindex(A::GenericMemory, i::Int)
395+
@_noub_if_noinbounds_meta
396+
(@_boundscheck) && _checkbounds_array(A, i)
397+
memoryrefget(memoryrefnew(memoryrefnew(A), i, false), default_access_order(A), false)
398+
end
399+
387400
getindex(A::GenericMemoryRef) = memoryrefget(A, default_access_order(A), @_boundscheck)
388401

389402
"""
@@ -949,13 +962,13 @@ end
949962
# linear indexing
950963
function getindex(A::Array, i::Int)
951964
@_noub_if_noinbounds_meta
952-
@boundscheck ult_int(bitcast(UInt, sub_int(i, 1)), bitcast(UInt, length(A))) || throw_boundserror(A, (i,))
965+
@boundscheck _checkbounds_array(A, i)
953966
memoryrefget(memoryrefnew(getfield(A, :ref), i, false), :not_atomic, false)
954967
end
955968
# simple Array{Any} operations needed for bootstrap
956969
function setindex!(A::Array{Any}, @nospecialize(x), i::Int)
957970
@_noub_if_noinbounds_meta
958-
@boundscheck ult_int(bitcast(UInt, sub_int(i, 1)), bitcast(UInt, length(A))) || throw_boundserror(A, (i,))
971+
@boundscheck _checkbounds_array(A, i)
959972
memoryrefset!(memoryrefnew(getfield(A, :ref), i, false), x, :not_atomic, false)
960973
return A
961974
end

0 commit comments

Comments
 (0)