<html>
    <head>
      <base href="https://bugs.llvm.org/">
    </head>
    <body><table border="1" cellspacing="0" cellpadding="8">
        <tr>
          <th>Bug ID</th>
          <td><a class="bz_bug_link 
          bz_status_NEW "
   title="NEW - Unnecessary memory read in a loop"
   href="https://bugs.llvm.org/show_bug.cgi?id=43962">43962</a>
          </td>
        </tr>

        <tr>
          <th>Summary</th>
          <td>Unnecessary memory read in a loop
          </td>
        </tr>

        <tr>
          <th>Product</th>
          <td>clang
          </td>
        </tr>

        <tr>
          <th>Version</th>
          <td>trunk
          </td>
        </tr>

        <tr>
          <th>Hardware</th>
          <td>PC
          </td>
        </tr>

        <tr>
          <th>OS</th>
          <td>Linux
          </td>
        </tr>

        <tr>
          <th>Status</th>
          <td>NEW
          </td>
        </tr>

        <tr>
          <th>Severity</th>
          <td>enhancement
          </td>
        </tr>

        <tr>
          <th>Priority</th>
          <td>P
          </td>
        </tr>

        <tr>
          <th>Component</th>
          <td>LLVM Codegen
          </td>
        </tr>

        <tr>
          <th>Assignee</th>
          <td>unassignedclangbugs@nondot.org
          </td>
        </tr>

        <tr>
          <th>Reporter</th>
          <td>antoshkka@gmail.com
          </td>
        </tr>

        <tr>
          <th>CC</th>
          <td>llvm-bugs@lists.llvm.org, neeilans@live.com, richard-llvm@metafoo.co.uk
          </td>
        </tr></table>
      <p>
        <div>
        <pre>Consider the example:

int* f2(int** x) {
    int** max = x;
    for (int i =0 ; i < 5; ++ i) {
        ++ x;
        if (**max < **x) {
            max = x;
        }
    }
    return *max;
}

Clang with '-O2 -fno-unroll-loops' generates the following assembly:

f2(int**): # @f2(int**)
  mov eax, 8
  mov rcx, rdi
  jmp .LBB0_1
.LBB0_3: # in Loop: Header=BB0_1 Depth=1
  add rax, 8
  cmp eax, 48
  je .LBB0_4
.LBB0_1: # =>This Inner Loop Header: Depth=1
  mov rdx, qword ptr [rcx]
  mov edx, dword ptr [rdx]
  mov rsi, qword ptr [rdi + rax]
  cmp edx, dword ptr [rsi]
  jge .LBB0_3
  lea rcx, [rdi + rax]
  jmp .LBB0_3
.LBB0_4:
  mov rax, qword ptr [rcx]
  ret

That assembly has 4 memory reads in a loop.

However other compilers generate loops with only 3 reads, for example:
f2(int**):
  mov rax, QWORD PTR [rdi]
  lea rcx, [rdi+40]
.L3:
  mov rdx, QWORD PTR [rdi+8]
  add rdi, 8
  mov esi, DWORD PTR [rdx]
  cmp DWORD PTR [rax], esi
  cmovl rax, rdx
  cmp rcx, rdi
  jne .L3
  ret

Please improve the memory accesses.
Godbolt playground: <a href="https://godbolt.org/z/F-dJSX">https://godbolt.org/z/F-dJSX</a></pre>
        </div>
      </p>


      <hr>
      <span>You are receiving this mail because:</span>

      <ul>
          <li>You are on the CC list for the bug.</li>
      </ul>
    </body>
</html>