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

    <tr>
        <th>Summary</th>
        <td>
            folding snprintf with n greater than INT_MAX succeeds and fails to set errno
        </td>
    </tr>

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

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

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

<pre>
    As the following test case shows, LLVM folds calls to `snprintf` with a constant format string containing no formatting directives to its length.  This is done provided the bound (the second argument, `n`, to the function) is greater than the string length.  This is both overly aggressive and needlessly restrictive.  This issue is about the former.
```
@s = constant [4 x i8] c"123\00"

declare i32 @snprintf(i8*, i64, i8*, ...)

define i32 @f(i8* %d) {
  %f = getelementptr [4 x i8], [4 x i8]* @s, i32 0, i32 0
  %n = call i32 (i8*, i64, i8*, ...) @snprintf(i8* %d, i64 2147483648, i8* %f)
  ret i32 %n
}
```
The resulting IR of the function:
```
define i32 @f(i8* %d) {
  %1 = bitcast i8* %d to i32*
  store i32 3355185, i32* %1, align 1
  ret i32 3
}
```
However, as an extension to C, POSIX specifies that
> The _`snprintf()`_ function shall fail if:
>
> `[EOVERFLOW]`
>    [CX] The value of _`n`_ is greater than `{INT_MAX}`.

This requirement is violated by the folding above.  To conform, the optimization either needs to fold the call to -1 and arrange for `errno` to be set to `EOVERFLOW` on POSIX systems, or it needs to avoid the folding for `n` in excess of `INT_MAX`.  (GCC does the latter, after issuing a warning for the excessive bound.)
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyVVdtu4zYQ_Rr5hVhBV1t-0IPjJG2AbFNsg23eDEocySxo0iUpe9Ov7wwlW-tu0KKBY4uXmTlzZuaoMeK93jjm98A6o5Q5S90zD86zljtgbm_OLsq27Pn562e6IRweKIUWhkXLxOmjldp3-MjO0u8ZZ63RznPt8bY9cM-ct-QTtz2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