<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/100793>100793</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            Modulo operation being incorrectly optimized out when working with custom section addresses
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          jace0x21
      </td>
    </tr>
</table>

<pre>
    I noticed with the following code that the modulo operation is optimized out at LTO time when compiled as so:

(This reproduces on Apple Silicon macOS, I haven't tested on other platforms)

`clang++ -fcf-protection=none -fno-stack-protector -fno-jump-tables -fpic -flto -arch x86_64 -O1 -o main main.cpp`

```
#include <stdio.h>

__attribute__ ((noinline)) __attribute__((section ("__TEXT,__" "custom"))) void random_function();

extern int __start_custom __asm("section$start$__TEXT$__" "custom");
extern int __stop_custom __asm("section$end$__TEXT$__" "custom");
size_t size = (uintptr_t)(&__stop_custom) - (uintptr_t)(&__start_custom);

void random_function() {
    __asm__ volatile(
        "nop\n\t"
 "nop\n\t"
        "nop\n\t"
    );
}

int main() {
    random_function();
    printf("Size: %ld\n", size);
 size_t remainder = (size) % 4;
    printf("Remainder: %ld\n", remainder);
}
```

At -O0 you get output like this:
```
Size: 9
Remainder: 1
```

But enabling optimization (-O1) results in:
```
Size: 9
Remainder: 0
```

Debugging it I discovered that at LTO time, `(size) % 4` is constant folded into 0. This optimization seems to be based on the ABI pointer alignment for integers being 4 on x86_64. However, in this case the custom section is not 4 byte aligned. It is unclear to me if this is an issue with clang's handling of inline asm or the backend code generators not aligning the custom section. 

I attached an LLVM IR file that was helpful in debugging the incorrect constant fold by running:
`opt -S -passes=instcombine ./test.ll`

[test.txt](https://github.com/user-attachments/files/16395146/test.txt)


</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJycVk9v4z4O_TTKhXDgyI6THHJomym2wAwKTIvF3gxZY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