[InstCombine] Infer nusw + nneg -> nuw for getelementptr (#111144)
[llvm-project.git] / libc / src / time / linux / clock.cpp
blobf43e1bcad6a3a196f23b3198b37bebabfed16eb2
1 //===-- Linux implementation of the clock function ------------------------===//
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 //===----------------------------------------------------------------------===//
9 #include "src/time/clock.h"
10 #include "hdr/time_macros.h"
11 #include "src/__support/CPP/limits.h"
12 #include "src/__support/common.h"
13 #include "src/__support/macros/config.h"
14 #include "src/__support/time/linux/clock_gettime.h"
15 #include "src/__support/time/units.h"
16 #include "src/errno/libc_errno.h"
18 namespace LIBC_NAMESPACE_DECL {
20 LLVM_LIBC_FUNCTION(clock_t, clock, ()) {
21 using namespace time_units;
22 struct timespec ts;
23 auto result = internal::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
24 if (!result.has_value()) {
25 libc_errno = result.error();
26 return -1;
29 // The above syscall gets the CPU time in seconds plus nanoseconds.
30 // The standard requires that we return clock_t(-1) if we cannot represent
31 // clocks as a clock_t value.
32 constexpr clock_t CLOCK_SECS_MAX =
33 cpp::numeric_limits<clock_t>::max() / CLOCKS_PER_SEC;
34 if (ts.tv_sec > CLOCK_SECS_MAX)
35 return clock_t(-1);
36 if (ts.tv_nsec / 1_s_ns > CLOCK_SECS_MAX - ts.tv_sec)
37 return clock_t(-1);
39 // For the integer computation converting tv_nsec to clocks to work
40 // correctly, we want CLOCKS_PER_SEC to be less than 1000000000.
41 static_assert(1_s_ns > CLOCKS_PER_SEC,
42 "Expected CLOCKS_PER_SEC to be less than 1'000'000'000.");
43 return clock_t(ts.tv_sec * CLOCKS_PER_SEC +
44 ts.tv_nsec / (1_s_ns / CLOCKS_PER_SEC));
47 } // namespace LIBC_NAMESPACE_DECL