Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ConstantFold] Fold log1p and log1pf when the input parameter is a constant value. #112113

Merged
merged 6 commits into from
Oct 15, 2024

Conversation

c8ef
Copy link
Contributor

@c8ef c8ef commented Oct 13, 2024

This patch adds support for constant folding for the log1p and log1pf libc functions.

@c8ef c8ef changed the title Draft [ConstantFold] Fold log1p and log1pf when the input parameter is a constant value. Oct 13, 2024
@c8ef c8ef marked this pull request as ready for review October 13, 2024 04:16
@c8ef c8ef requested review from arsenm and dtcxzyw October 13, 2024 04:17
@llvmbot
Copy link
Member

llvmbot commented Oct 13, 2024

@llvm/pr-subscribers-llvm-transforms

@llvm/pr-subscribers-llvm-analysis

Author: None (c8ef)

Changes

This patch adds support for constant folding for the log1p and log1pf libc functions.


Full diff: https://github.com/llvm/llvm-project/pull/112113.diff

2 Files Affected:

  • (modified) llvm/lib/Analysis/ConstantFolding.cpp (+7-1)
  • (added) llvm/test/Transforms/InstCombine/log1p.ll (+113)
diff --git a/llvm/lib/Analysis/ConstantFolding.cpp b/llvm/lib/Analysis/ConstantFolding.cpp
index 102762dc7937c6..303e1ca320e045 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -1679,7 +1679,8 @@ bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) {
   case 'l':
     return Name == "log" || Name == "logf" || Name == "logl" ||
            Name == "log2" || Name == "log2f" || Name == "log10" ||
-           Name == "log10f" || Name == "logb" || Name == "logbf";
+           Name == "log10f" || Name == "logb" || Name == "logbf" ||
+           Name == "log1p" || Name == "log1pf";
   case 'n':
     return Name == "nearbyint" || Name == "nearbyintf";
   case 'p':
@@ -2394,6 +2395,11 @@ static Constant *ConstantFoldScalarCall1(StringRef Name,
       if (!APF.isZero() && TLI->has(Func))
         return ConstantFoldFP(logb, APF, Ty);
       break;
+    case LibFunc_log1p:
+    case LibFunc_log1pf:
+      if (APF > APFloat(APF.getSemantics(), "-1") && TLI->has(Func))
+        return ConstantFoldFP(log1p, APF, Ty);
+      break;
     case LibFunc_logl:
       return nullptr;
     case LibFunc_nearbyint:
diff --git a/llvm/test/Transforms/InstCombine/log1p.ll b/llvm/test/Transforms/InstCombine/log1p.ll
new file mode 100644
index 00000000000000..9e22c3f43fb7a2
--- /dev/null
+++ b/llvm/test/Transforms/InstCombine/log1p.ll
@@ -0,0 +1,113 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 5
+; RUN: opt < %s -passes=instcombine -S | FileCheck %s
+
+define float @log1pf_const() {
+; CHECK-LABEL: define float @log1pf_const() {
+; CHECK-NEXT:    [[R:%.*]] = call float @log1pf(float 7.000000e+00)
+; CHECK-NEXT:    ret float 0x4000A2B240000000
+;
+  %r = call float @log1pf(float 7.000000e+00)
+  ret float %r
+}
+
+define double @log1p_const() {
+; CHECK-LABEL: define double @log1p_const() {
+; CHECK-NEXT:    [[R:%.*]] = call double @log1p(double 7.000000e+00)
+; CHECK-NEXT:    ret double 0x4000A2B23F3BAB73
+;
+  %r = call double @log1p(double 7.000000e+00)
+  ret double %r
+}
+
+define float @log1pf_minus_one() {
+; CHECK-LABEL: define float @log1pf_minus_one() {
+; CHECK-NEXT:    [[R:%.*]] = call float @log1pf(float -1.000000e+00)
+; CHECK-NEXT:    ret float [[R]]
+;
+  %r = call float @log1pf(float -1.000000e+00)
+  ret float %r
+}
+
+define double @log1p_minus_one() {
+; CHECK-LABEL: define double @log1p_minus_one() {
+; CHECK-NEXT:    [[R:%.*]] = call double @log1p(double -1.000000e+00)
+; CHECK-NEXT:    ret double [[R]]
+;
+  %r = call double @log1p(double -1.000000e+00)
+  ret double %r
+}
+
+define float @log1pf_zero() {
+; CHECK-LABEL: define float @log1pf_zero() {
+; CHECK-NEXT:    [[R:%.*]] = call float @log1pf(float 0.000000e+00)
+; CHECK-NEXT:    ret float 0.000000e+00
+;
+  %r = call float @log1pf(float 0.000000e+00)
+  ret float %r
+}
+
+define double @log1p_zero() {
+; CHECK-LABEL: define double @log1p_zero() {
+; CHECK-NEXT:    [[R:%.*]] = call double @log1p(double 0.000000e+00)
+; CHECK-NEXT:    ret double 0.000000e+00
+;
+  %r = call double @log1p(double 0.000000e+00)
+  ret double %r
+}
+
+define float @log1pf_inf() {
+; CHECK-LABEL: define float @log1pf_inf() {
+; CHECK-NEXT:    [[R:%.*]] = call float @log1pf(float 0x7FF0000000000000)
+; CHECK-NEXT:    ret float [[R]]
+;
+  %r = call float @log1pf(float 0x7FF0000000000000)
+  ret float %r
+}
+
+define double @log1p_inf() {
+; CHECK-LABEL: define double @log1p_inf() {
+; CHECK-NEXT:    [[R:%.*]] = call double @log1p(double 0x7FF0000000000000)
+; CHECK-NEXT:    ret double [[R]]
+;
+  %r = call double @log1p(double 0x7FF0000000000000)
+  ret double %r
+}
+
+define float @log1pf_nan() {
+; CHECK-LABEL: define float @log1pf_nan() {
+; CHECK-NEXT:    [[R:%.*]] = call float @log1pf(float 0x7FF8000000000000)
+; CHECK-NEXT:    ret float [[R]]
+;
+  %r = call float @log1pf(float 0x7FF8000000000000)
+  ret float %r
+}
+
+define double @log1p_nan() {
+; CHECK-LABEL: define double @log1p_nan() {
+; CHECK-NEXT:    [[R:%.*]] = call double @log1p(double 0x7FF8000000000000)
+; CHECK-NEXT:    ret double [[R]]
+;
+  %r = call double @log1p(double 0x7FF8000000000000)
+  ret double %r
+}
+
+define float @log1pf_poison() {
+; CHECK-LABEL: define float @log1pf_poison() {
+; CHECK-NEXT:    [[R:%.*]] = call float @log1pf(float poison)
+; CHECK-NEXT:    ret float [[R]]
+;
+  %r = call float @log1pf(float poison)
+  ret float %r
+}
+
+define double @log1p_poison() {
+; CHECK-LABEL: define double @log1p_poison() {
+; CHECK-NEXT:    [[R:%.*]] = call double @log1p(double poison)
+; CHECK-NEXT:    ret double [[R]]
+;
+  %r = call double @log1p(double poison)
+  ret double %r
+}
+
+declare float @log1pf(float)
+declare double @log1p(double)

@@ -2394,6 +2395,11 @@ static Constant *ConstantFoldScalarCall1(StringRef Name,
if (!APF.isZero() && TLI->has(Func))
return ConstantFoldFP(logb, APF, Ty);
break;
case LibFunc_log1p:
case LibFunc_log1pf:
if (APF > APFloat(APF.getSemantics(), "-1") && TLI->has(Func))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid the string? Also still fold if call is memory none

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using -1 directly seems to pick a different constructor and not achieve the intended behavior. Using -1.0 will pick a deleted constructor, so I opted to use "-1" here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is an APFloat::getOne constructor

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried this as well, but it still doesn't work. It seems really strange.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean doesn't work?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So APFloat bug, cool

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @davemgreen Can you have a look and add some unittests?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will fix this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Please rebase this patch on a54d88f.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

%r = call double @log1p(double poison)
ret double %r
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test memory none special cases

Copy link
Contributor Author

@c8ef c8ef Oct 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have indeed considered handling memory(none) cases. My current plan is not to handle libc functions on a case-by-case basis, but to directly use the value from the libc function regardless of its parameter. Essentially, what I want is to pass the CallBase into the constantFold function, which involves two scenarios. In Case 1, if there are no floating-point exceptions, everything is fine, and we return the folded value. In Case 2, if there is a floating-point exception, we return either nullptr or the exact value returned from the function (such as NaN, HUGE_VAL, etc.) depending on whether this call accesses memory. By doing this, we can eliminate the range check in the Constant Folding phase and avoid error handling based on each function. I look forward to hearing your thoughts on this initial plan.

Constant *ConstantFoldFP(double (*NativeFP)(double), const APFloat &V, Type *Ty,
                         CallBase *CB) {
  llvm_fenv_clearexcept();
  double Result = NativeFP(V.convertToDouble());
  if (llvm_fenv_testexcept()) {
    llvm_fenv_clearexcept();

    if (CB->doesNotAccessMemory())
      return GetConstantFoldFPValue(Result, Ty);
    else
      return nullptr;
  }

  return GetConstantFoldFPValue(Result, Ty);
}

Handling memory(none) cases will impact all current folding operations. I believe it may break some tests and require additional testing. Therefore, my preference is to constant fold most common math functions as much as possible, and then address edge cases afterwards. Would this approach be acceptable?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the consideration of doesNotAccessMemory belongs down in ConstantFoldFP. It should produce the constant folded value regardless of the side effects. The legality of ignoring the side effects is context dependent

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Plus you can and should still add the tests for these cases here, even if they do not fold yet

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Plus you can and should still add the tests for these cases here, even if they do not fold yet

Done.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the consideration of doesNotAccessMemory belongs down in ConstantFoldFP. It should produce the constant folded value regardless of the side effects. The legality of ignoring the side effects is context dependent

But IIUC the current implementation of ConstantFoldFP already considers side effects? If errno is set or a floating-point exception occurs, it returns nullptr instead of the expected return value.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would consider that a defect of implementation. The separation of concerns should yield the result. If we wanted, we could produce a side piece of information for raised errors. Whether or not you care if an error occurred depend on the callsite (i.e we can ignore any exceptions in default FP environment, and memory(none) callsites can ignore errno writes)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe our ideas align. Even if the implementation of ConstantFolfFP directly returns the result from the underlying libc, we still need a wrapper to validate the libc function parameter. Utilizing fp exceptions and errno to determine the legitimacy of the parameter is convenient as it eliminates the need to write range checks for each individual function.

@c8ef c8ef requested a review from arsenm October 13, 2024 10:18
dtcxzyw added a commit that referenced this pull request Oct 15, 2024
`APFloat::APFloat(const fltSemantics &Semantics, integerPart I)`
interprets 'I' as a unsigned integer.
Fix the bug found in
#112113 (comment).
@c8ef c8ef merged commit 47a6da2 into llvm:main Oct 15, 2024
8 checks passed
@c8ef c8ef deleted the log1p branch October 15, 2024 16:19
DanielCChen pushed a commit to DanielCChen/llvm-project that referenced this pull request Oct 16, 2024
`APFloat::APFloat(const fltSemantics &Semantics, integerPart I)`
interprets 'I' as a unsigned integer.
Fix the bug found in
llvm#112113 (comment).
DanielCChen pushed a commit to DanielCChen/llvm-project that referenced this pull request Oct 16, 2024
…a constant value. (llvm#112113)

This patch adds support for constant folding for the `log1p` and
`log1pf` libc functions.
@jakeegan
Copy link
Member

This test fails on the AIX bot, could you take a look?
https://lab.llvm.org/buildbot/#/builders/64/builds/1232/steps/6/logs/FAIL__LLVM__log1p_ll

@c8ef
Copy link
Contributor Author

c8ef commented Oct 18, 2024

The current constant folding of the log1p function relies on the host's libc to compute the folded result. I'm not very familiar with the Power platform. Does its implementation differ from x86 or AArch64, particularly in handling positive or negative zero?

@c8ef
Copy link
Contributor Author

c8ef commented Oct 18, 2024

Based on this Godbolt example (https://godbolt.org/z/a9f6xjvK1), it appears that the log1p constant folding handles negative zero correctly. Since I don't have access to a PowerPC machine, could you assist me in verifying this on current trunk?
@jakeegan

@jakeegan
Copy link
Member

@c8ef The result is:

define noundef double @f() local_unnamed_addr #0 {
entry:
  ret double 0.000000e+00
}

It seems this will require more investigation on an AIX machine, so I'll XFAIL the test on AIX and investigate further.

@hubert-reinterpretcast
Copy link
Collaborator

The negative zero behaviour is optional. Clang on AIX defines neither __STDC_IEC_559__ nor __STDC_IEC_60559_BFP__.

@jakeegan
Copy link
Member

@c8ef Would you be able to adapt the test to reflect negative zero behaviour being optional?

@c8ef
Copy link
Contributor Author

c8ef commented Oct 23, 2024

Marking it as XFAIL: target={{.*}}-aix{{.*}} will be sufficient?

@hubert-reinterpretcast
Copy link
Collaborator

Marking it as XFAIL: target={{.*}}-aix{{.*}} will be sufficient?

The XFAIL is actually wrong. The real issue is that compiling for a non-AIX target on an AIX machine will not generate the negative zero result.

A possible solution is to add the special cases to the constant-folding code in LLVM.

@c8ef
Copy link
Contributor Author

c8ef commented Oct 24, 2024

Marking it as XFAIL: target={{.*}}-aix{{.*}} will be sufficient?

The XFAIL is actually wrong. The real issue is that compiling for a non-AIX target on an AIX machine will not generate the negative zero result.

A possible solution is to add the special cases to the constant-folding code in LLVM.

It appears that when using the default libc for constant folding, the result's dependency on the platform is unavoidable. In contrast, GCC uses mpfr for constant folding, which may help in disregarding platform information during computation and performing the transformation later.

BTW, could you please review #113020 if you are available? @hubert-reinterpretcast

@arsenm
Copy link
Contributor

arsenm commented Oct 24, 2024

Can you write a regex check allowing flexibility in the low bits?

@arsenm
Copy link
Contributor

arsenm commented Oct 24, 2024

Also could special case the zero

@hubert-reinterpretcast
Copy link
Collaborator

Also could special case the zero

#114635 created to implement that direction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants