https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109950

            Bug ID: 109950
           Summary: can array subscripts be assumed to be non-negative?
           Product: gcc
           Version: 14.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: lh_mouse at 126 dot com
  Target Milestone: ---

There is a lot of historical code which has been using `int` for array indexes:

```
extern int data[];
extern int next;

int
test_function(int* outptr)
  {
    *outptr = data[next];
    return next >= 0;
  }
```

In this example, the value of `next` is used as an array index. Despite the
unknown size, elements in an array can't have negative indexes, so maybe here
`next >= 0` can be optimized to a constant?


Specifically about x86_64, there is some more optimization that we can do: The
value of `next` can be loaded into a 32-bit register, zeroing the upper half
implicitly, without using a sign-extension instruction, as in machine code:

```
48 63 05 IMM32   ; movsxd rax, dword ptr [rip + IMM32]
   8B 05 IMM32   ; mov    eax, dword ptr [rip + IMM32]
```

The former contains an operand size override prefix, takes up one more byte,
and costs an extra cycle to decode.

Reply via email to