@_semantics("array.check_subscript") is elided in my code

Hiya,

Here with the strange questions again! In my sample code, I'm not seeing the behaviour I expect from my standard library code when subscripting Array. My version of _checkSubscript passes the subscript as an inout parameter. The underlying array buffer/storage checks within bounds and clips it to bounds if not. This usually works, but in some sample code like this...

var array3 = ["first time", "lucky"]
print(array3[9])

... the call to _checkSubscript seems to be elided during conversion from SIL to canonical SIL. This leaves a call to _getElement that runs out of bounds. I guessed that the compiler is optimising away the call to _checkSubscript. And, to confirm that, if I comment out the @_semantics attribute from the function, it all works again. But of course, I've now eliminated the possibility of the compiler optimising away bounds checks when they're not needed, which is a peformance degradation.

@inlinable
  // @_semantics("array.check_subscript")
  public // @testable
  func _checkSubscript

I'd like to work out if a) there is some documentation that describes how the compiler makes the decision to elide "array.check_subscript" calls or (more likely) b) work out how to breakpoint and step through the compiler to see what it's doing.

Probably this is one of those cases where my standard library behaviour is so far beyond what the developers of the Swift compiler considered "normal" behaviour (trapping), that their optimisations would not take this possibility into account. Possibly it's assumed the program would have trapped somehow before now.

As ever, any help you guys can give on my lonely, windswept, snowy corner of the Swift world... would be lovely. :)

Carl

3 Likes