blob: 941f18877e2dcbee3d777689926cca0ae869c18e [file] [log] [blame]
Tim Shen7d0bffb2017-02-10 20:30:43 +00001//===-- xray_tsc.h ----------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of XRay, a dynamic runtime instrumentation system.
11//
12//===----------------------------------------------------------------------===//
13#ifndef XRAY_EMULATE_TSC_H
14#define XRAY_EMULATE_TSC_H
15
16#if defined(__x86_64__)
17#include "xray_x86_64.inc"
18#elif defined(__arm__) || defined(__aarch64__)
19// Emulated TSC.
20// There is no instruction like RDTSCP in user mode on ARM. ARM's CP15 does
21// not have a constant frequency like TSC on x86(_64), it may go faster
22// or slower depending on CPU turbo or power saving mode. Furthermore,
23// to read from CP15 on ARM a kernel modification or a driver is needed.
24// We can not require this from users of compiler-rt.
25// So on ARM we use clock_gettime() which gives the result in nanoseconds.
26// To get the measurements per second, we scale this by the number of
27// nanoseconds per second, pretending that the TSC frequency is 1GHz and
28// one TSC tick is 1 nanosecond.
29#include "sanitizer_common/sanitizer_common.h"
30#include "sanitizer_common/sanitizer_internal_defs.h"
31#include "xray_defs.h"
32#include <cerrno>
33#include <cstdint>
34#include <time.h>
35
36namespace __xray {
37
38static constexpr uint64_t NanosecondsPerSecond = 1000ULL * 1000 * 1000;
39
40inline bool probeRequiredCPUFeatures() XRAY_NEVER_INSTRUMENT { return true; }
41
42ALWAYS_INLINE uint64_t readTSC(uint8_t &CPU) XRAY_NEVER_INSTRUMENT {
43 timespec TS;
44 int result = clock_gettime(CLOCK_REALTIME, &TS);
45 if (result != 0) {
46 Report("clock_gettime(2) returned %d, errno=%d.", result, int(errno));
47 TS.tv_sec = 0;
48 TS.tv_nsec = 0;
49 }
50 CPU = 0;
51 return TS.tv_sec * NanosecondsPerSecond + TS.tv_nsec;
52}
53
54inline uint64_t getTSCFrequency() XRAY_NEVER_INSTRUMENT {
55 return NanosecondsPerSecond;
56}
57
58} // namespace __xray
59
60#else
61"Unsupported CPU Architecture"
62#endif // CPU architecture
63
64#endif // XRAY_EMULATE_TSC_H