xref: /llvm-project/libc/test/src/fenv/exception_flags_test.cpp (revision 578a4cfe19121df5e5e02bf03482233e3bc56a0d)
1 //===-- Unittests for fegetexceptflag and fesetexceptflag -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/fenv/fegetexceptflag.h"
10 #include "src/fenv/fesetexceptflag.h"
11 
12 #include "utils/FPUtil/FEnv.h"
13 #include "utils/UnitTest/Test.h"
14 
15 #include <fenv.h>
16 
17 TEST(LlvmLibcFenvTest, GetExceptFlagAndSetExceptFlag) {
18   // We will disable all exceptions to prevent invocation of the exception
19   // handler.
20   __llvm_libc::fputil::disableExcept(FE_ALL_EXCEPT);
21   __llvm_libc::fputil::clearExcept(FE_ALL_EXCEPT);
22 
23   int excepts[] = {FE_DIVBYZERO, FE_INVALID, FE_INEXACT, FE_OVERFLOW,
24                    FE_UNDERFLOW};
25 
26   for (int e : excepts) {
27     // The overall idea is to raise an except and save the exception flags.
28     // Next, clear the flags and then set the saved exception flags. This
29     // should set the flag corresponding to the previously raised exception.
30     __llvm_libc::fputil::raiseExcept(e);
31     // Make sure that the exception flag is set.
32     ASSERT_NE(__llvm_libc::fputil::testExcept(FE_ALL_EXCEPT) & e, 0);
33 
34     fexcept_t eflags;
35     ASSERT_EQ(__llvm_libc::fegetexceptflag(&eflags, FE_ALL_EXCEPT), 0);
36 
37     __llvm_libc::fputil::clearExcept(e);
38     ASSERT_EQ(__llvm_libc::fputil::testExcept(FE_ALL_EXCEPT) & e, 0);
39 
40     ASSERT_EQ(__llvm_libc::fesetexceptflag(&eflags, FE_ALL_EXCEPT), 0);
41     ASSERT_NE(__llvm_libc::fputil::testExcept(FE_ALL_EXCEPT) & e, 0);
42 
43     // Cleanup. We clear all excepts as raising excepts like FE_OVERFLOW
44     // can also raise FE_INEXACT.
45     __llvm_libc::fputil::clearExcept(FE_ALL_EXCEPT);
46   }
47 
48   // Next, we will raise one exception and save the flags.
49   __llvm_libc::fputil::raiseExcept(FE_INVALID);
50   fexcept_t eflags;
51   __llvm_libc::fegetexceptflag(&eflags, FE_ALL_EXCEPT);
52   // Clear all exceptions and raise two other exceptions.
53   __llvm_libc::fputil::clearExcept(FE_ALL_EXCEPT);
54   __llvm_libc::fputil::raiseExcept(FE_OVERFLOW | FE_INEXACT);
55   // When we set the flags and test, we should only see FE_INVALID.
56   __llvm_libc::fesetexceptflag(&eflags, FE_ALL_EXCEPT);
57   EXPECT_EQ(__llvm_libc::fputil::testExcept(FE_ALL_EXCEPT), FE_INVALID);
58 }
59