Debian Codegraph @

flang/runtime/time-intrinsic.cpp

raw
1 //===-- runtime/time-intrinsic.cpp ----------------------------------------===//
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 // Implements time-related intrinsic subroutines.
10
11 #include "flang/Runtime/time-intrinsic.h"
12 #include "terminator.h"
13 #include "tools.h"
14 #include "flang/Runtime/cpp-type.h"
15 #include "flang/Runtime/descriptor.h"
16 #include <algorithm>
17 #include <cstdint>
18 #include <cstdio>
19 #include <cstdlib>
20 #include <cstring>
21 #include <ctime>
22 #ifdef _WIN32
23 #include "flang/Common/windows-include.h"
24 #else
25 #include <sys/time.h> // gettimeofday
26 #include <sys/times.h>
27 #include <unistd.h>
28 #endif
29
30 // CPU_TIME (Fortran 2018 16.9.57)
31 // SYSTEM_CLOCK (Fortran 2018 16.9.168)
32 //
33 // We can use std::clock() from the <ctime> header as a fallback implementation
34 // that should be available everywhere. This may not provide the best resolution
35 // and is particularly troublesome on (some?) POSIX systems where CLOCKS_PER_SEC
36 // is defined as 10^6 regardless of the actual precision of std::clock().
37 // Therefore, we will usually prefer platform-specific alternatives when they
38 // are available.
39 //
40 // We can use SFINAE to choose a platform-specific alternative. To do so, we
41 // introduce a helper function template, whose overload set will contain only
42 // implementations relying on interfaces which are actually available. Each
43 // overload will have a dummy parameter whose type indicates whether or not it
44 // should be preferred. Any other parameters required for SFINAE should have
45 // default values provided.
46 namespace {
47 // Types for the dummy parameter indicating the priority of a given overload.
48 // We will invoke our helper with an integer literal argument, so the overload
49 // with the highest priority should have the type int.
50 using fallback_implementation = double;
51 using preferred_implementation = int;
52
53 // This is the fallback implementation, which should work everywhere.
54 template <typename Unused = void> double GetCpuTime(fallback_implementation) {
55 std::clock_t timestamp{std::clock()};
56 if (timestamp != static_cast<std::clock_t>(-1)) {
57 return static_cast<double>(timestamp) / CLOCKS_PER_SEC;
58 }
59 // Return some negative value to represent failure.
60 return -1.0;
61 }
62
63 #if defined __MINGW32__
64 // clock_gettime is implemented in the pthread library for MinGW.
65 // Using it here would mean that all programs that link libFortranRuntime are
66 // required to also link to pthread. Instead, don't use the function.
67 #undef CLOCKID_CPU_TIME
68 #undef CLOCKID_ELAPSED_TIME
69 #else
70 // Determine what clock to use for CPU time.
71 #if defined CLOCK_PROCESS_CPUTIME_ID
72 #define CLOCKID_CPU_TIME CLOCK_PROCESS_CPUTIME_ID
73 #elif defined CLOCK_THREAD_CPUTIME_ID
74 #define CLOCKID_CPU_TIME CLOCK_THREAD_CPUTIME_ID
75 #else
76 #undef CLOCKID_CPU_TIME
77 #endif
78
79 // Determine what clock to use for elapsed time.
80 #if defined CLOCK_MONOTONIC
81 #define CLOCKID_ELAPSED_TIME CLOCK_MONOTONIC
82 #elif defined CLOCK_REALTIME
83 #define CLOCKID_ELAPSED_TIME CLOCK_REALTIME
84 #else
85 #undef CLOCKID_ELAPSED_TIME
86 #endif
87 #endif
88
89 #ifdef CLOCKID_CPU_TIME
90 // POSIX implementation using clock_gettime. This is only enabled where
91 // clock_gettime is available.
92 template <typename T = int, typename U = struct timespec>
93 double GetCpuTime(preferred_implementation,
94 // We need some dummy parameters to pass to decltype(clock_gettime).
95 T ClockId = 0, U *Timespec = nullptr,
96 decltype(clock_gettime(ClockId, Timespec)) *Enabled = nullptr) {
97 struct timespec tspec;
98 if (clock_gettime(CLOCKID_CPU_TIME, &tspec) == 0) {
99 return tspec.tv_nsec * 1.0e-9 + tspec.tv_sec;
100 }
101 // Return some negative value to represent failure.
102 return -1.0;
103 }
104 #endif // CLOCKID_CPU_TIME
105
106 using count_t = std::int64_t;
107 using unsigned_count_t = std::uint64_t;
108
109 // POSIX implementation using clock_gettime where available. The clock_gettime
110 // result is in nanoseconds, which is converted as necessary to
111 // - deciseconds for kind 1
112 // - milliseconds for kinds 2, 4
113 // - nanoseconds for kinds 8, 16
114 constexpr unsigned_count_t DS_PER_SEC{10u};
115 constexpr unsigned_count_t MS_PER_SEC{1'000u};
116 constexpr unsigned_count_t NS_PER_SEC{1'000'000'000u};
117
118 // Computes HUGE(INT(0,kind)) as an unsigned integer value.
119 static constexpr inline unsigned_count_t GetHUGE(int kind) {
120 if (kind > 8) {
121 kind = 8;
122 }
123 return (unsigned_count_t{1} << ((8 * kind) - 1)) - 1;
124 }
125
126 // Function converts a std::timespec_t into the desired count to
127 // be returned by the timing functions in accordance with the requested
128 // kind at the call site.
129 count_t ConvertTimeSpecToCount(int kind, const struct timespec &tspec) {
130 const unsigned_count_t huge{GetHUGE(kind)};
131 unsigned_count_t sec{static_cast<unsigned_count_t>(tspec.tv_sec)};
132 unsigned_count_t nsec{static_cast<unsigned_count_t>(tspec.tv_nsec)};
133 if (kind >= 8) {
134 return (sec * NS_PER_SEC + nsec) % (huge + 1);
135 } else if (kind >= 2) {
136 return (sec * MS_PER_SEC + (nsec / (NS_PER_SEC / MS_PER_SEC))) % (huge + 1);
137 } else { // kind == 1
138 return (sec * DS_PER_SEC + (nsec / (NS_PER_SEC / DS_PER_SEC))) % (huge + 1);
139 }
140 }
141
142 #ifndef _AIX
143 // This is the fallback implementation, which should work everywhere.
144 template <typename Unused = void>
145 count_t GetSystemClockCount(int kind, fallback_implementation) {
146 struct timespec tspec;
147
148 if (timespec_get(&tspec, TIME_UTC) < 0) {
149 // Return -HUGE(COUNT) to represent failure.
150 return -static_cast<count_t>(GetHUGE(kind));
151 }
152
153 // Compute the timestamp as seconds plus nanoseconds in accordance
154 // with the requested kind at the call site.
155 return ConvertTimeSpecToCount(kind, tspec);
156 }
157 #endif
158
159 template <typename Unused = void>
160 count_t GetSystemClockCountRate(int kind, fallback_implementation) {
161 return kind >= 8 ? NS_PER_SEC : kind >= 2 ? MS_PER_SEC : DS_PER_SEC;
162 }
163
164 template <typename Unused = void>
165 count_t GetSystemClockCountMax(int kind, fallback_implementation) {
166 unsigned_count_t maxCount{GetHUGE(kind)};
167 return maxCount;
168 }
169
170 #ifdef CLOCKID_ELAPSED_TIME
171 template <typename T = int, typename U = struct timespec>
172 count_t GetSystemClockCount(int kind, preferred_implementation,
173 // We need some dummy parameters to pass to decltype(clock_gettime).
174 T ClockId = 0, U *Timespec = nullptr,
175 decltype(clock_gettime(ClockId, Timespec)) *Enabled = nullptr) {
176 struct timespec tspec;
177 const unsigned_count_t huge{GetHUGE(kind)};
178 if (clock_gettime(CLOCKID_ELAPSED_TIME, &tspec) != 0) {
179 return -huge; // failure
180 }
181
182 // Compute the timestamp as seconds plus nanoseconds in accordance
183 // with the requested kind at the call site.
184 return ConvertTimeSpecToCount(kind, tspec);
185 }
186 #endif // CLOCKID_ELAPSED_TIME
187
188 template <typename T = int, typename U = struct timespec>
189 count_t GetSystemClockCountRate(int kind, preferred_implementation,
190 // We need some dummy parameters to pass to decltype(clock_gettime).
191 T ClockId = 0, U *Timespec = nullptr,
192 decltype(clock_gettime(ClockId, Timespec)) *Enabled = nullptr) {
193 return kind >= 8 ? NS_PER_SEC : kind >= 2 ? MS_PER_SEC : DS_PER_SEC;
194 }
195
196 template <typename T = int, typename U = struct timespec>
197 count_t GetSystemClockCountMax(int kind, preferred_implementation,
198 // We need some dummy parameters to pass to decltype(clock_gettime).
199 T ClockId = 0, U *Timespec = nullptr,
200 decltype(clock_gettime(ClockId, Timespec)) *Enabled = nullptr) {
201 return GetHUGE(kind);
202 }
203
204 // DATE_AND_TIME (Fortran 2018 16.9.59)
205
206 // Helper to set an integer value to -HUGE
207 template <int KIND> struct StoreNegativeHugeAt {
208 void operator()(
209 const Fortran::runtime::Descriptor &result, std::size_t at) const {
210 *result.ZeroBasedIndexedElement<Fortran::runtime::CppTypeFor<
211 Fortran::common::TypeCategory::Integer, KIND>>(at) =
212 -std::numeric_limits<Fortran::runtime::CppTypeFor<
213 Fortran::common::TypeCategory::Integer, KIND>>::max();
214 }
215 };
216
217 // Default implementation when date and time information is not available (set
218 // strings to blanks and values to -HUGE as defined by the standard).
219 static void DateAndTimeUnavailable(Fortran::runtime::Terminator &terminator,
220 char *date, std::size_t dateChars, char *time, std::size_t timeChars,
221 char *zone, std::size_t zoneChars,
222 const Fortran::runtime::Descriptor *values) {
223 if (date) {
224 std::memset(date, static_cast<int>(' '), dateChars);
225 }
226 if (time) {
227 std::memset(time, static_cast<int>(' '), timeChars);
228 }
229 if (zone) {
230 std::memset(zone, static_cast<int>(' '), zoneChars);
231 }
232 if (values) {
233 auto typeCode{values->type().GetCategoryAndKind()};
234 RUNTIME_CHECK(terminator,
235 values->rank() == 1 && values->GetDimension(0).Extent() >= 8 &&
236 typeCode &&
237 typeCode->first == Fortran::common::TypeCategory::Integer);
238 // DATE_AND_TIME values argument must have decimal range > 4. Do not accept
239 // KIND 1 here.
240 int kind{typeCode->second};
241 RUNTIME_CHECK(terminator, kind != 1);
242 for (std::size_t i = 0; i < 8; ++i) {
243 Fortran::runtime::ApplyIntegerKind<StoreNegativeHugeAt, void>(
244 kind, terminator, *values, i);
245 }
246 }
247 }
248
249 #ifndef _WIN32
250
251 // SFINAE helper to return the struct tm.tm_gmtoff which is not a POSIX standard
252 // field.
253 template <int KIND, typename TM = struct tm>
254 Fortran::runtime::CppTypeFor<Fortran::common::TypeCategory::Integer, KIND>
255 GetGmtOffset(const TM &tm, preferred_implementation,
256 decltype(tm.tm_gmtoff) *Enabled = nullptr) {
257 // Returns the GMT offset in minutes.
258 return tm.tm_gmtoff / 60;
259 }
260 template <int KIND, typename TM = struct tm>
261 Fortran::runtime::CppTypeFor<Fortran::common::TypeCategory::Integer, KIND>
262 GetGmtOffset(const TM &tm, fallback_implementation) {
263 // tm.tm_gmtoff is not available, there may be platform dependent alternatives
264 // (such as using timezone from <time.h> when available), but so far just
265 // return -HUGE to report that this information is not available.
266 return -std::numeric_limits<Fortran::runtime::CppTypeFor<
267 Fortran::common::TypeCategory::Integer, KIND>>::max();
268 }
269 template <typename TM = struct tm> struct GmtOffsetHelper {
270 template <int KIND> struct StoreGmtOffset {
271 void operator()(const Fortran::runtime::Descriptor &result, std::size_t at,
272 TM &tm) const {
273 *result.ZeroBasedIndexedElement<Fortran::runtime::CppTypeFor<
274 Fortran::common::TypeCategory::Integer, KIND>>(at) =
275 GetGmtOffset<KIND>(tm, 0);
276 }
277 };
278 };
279
280 // Dispatch to posix implementation where gettimeofday and localtime_r are
281 // available.
282 static void GetDateAndTime(Fortran::runtime::Terminator &terminator, char *date,
283 std::size_t dateChars, char *time, std::size_t timeChars, char *zone,
284 std::size_t zoneChars, const Fortran::runtime::Descriptor *values) {
285
286 timeval t;
287 if (gettimeofday(&t, nullptr) != 0) {
288 DateAndTimeUnavailable(
289 terminator, date, dateChars, time, timeChars, zone, zoneChars, values);
290 return;
291 }
292 time_t timer{t.tv_sec};
293 tm localTime;
294 localtime_r(&timer, &localTime);
295 std::intmax_t ms{t.tv_usec / 1000};
296
297 static constexpr std::size_t buffSize{16};
298 char buffer[buffSize];
299 auto copyBufferAndPad{
300 [&](char *dest, std::size_t destChars, std::size_t len) {
301 auto copyLen{std::min(len, destChars)};
302 std::memcpy(dest, buffer, copyLen);
303 for (auto i{copyLen}; i < destChars; ++i) {
304 dest[i] = ' ';
305 }
306 }};
307 if (date) {
308 auto len = std::strftime(buffer, buffSize, "%Y%m%d", &localTime);
309 copyBufferAndPad(date, dateChars, len);
310 }
311 if (time) {
312 auto len{std::snprintf(buffer, buffSize, "%02d%02d%02d.%03jd",
313 localTime.tm_hour, localTime.tm_min, localTime.tm_sec, ms)};
314 copyBufferAndPad(time, timeChars, len);
315 }
316 if (zone) {
317 // Note: this may leave the buffer empty on many platforms. Classic flang
318 // has a much more complex way of doing this (see __io_timezone in classic
319 // flang).
320 auto len{std::strftime(buffer, buffSize, "%z", &localTime)};
321 copyBufferAndPad(zone, zoneChars, len);
322 }
323 if (values) {
324 auto typeCode{values->type().GetCategoryAndKind()};
325 RUNTIME_CHECK(terminator,
326 values->rank() == 1 && values->GetDimension(0).Extent() >= 8 &&
327 typeCode &&
328 typeCode->first == Fortran::common::TypeCategory::Integer);
329 // DATE_AND_TIME values argument must have decimal range > 4. Do not accept
330 // KIND 1 here.
331 int kind{typeCode->second};
332 RUNTIME_CHECK(terminator, kind != 1);
333 auto storeIntegerAt = [&](std::size_t atIndex, std::int64_t value) {
334 Fortran::runtime::ApplyIntegerKind<Fortran::runtime::StoreIntegerAt,
335 void>(kind, terminator, *values, atIndex, value);
336 };
337 storeIntegerAt(0, localTime.tm_year + 1900);
338 storeIntegerAt(1, localTime.tm_mon + 1);
339 storeIntegerAt(2, localTime.tm_mday);
340 Fortran::runtime::ApplyIntegerKind<
341 GmtOffsetHelper<struct tm>::StoreGmtOffset, void>(
342 kind, terminator, *values, 3, localTime);
343 storeIntegerAt(4, localTime.tm_hour);
344 storeIntegerAt(5, localTime.tm_min);
345 storeIntegerAt(6, localTime.tm_sec);
346 storeIntegerAt(7, ms);
347 }
348 }
349
350 #else
351 // Fallback implementation where gettimeofday or localtime_r are not both
352 // available (e.g. windows).
353 static void GetDateAndTime(Fortran::runtime::Terminator &terminator, char *date,
354 std::size_t dateChars, char *time, std::size_t timeChars, char *zone,
355 std::size_t zoneChars, const Fortran::runtime::Descriptor *values) {
356 // TODO: An actual implementation for non Posix system should be added.
357 // So far, implement as if the date and time is not available on those
358 // platforms.
359 DateAndTimeUnavailable(
360 terminator, date, dateChars, time, timeChars, zone, zoneChars, values);
361 }
362 #endif
363 } // namespace
364
365 namespace Fortran::runtime {
366 extern "C" {
367
368 double RTNAME(CpuTime)() { return GetCpuTime(0); }
369
370 std::int64_t RTNAME(SystemClockCount)(int kind) {
371 return GetSystemClockCount(kind, 0);
372 }
373
374 std::int64_t RTNAME(SystemClockCountRate)(int kind) {
375 return GetSystemClockCountRate(kind, 0);
376 }
377
378 std::int64_t RTNAME(SystemClockCountMax)(int kind) {
379 return GetSystemClockCountMax(kind, 0);
380 }
381
382 void RTNAME(DateAndTime)(char *date, std::size_t dateChars, char *time,
383 std::size_t timeChars, char *zone, std::size_t zoneChars,
384 const char *source, int line, const Descriptor *values) {
385 Fortran::runtime::Terminator terminator{source, line};
386 return GetDateAndTime(
387 terminator, date, dateChars, time, timeChars, zone, zoneChars, values);
388 }
389
390 void RTNAME(Etime)(const Descriptor *values, const Descriptor *time,
391 const char *sourceFile, int line) {
392 Fortran::runtime::Terminator terminator{sourceFile, line};
393
394 double usrTime = -1.0, sysTime = -1.0, realTime = -1.0;
395
396 #ifdef _WIN32
397 FILETIME creationTime;
398 FILETIME exitTime;
399 FILETIME kernelTime;
400 FILETIME userTime;
401
402 if (GetProcessTimes(GetCurrentProcess(), &creationTime, &exitTime,
403 &kernelTime, &userTime) == 0) {
404 ULARGE_INTEGER userSystemTime;
405 ULARGE_INTEGER kernelSystemTime;
406
407 memcpy(&userSystemTime, &userTime, sizeof(FILETIME));
408 memcpy(&kernelSystemTime, &kernelTime, sizeof(FILETIME));
409
410 usrTime = ((double)(userSystemTime.QuadPart)) / 10000000.0;
411 sysTime = ((double)(kernelSystemTime.QuadPart)) / 10000000.0;
412 realTime = usrTime + sysTime;
413 }
414 #else
415 struct tms tms;
416 if (times(&tms) != (clock_t)-1) {
417 usrTime = ((double)(tms.tms_utime)) / sysconf(_SC_CLK_TCK);
418 sysTime = ((double)(tms.tms_stime)) / sysconf(_SC_CLK_TCK);
419 realTime = usrTime + sysTime;
420 }
421 #endif
422
423 if (values) {
424 auto typeCode{values->type().GetCategoryAndKind()};
425 // ETIME values argument must have decimal range == 2.
426 RUNTIME_CHECK(terminator,
427 values->rank() == 1 && values->GetDimension(0).Extent() == 2 &&
428 typeCode && typeCode->first == Fortran::common::TypeCategory::Real);
429 // Only accept KIND=4 here.
430 int kind{typeCode->second};
431 RUNTIME_CHECK(terminator, kind == 4);
432
433 ApplyFloatingPointKind<StoreFloatingPointAt, void>(
434 kind, terminator, *values, /* atIndex = */ 0, usrTime);
435 ApplyFloatingPointKind<StoreFloatingPointAt, void>(
436 kind, terminator, *values, /* atIndex = */ 1, sysTime);
437 }
438
439 if (time) {
440 auto typeCode{time->type().GetCategoryAndKind()};
441 // ETIME time argument must have decimal range == 0.
442 RUNTIME_CHECK(terminator,
443 time->rank() == 0 && typeCode &&
444 typeCode->first == Fortran::common::TypeCategory::Real);
445 // Only accept KIND=4 here.
446 int kind{typeCode->second};
447 RUNTIME_CHECK(terminator, kind == 4);
448
449 ApplyFloatingPointKind<StoreFloatingPointAt, void>(
450 kind, terminator, *time, /* atIndex = */ 0, realTime);
451 }
452 }
453
454 } // extern "C"
455 } // namespace Fortran::runtime