dplassgit / d2lang

D2 is a strongly-typed, statically-typed, (mostly) inferred-type compiled language.
MIT License
6 stars 0 forks source link

Comparing strings to null is very expensive #218

Closed dplassgit closed 1 year ago

dplassgit commented 1 year ago

Testing s != null should be something like

  ; SOURCE LINE 1: __temp4 = s != __null
  ; Allocating __temp4 to RBX
  cmp QWORD RCX, 0
  setz BL

but instead it's

  ; SOURCE LINE 1: __temp4 = s != __null
  ; Allocating __temp4 to RBX
  ; if they're identical we can stop now
  cmp QWORD RCX, 0
  jne __next_strcmp_test_1
  mov BYTE BL, 0
  jmp __strcmp_short_circuit_0
  ; not identical; test for null

__next_strcmp_test_1:
  cmp QWORD RCX, 0
  jne __next_strcmp_test_2
  ; left is null, right is not
  mov BYTE BL, 1
  jmp __strcmp_short_circuit_0
  ; left is not null, test right

__next_strcmp_test_2:
  ; right is literal null
  mov BYTE BL, 1
  jmp __strcmp_short_circuit_0
  ; left and right both not null
  push RCX
  ; strcmp: BL = RCX != 0
  ; mov RCX, s is a nop
  xor RDX, RDX  ; instead of mov reg, 0
  sub RSP, 0x20
  call strcmp
  add RSP, 0x20
  cmp RAX, 0
  setnz BL  ; string !=
  pop RCX

__strcmp_short_circuit_0:

In StringCodeGenerator it should test against literal null MUCH earlier.

dplassgit commented 1 year ago

somehow it's broken

dplassgit commented 1 year ago

The "simple" compare was so complicated it didn't have enough "cases". Replacing with a table should be more resilient.