From e130557d9fce5ae426c040a72786012bfce407a1 Mon Sep 17 00:00:00 2001 From: florian Date: Wed, 17 Apr 2024 23:29:13 +0200 Subject: [PATCH] * optimize x < length(arr) and x >= length(arr) as proposed in #40292 --- compiler/nadd.pas | 25 +++++++++++++++++++++++++ tests/webtbs/tw40292.pp | 12 ++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 tests/webtbs/tw40292.pp diff --git a/compiler/nadd.pas b/compiler/nadd.pas index 6bec18a2a8..f321893b97 100644 --- a/compiler/nadd.pas +++ b/compiler/nadd.pas @@ -1739,6 +1739,31 @@ implementation ; end; + { + compile x < length(arr) as x <= high(arr) + compile x >= length(arr) as x > high(arr) + + tested by tests/webtbs/tw40292.pp + } + if (nodetype in [ltn,gten]) and + (right.nodetype=inlinen) and (tinlinenode(right).inlinenumber=in_length_x) and + ((is_dynamic_array(tinlinenode(right).left.resultdef)) or + (is_open_array(tinlinenode(right).left.resultdef)) + ) then + begin + case nodetype of + ltn: + result:=caddnode.create(lten,left,cinlinenode.create(in_high_x,false,tinlinenode(right).left)); + gten: + result:=caddnode.create(gtn,left,cinlinenode.create(in_high_x,false,tinlinenode(right).left)); + else + Internalerror(2024041701); + end; + left:=nil; + tinlinenode(right).left:=nil; + exit; + end; + { using sqr(x) for reals instead of x*x might reduces register pressure and/or memory accesses while sqr() has no drawback } if diff --git a/tests/webtbs/tw40292.pp b/tests/webtbs/tw40292.pp new file mode 100644 index 0000000000..3708c9c6c5 --- /dev/null +++ b/tests/webtbs/tw40292.pp @@ -0,0 +1,12 @@ +var + arr: array of longint; + x: longint; +begin + x:=12+random(0); + setlength(arr,13+random(0)); + if (x < length(arr)) <> (x <= high(arr)) then + halt(1); + x:=13+random(0); + if (x >= length(arr)) <> (x > high(arr)) then + halt(2); +end.