counters.h 51.6 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4 5 6 7

#ifndef V8_COUNTERS_H_
#define V8_COUNTERS_H_

8 9
#include "include/v8.h"
#include "src/allocation.h"
10
#include "src/base/atomic-utils.h"
11
#include "src/base/optional.h"
12
#include "src/base/platform/elapsed-timer.h"
13
#include "src/base/platform/time.h"
14
#include "src/counters-definitions.h"
15
#include "src/globals.h"
16
#include "src/heap-symbols.h"
17
#include "src/isolate.h"
18
#include "src/objects.h"
19
#include "src/runtime/runtime.h"
20
#include "src/tracing/trace-event.h"
21
#include "src/tracing/traced-value.h"
22
#include "src/tracing/tracing-category-observer.h"
23

24 25
namespace v8 {
namespace internal {
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// This struct contains a set of flags that can be modified from multiple
// threads at runtime unlike the normal FLAG_-like flags which are not modified
// after V8 instance is initialized.

struct TracingFlags {
  static V8_EXPORT_PRIVATE std::atomic_uint runtime_stats;
  static V8_EXPORT_PRIVATE std::atomic_uint gc_stats;
  static V8_EXPORT_PRIVATE std::atomic_uint ic_stats;

  static bool is_runtime_stats_enabled() {
    return runtime_stats.load(std::memory_order_relaxed) != 0;
  }

  static bool is_gc_stats_enabled() {
    return gc_stats.load(std::memory_order_relaxed) != 0;
  }

  static bool is_ic_stats_enabled() {
    return ic_stats.load(std::memory_order_relaxed) != 0;
  }
};

49 50 51 52
// StatsCounters is an interface for plugging into external
// counters for monitoring.  Counters can be looked up and
// manipulated by name.

53 54
class Counters;

55
class StatsTable {
56
 public:
57 58
  // Register an application-defined function for recording
  // subsequent counter statistics.
59
  void SetCounterFunction(CounterLookupCallback f);
60

61 62
  // Register an application-defined function to create histograms for
  // recording subsequent histogram samples.
63
  void SetCreateHistogramFunction(CreateHistogramCallback f) {
64 65 66 67
    create_histogram_function_ = f;
  }

  // Register an application-defined function to add a sample
68
  // to a histogram created with CreateHistogram function.
69
  void SetAddHistogramSampleFunction(AddHistogramSampleCallback f) {
70 71 72
    add_histogram_sample_function_ = f;
  }

73
  bool HasCounterFunction() const { return lookup_function_ != nullptr; }
74 75

  // Lookup the location of a counter by name.  If the lookup
76
  // is successful, returns a non-nullptr pointer for writing the
77 78 79 80
  // value of the counter.  Each thread calling this function
  // may receive a different location to store it's counter.
  // The return value must not be cached and re-used across
  // threads, although a single thread is free to cache it.
81
  int* FindLocation(const char* name) {
82
    if (!lookup_function_) return nullptr;
83 84 85
    return lookup_function_(name);
  }

86
  // Create a histogram by name. If the create is successful,
87
  // returns a non-nullptr pointer for use with AddHistogramSample
88 89 90
  // function. min and max define the expected minimum and maximum
  // sample values. buckets is the maximum number of buckets
  // that the samples will be grouped into.
91 92 93 94
  void* CreateHistogram(const char* name,
                        int min,
                        int max,
                        size_t buckets) {
95
    if (!create_histogram_function_) return nullptr;
96 97 98 99 100
    return create_histogram_function_(name, min, max, buckets);
  }

  // Add a sample to a histogram created with the CreateHistogram
  // function.
101
  void AddHistogramSample(void* histogram, int sample) {
102 103 104 105
    if (!add_histogram_sample_function_) return;
    return add_histogram_sample_function_(histogram, sample);
  }

106
 private:
107 108
  friend class Counters;

109
  explicit StatsTable(Counters* counters);
110 111 112 113 114 115

  CounterLookupCallback lookup_function_;
  CreateHistogramCallback create_histogram_function_;
  AddHistogramSampleCallback add_histogram_sample_function_;

  DISALLOW_COPY_AND_ASSIGN(StatsTable);
116 117
};

118 119 120
// Base class for stats counters.
class StatsCounterBase {
 protected:
121
  Counters* counters_;
122 123 124
  const char* name_;
  int* ptr_;

125
  StatsCounterBase() = default;
126 127 128
  StatsCounterBase(Counters* counters, const char* name)
      : counters_(counters), name_(name), ptr_(nullptr) {}

129 130 131 132 133 134
  void SetLoc(int* loc, int value) { *loc = value; }
  void IncrementLoc(int* loc) { (*loc)++; }
  void IncrementLoc(int* loc, int value) { (*loc) += value; }
  void DecrementLoc(int* loc) { (*loc)--; }
  void DecrementLoc(int* loc, int value) { (*loc) -= value; }

135
  V8_EXPORT_PRIVATE int* FindLocationInStatsTable() const;
136 137
};

138 139 140 141 142 143 144
// StatsCounters are dynamically created values which can be tracked in
// the StatsTable.  They are designed to be lightweight to create and
// easy to use.
//
// Internally, a counter represents a value in a row of a StatsTable.
// The row has a 32bit value for each process/thread in the table and also
// a name (stored in the table metadata).  Since the storage location can be
145 146
// thread-specific, this class cannot be shared across threads. Note: This
// class is not thread safe.
147
class StatsCounter : public StatsCounterBase {
148
 public:
149 150
  // Sets the counter to a specific value.
  void Set(int value) {
151
    if (int* loc = GetPtr()) SetLoc(loc, value);
152 153 154 155
  }

  // Increments the counter.
  void Increment() {
156
    if (int* loc = GetPtr()) IncrementLoc(loc);
157 158 159
  }

  void Increment(int value) {
160
    if (int* loc = GetPtr()) IncrementLoc(loc, value);
161 162 163 164
  }

  // Decrements the counter.
  void Decrement() {
165
    if (int* loc = GetPtr()) DecrementLoc(loc);
166 167 168
  }

  void Decrement(int value) {
169
    if (int* loc = GetPtr()) DecrementLoc(loc, value);
170 171 172 173
  }

  // Is this counter enabled?
  // Returns false if table is full.
174
  bool Enabled() { return GetPtr() != nullptr; }
175 176 177 178 179 180

  // Get the internal pointer to the counter. This is used
  // by the code generator to emit code that manipulates a
  // given counter without calling the runtime system.
  int* GetInternalPointer() {
    int* loc = GetPtr();
181
    DCHECK_NOT_NULL(loc);
182 183 184
    return loc;
  }

185 186 187
 private:
  friend class Counters;

188
  StatsCounter() = default;
189 190 191
  StatsCounter(Counters* counters, const char* name)
      : StatsCounterBase(counters, name), lookup_done_(false) {}

192 193 194
  // Reset the cached internal pointer.
  void Reset() { lookup_done_ = false; }

195 196
  // Returns the cached address of this counter location.
  int* GetPtr() {
197
    if (lookup_done_) return ptr_;
198
    lookup_done_ = true;
199
    ptr_ = FindLocationInStatsTable();
200 201
    return ptr_;
  }
202

203 204 205
  bool lookup_done_;
};

206
// Thread safe version of StatsCounter.
207
class V8_EXPORT_PRIVATE StatsCounterThreadSafe : public StatsCounterBase {
208 209 210 211 212 213
 public:
  void Set(int Value);
  void Increment();
  void Increment(int value);
  void Decrement();
  void Decrement(int value);
214
  bool Enabled() { return ptr_ != nullptr; }
215
  int* GetInternalPointer() {
216
    DCHECK_NOT_NULL(ptr_);
217 218 219
    return ptr_;
  }

220
 private:
221 222 223 224
  friend class Counters;

  StatsCounterThreadSafe(Counters* counters, const char* name);
  void Reset() { ptr_ = FindLocationInStatsTable(); }
225

226 227 228
  base::Mutex mutex_;

  DISALLOW_IMPLICIT_CONSTRUCTORS(StatsCounterThreadSafe);
229 230
};

231 232
// A Histogram represents a dynamically created histogram in the
// StatsTable.  Note: This class is thread safe.
233 234
class Histogram {
 public:
235 236
  // Add a single sample to this histogram.
  void AddSample(int sample);
237

238
  // Returns true if this histogram is enabled.
239
  bool Enabled() { return histogram_ != nullptr; }
240

241 242
  const char* name() { return name_; }

243 244 245 246
  int min() const { return min_; }
  int max() const { return max_; }
  int num_buckets() const { return num_buckets_; }

247 248 249 250 251 252
  // Asserts that |expected_counters| are the same as the Counters this
  // Histogram reports to.
  void AssertReportsToCounters(Counters* expected_counters) {
    DCHECK_EQ(counters_, expected_counters);
  }

253
 protected:
254
  Histogram() = default;
255 256 257 258 259 260 261
  Histogram(const char* name, int min, int max, int num_buckets,
            Counters* counters)
      : name_(name),
        min_(min),
        max_(max),
        num_buckets_(num_buckets),
        histogram_(nullptr),
262 263 264
        counters_(counters) {
    DCHECK(counters_);
  }
265

266
  Counters* counters() const { return counters_; }
267

268 269 270
  // Reset the cached internal pointer.
  void Reset() { histogram_ = CreateHistogram(); }

271
 private:
272 273
  friend class Counters;

274
  void* CreateHistogram() const;
275

276 277 278 279 280
  const char* name_;
  int min_;
  int max_;
  int num_buckets_;
  void* histogram_;
281
  Counters* counters_;
282
};
283

284 285 286 287
enum class HistogramTimerResolution { MILLISECOND, MICROSECOND };

// A thread safe histogram timer. It also allows distributions of
// nested timed results.
288
class TimedHistogram : public Histogram {
289
 public:
290
  // Start the timer. Log if isolate non-null.
291
  V8_EXPORT_PRIVATE void Start(base::ElapsedTimer* timer, Isolate* isolate);
292

293
  // Stop the timer and record the results. Log if isolate non-null.
294
  V8_EXPORT_PRIVATE void Stop(base::ElapsedTimer* timer, Isolate* isolate);
295

296 297 298 299
  // Records a TimeDelta::Max() result. Useful to record percentage of tasks
  // that never got to run in a given scenario. Log if isolate non-null.
  void RecordAbandon(base::ElapsedTimer* timer, Isolate* isolate);

300 301 302 303
 protected:
  friend class Counters;
  HistogramTimerResolution resolution_;

304
  TimedHistogram() = default;
305 306 307
  TimedHistogram(const char* name, int min, int max,
                 HistogramTimerResolution resolution, int num_buckets,
                 Counters* counters)
308
      : Histogram(name, min, max, num_buckets, counters),
yangguo's avatar
yangguo committed
309
        resolution_(resolution) {}
310 311 312 313 314 315 316 317 318 319 320
  void AddTimeSample();
};

// Helper class for scoping a TimedHistogram.
class TimedHistogramScope {
 public:
  explicit TimedHistogramScope(TimedHistogram* histogram,
                               Isolate* isolate = nullptr)
      : histogram_(histogram), isolate_(isolate) {
    histogram_->Start(&timer_, isolate);
  }
321

322 323 324 325 326 327
  ~TimedHistogramScope() { histogram_->Stop(&timer_, isolate_); }

 private:
  base::ElapsedTimer timer_;
  TimedHistogram* histogram_;
  Isolate* isolate_;
328

329 330 331
  DISALLOW_IMPLICIT_CONSTRUCTORS(TimedHistogramScope);
};

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
enum class OptionalTimedHistogramScopeMode { TAKE_TIME, DONT_TAKE_TIME };

// Helper class for scoping a TimedHistogram.
// It will not take time for mode = DONT_TAKE_TIME.
class OptionalTimedHistogramScope {
 public:
  OptionalTimedHistogramScope(TimedHistogram* histogram, Isolate* isolate,
                              OptionalTimedHistogramScopeMode mode)
      : histogram_(histogram), isolate_(isolate), mode_(mode) {
    if (mode == OptionalTimedHistogramScopeMode::TAKE_TIME) {
      histogram_->Start(&timer_, isolate);
    }
  }

  ~OptionalTimedHistogramScope() {
    if (mode_ == OptionalTimedHistogramScopeMode::TAKE_TIME) {
      histogram_->Stop(&timer_, isolate_);
    }
  }

 private:
  base::ElapsedTimer timer_;
  TimedHistogram* const histogram_;
  Isolate* const isolate_;
  const OptionalTimedHistogramScopeMode mode_;
  DISALLOW_IMPLICIT_CONSTRUCTORS(OptionalTimedHistogramScope);
};

360 361 362 363 364 365 366 367
// Helper class for recording a TimedHistogram asynchronously with manual
// controls (it will not generate a report if destroyed without explicitly
// triggering a report). |async_counters| should be a shared_ptr to
// |histogram->counters()|, making it is safe to report to an
// AsyncTimedHistogram after the associated isolate has been destroyed.
// AsyncTimedHistogram can be moved/copied to avoid computing Now() multiple
// times when the times of multiple tasks are identical; each copy will generate
// its own report.
368
class AsyncTimedHistogram {
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
 public:
  explicit AsyncTimedHistogram(TimedHistogram* histogram,
                               std::shared_ptr<Counters> async_counters)
      : histogram_(histogram), async_counters_(std::move(async_counters)) {
    histogram_->AssertReportsToCounters(async_counters_.get());
    histogram_->Start(&timer_, nullptr);
  }

  // Records the time elapsed to |histogram_| and stops |timer_|.
  void RecordDone() { histogram_->Stop(&timer_, nullptr); }

  // Records TimeDelta::Max() to |histogram_| and stops |timer_|.
  void RecordAbandon() { histogram_->RecordAbandon(&timer_, nullptr); }

 private:
  base::ElapsedTimer timer_;
  TimedHistogram* histogram_;
  std::shared_ptr<Counters> async_counters_;
};

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
// Helper class for scoping a TimedHistogram, where the histogram is selected at
// stop time rather than start time.
// TODO(leszeks): This is heavily reliant on TimedHistogram::Start() doing
// nothing but starting the timer, and TimedHistogram::Stop() logging the sample
// correctly even if Start() was not called. This happens to be true iff Stop()
// is passed a null isolate, but that's an implementation detail of
// TimedHistogram, and we shouldn't rely on it.
class LazyTimedHistogramScope {
 public:
  LazyTimedHistogramScope() : histogram_(nullptr) { timer_.Start(); }
  ~LazyTimedHistogramScope() {
    // We should set the histogram before this scope exits.
    DCHECK_NOT_NULL(histogram_);
    histogram_->Stop(&timer_, nullptr);
  }

  void set_histogram(TimedHistogram* histogram) { histogram_ = histogram; }

 private:
  base::ElapsedTimer timer_;
  TimedHistogram* histogram_;
};

412 413 414 415 416 417 418 419 420 421
// A HistogramTimer allows distributions of non-nested timed results
// to be created. WARNING: This class is not thread safe and can only
// be run on the foreground thread.
class HistogramTimer : public TimedHistogram {
 public:
  // Note: public for testing purposes only.
  HistogramTimer(const char* name, int min, int max,
                 HistogramTimerResolution resolution, int num_buckets,
                 Counters* counters)
      : TimedHistogram(name, min, max, resolution, num_buckets, counters) {}
422

423 424
  inline void Start();
  inline void Stop();
425 426 427

  // Returns true if the timer is running.
  bool Running() {
428
    return Enabled() && timer_.IsStarted();
429
  }
430

431 432
  // TODO(bmeurer): Remove this when HistogramTimerScope is fixed.
#ifdef DEBUG
433
  base::ElapsedTimer* timer() { return &timer_; }
434 435
#endif

436
 private:
437 438
  friend class Counters;

439
  base::ElapsedTimer timer_;
440

441
  HistogramTimer() = default;
442 443
};

444
// Helper class for scoping a HistogramTimer.
445 446 447 448
// TODO(bmeurer): The ifdeffery is an ugly hack around the fact that the
// Parser is currently reentrant (when it throws an error, we call back
// into JavaScript and all bets are off), but ElapsedTimer is not
// reentry-safe. Fix this properly and remove |allow_nesting|.
449
class HistogramTimerScope {
450
 public:
451 452 453
  explicit HistogramTimerScope(HistogramTimer* timer,
                               bool allow_nesting = false)
#ifdef DEBUG
454
      : timer_(timer), skipped_timer_start_(false) {
455 456 457 458 459
    if (timer_->timer()->IsStarted() && allow_nesting) {
      skipped_timer_start_ = true;
    } else {
      timer_->Start();
    }
460
  }
461 462
#else
      : timer_(timer) {
463
    timer_->Start();
464
  }
465
#endif
466
  ~HistogramTimerScope() {
467 468 469 470 471
#ifdef DEBUG
    if (!skipped_timer_start_) {
      timer_->Stop();
    }
#else
472
    timer_->Stop();
473
#endif
474
  }
475

476
 private:
477
  HistogramTimer* timer_;
478 479 480
#ifdef DEBUG
  bool skipped_timer_start_;
#endif
481 482
};

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
// A histogram timer that can aggregate events within a larger scope.
//
// Intended use of this timer is to have an outer (aggregating) and an inner
// (to be aggregated) scope, where the inner scope measure the time of events,
// and all those inner scope measurements will be summed up by the outer scope.
// An example use might be to aggregate the time spent in lazy compilation
// while running a script.
//
// Helpers:
// - AggregatingHistogramTimerScope, the "outer" scope within which
//     times will be summed up.
// - AggregatedHistogramTimerScope, the "inner" scope which defines the
//     events to be timed.
class AggregatableHistogramTimer : public Histogram {
 public:
  // Start/stop the "outer" scope.
  void Start() { time_ = base::TimeDelta(); }
500 501 502 503 504 505 506
  void Stop() {
    if (time_ != base::TimeDelta()) {
      // Only add non-zero samples, since zero samples represent situations
      // where there were no aggregated samples added.
      AddSample(static_cast<int>(time_.InMicroseconds()));
    }
  }
507 508 509 510 511

  // Add a time value ("inner" scope).
  void Add(base::TimeDelta other) { time_ += other; }

 private:
512 513
  friend class Counters;

514
  AggregatableHistogramTimer() = default;
515 516 517 518
  AggregatableHistogramTimer(const char* name, int min, int max,
                             int num_buckets, Counters* counters)
      : Histogram(name, min, max, num_buckets, counters) {}

519 520 521
  base::TimeDelta time_;
};

522
// A helper class for use with AggregatableHistogramTimer. This is the
523 524
// // outer-most timer scope used with an AggregatableHistogramTimer. It will
// // aggregate the information from the inner AggregatedHistogramTimerScope.
525 526 527 528 529 530 531 532 533 534 535 536
class AggregatingHistogramTimerScope {
 public:
  explicit AggregatingHistogramTimerScope(AggregatableHistogramTimer* histogram)
      : histogram_(histogram) {
    histogram_->Start();
  }
  ~AggregatingHistogramTimerScope() { histogram_->Stop(); }

 private:
  AggregatableHistogramTimer* histogram_;
};

537
// A helper class for use with AggregatableHistogramTimer, the "inner" scope
538
// // which defines the events to be timed.
539 540 541 542 543 544 545 546 547 548 549 550 551 552
class AggregatedHistogramTimerScope {
 public:
  explicit AggregatedHistogramTimerScope(AggregatableHistogramTimer* histogram)
      : histogram_(histogram) {
    timer_.Start();
  }
  ~AggregatedHistogramTimerScope() { histogram_->Add(timer_.Elapsed()); }

 private:
  base::ElapsedTimer timer_;
  AggregatableHistogramTimer* histogram_;
};


553 554 555 556 557 558 559 560 561 562 563 564
// AggretatedMemoryHistogram collects (time, value) sample pairs and turns
// them into time-uniform samples for the backing historgram, such that the
// backing histogram receives one sample every T ms, where the T is controlled
// by the FLAG_histogram_interval.
//
// More formally: let F be a real-valued function that maps time to sample
// values. We define F as a linear interpolation between adjacent samples. For
// each time interval [x; x + T) the backing histogram gets one sample value
// that is the average of F(t) in the interval.
template <typename Histogram>
class AggregatedMemoryHistogram {
 public:
565
  // Note: public for testing purposes only.
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
  explicit AggregatedMemoryHistogram(Histogram* backing_histogram)
      : AggregatedMemoryHistogram() {
    backing_histogram_ = backing_histogram;
  }

  // Invariants that hold before and after AddSample if
  // is_initialized_ is true:
  //
  // 1) For we processed samples that came in before start_ms_ and sent the
  // corresponding aggregated samples to backing histogram.
  // 2) (last_ms_, last_value_) is the last received sample.
  // 3) last_ms_ < start_ms_ + FLAG_histogram_interval.
  // 4) aggregate_value_ is the average of the function that is constructed by
  // linearly interpolating samples received between start_ms_ and last_ms_.
  void AddSample(double current_ms, double current_value);

 private:
583 584 585 586 587 588 589 590
  friend class Counters;

  AggregatedMemoryHistogram()
      : is_initialized_(false),
        start_ms_(0.0),
        last_ms_(0.0),
        aggregate_value_(0.0),
        last_value_(0.0),
591
        backing_histogram_(nullptr) {}
592
  double Aggregate(double current_ms, double current_value);
593

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
  bool is_initialized_;
  double start_ms_;
  double last_ms_;
  double aggregate_value_;
  double last_value_;
  Histogram* backing_histogram_;
};


template <typename Histogram>
void AggregatedMemoryHistogram<Histogram>::AddSample(double current_ms,
                                                     double current_value) {
  if (!is_initialized_) {
    aggregate_value_ = current_value;
    start_ms_ = current_ms;
    last_value_ = current_value;
    last_ms_ = current_ms;
    is_initialized_ = true;
  } else {
    const double kEpsilon = 1e-6;
    const int kMaxSamples = 1000;
    if (current_ms < last_ms_ + kEpsilon) {
      // Two samples have the same time, remember the last one.
      last_value_ = current_value;
    } else {
      double sample_interval_ms = FLAG_histogram_interval;
      double end_ms = start_ms_ + sample_interval_ms;
      if (end_ms <= current_ms + kEpsilon) {
        // Linearly interpolate between the last_ms_ and the current_ms.
        double slope = (current_value - last_value_) / (current_ms - last_ms_);
        int i;
        // Send aggregated samples to the backing histogram from the start_ms
        // to the current_ms.
        for (i = 0; i < kMaxSamples && end_ms <= current_ms + kEpsilon; i++) {
          double end_value = last_value_ + (end_ms - last_ms_) * slope;
          double sample_value;
          if (i == 0) {
            // Take aggregate_value_ into account.
            sample_value = Aggregate(end_ms, end_value);
          } else {
            // There is no aggregate_value_ for i > 0.
            sample_value = (last_value_ + end_value) / 2;
          }
          backing_histogram_->AddSample(static_cast<int>(sample_value + 0.5));
          last_value_ = end_value;
          last_ms_ = end_ms;
          end_ms += sample_interval_ms;
        }
        if (i == kMaxSamples) {
          // We hit the sample limit, ignore the remaining samples.
          aggregate_value_ = current_value;
          start_ms_ = current_ms;
        } else {
          aggregate_value_ = last_value_;
          start_ms_ = last_ms_;
        }
      }
      aggregate_value_ = current_ms > start_ms_ + kEpsilon
                             ? Aggregate(current_ms, current_value)
                             : aggregate_value_;
      last_value_ = current_value;
      last_ms_ = current_ms;
    }
  }
}


template <typename Histogram>
double AggregatedMemoryHistogram<Histogram>::Aggregate(double current_ms,
                                                       double current_value) {
  double interval_ms = current_ms - start_ms_;
  double value = (current_value + last_value_) / 2;
  // The aggregate_value_ is the average for [start_ms_; last_ms_].
  // The value is the average for [last_ms_; current_ms].
  // Return the weighted average of the aggregate_value_ and the value.
  return aggregate_value_ * ((last_ms_ - start_ms_) / interval_ms) +
         value * ((current_ms - last_ms_) / interval_ms);
}

673 674
class RuntimeCallCounter final {
 public:
675
  RuntimeCallCounter() : RuntimeCallCounter(nullptr) {}
676 677
  explicit RuntimeCallCounter(const char* name)
      : name_(name), count_(0), time_(0) {}
678
  V8_NOINLINE void Reset();
679
  V8_NOINLINE void Dump(v8::tracing::TracedValue* value);
680
  void Add(RuntimeCallCounter* other);
681

682 683
  const char* name() const { return name_; }
  int64_t count() const { return count_; }
684 685 686
  base::TimeDelta time() const {
    return base::TimeDelta::FromMicroseconds(time_);
  }
687
  void Increment() { count_++; }
688
  void Add(base::TimeDelta delta) { time_ += delta.InMicroseconds(); }
689 690

 private:
691 692
  friend class RuntimeCallStats;

693
  const char* name_;
694 695 696
  int64_t count_;
  // Stored as int64_t so that its initialization can be deferred.
  int64_t time_;
697 698 699 700
};

// RuntimeCallTimer is used to keep track of the stack of currently active
// timers used for properly measuring the own time of a RuntimeCallCounter.
701
class RuntimeCallTimer final {
702
 public:
703
  RuntimeCallCounter* counter() { return counter_; }
704
  void set_counter(RuntimeCallCounter* counter) { counter_ = counter; }
705
  RuntimeCallTimer* parent() const { return parent_.Value(); }
706 707
  void set_parent(RuntimeCallTimer* timer) { parent_.SetValue(timer); }
  const char* name() const { return counter_->name(); }
708

709
  inline bool IsStarted();
710

711 712 713
  inline void Start(RuntimeCallCounter* counter, RuntimeCallTimer* parent);
  void Snapshot();
  inline RuntimeCallTimer* Stop();
714

715 716 717
  // Make the time source configurable for testing purposes.
  V8_EXPORT_PRIVATE static base::TimeTicks (*Now)();

718 719 720 721
 private:
  inline void Pause(base::TimeTicks now);
  inline void Resume(base::TimeTicks now);
  inline void CommitTimeToCounter();
722

723
  RuntimeCallCounter* counter_ = nullptr;
724
  base::AtomicValue<RuntimeCallTimer*> parent_;
725 726
  base::TimeTicks start_ticks_;
  base::TimeDelta elapsed_;
727 728
};

729 730 731
#define FOR_EACH_GC_COUNTER(V) \
  TRACER_SCOPES(V)             \
  TRACER_BACKGROUND_SCOPES(V)
732

733 734
#define FOR_EACH_API_COUNTER(V)                            \
  V(ArrayBuffer_Cast)                                      \
735
  V(ArrayBuffer_Detach)                                    \
736 737 738
  V(ArrayBuffer_New)                                       \
  V(Array_CloneElementAt)                                  \
  V(Array_New)                                             \
739
  V(BigInt64Array_New)                                     \
740
  V(BigInt_NewFromWords)                                   \
741
  V(BigIntObject_BigIntValue)                              \
742 743
  V(BigIntObject_New)                                      \
  V(BigUint64Array_New)                                    \
744 745 746
  V(BooleanObject_BooleanValue)                            \
  V(BooleanObject_New)                                     \
  V(Context_New)                                           \
747
  V(Context_NewRemoteContext)                              \
748 749 750 751
  V(DataView_New)                                          \
  V(Date_New)                                              \
  V(Date_NumberValue)                                      \
  V(Debug_Call)                                            \
752
  V(debug_GetPrivateFields)                                \
753 754 755 756 757 758 759 760 761
  V(Error_New)                                             \
  V(External_New)                                          \
  V(Float32Array_New)                                      \
  V(Float64Array_New)                                      \
  V(Function_Call)                                         \
  V(Function_New)                                          \
  V(Function_NewInstance)                                  \
  V(FunctionTemplate_GetFunction)                          \
  V(FunctionTemplate_New)                                  \
762
  V(FunctionTemplate_NewRemoteInstance)                    \
763
  V(FunctionTemplate_NewWithCache)                         \
764 765 766 767
  V(FunctionTemplate_NewWithFastHandler)                   \
  V(Int16Array_New)                                        \
  V(Int32Array_New)                                        \
  V(Int8Array_New)                                         \
768 769
  V(Isolate_DateTimeConfigurationChangeNotification)       \
  V(Isolate_LocaleConfigurationChangeNotification)         \
770 771 772 773 774 775 776 777 778 779 780 781 782
  V(JSON_Parse)                                            \
  V(JSON_Stringify)                                        \
  V(Map_AsArray)                                           \
  V(Map_Clear)                                             \
  V(Map_Delete)                                            \
  V(Map_Get)                                               \
  V(Map_Has)                                               \
  V(Map_New)                                               \
  V(Map_Set)                                               \
  V(Message_GetEndColumn)                                  \
  V(Message_GetLineNumber)                                 \
  V(Message_GetSourceLine)                                 \
  V(Message_GetStartColumn)                                \
783
  V(Module_Evaluate)                                       \
784
  V(Module_InstantiateModule)                              \
785 786 787 788 789 790
  V(NumberObject_New)                                      \
  V(NumberObject_NumberValue)                              \
  V(Object_CallAsConstructor)                              \
  V(Object_CallAsFunction)                                 \
  V(Object_CreateDataProperty)                             \
  V(Object_DefineOwnProperty)                              \
791
  V(Object_DefineProperty)                                 \
792 793 794 795 796 797 798 799 800 801 802 803
  V(Object_Delete)                                         \
  V(Object_DeleteProperty)                                 \
  V(Object_ForceSet)                                       \
  V(Object_Get)                                            \
  V(Object_GetOwnPropertyDescriptor)                       \
  V(Object_GetOwnPropertyNames)                            \
  V(Object_GetPropertyAttributes)                          \
  V(Object_GetPropertyNames)                               \
  V(Object_GetRealNamedProperty)                           \
  V(Object_GetRealNamedPropertyAttributes)                 \
  V(Object_GetRealNamedPropertyAttributesInPrototypeChain) \
  V(Object_GetRealNamedPropertyInPrototypeChain)           \
804
  V(Object_Has)                                            \
805 806 807 808 809 810 811 812 813 814 815 816 817 818
  V(Object_HasOwnProperty)                                 \
  V(Object_HasRealIndexedProperty)                         \
  V(Object_HasRealNamedCallbackProperty)                   \
  V(Object_HasRealNamedProperty)                           \
  V(Object_New)                                            \
  V(Object_ObjectProtoToString)                            \
  V(Object_Set)                                            \
  V(Object_SetAccessor)                                    \
  V(Object_SetIntegrityLevel)                              \
  V(Object_SetPrivate)                                     \
  V(Object_SetPrototype)                                   \
  V(ObjectTemplate_New)                                    \
  V(ObjectTemplate_NewInstance)                            \
  V(Object_ToArrayIndex)                                   \
819
  V(Object_ToBigInt)                                       \
820 821 822 823 824 825 826 827 828 829 830 831 832
  V(Object_ToDetailString)                                 \
  V(Object_ToInt32)                                        \
  V(Object_ToInteger)                                      \
  V(Object_ToNumber)                                       \
  V(Object_ToObject)                                       \
  V(Object_ToString)                                       \
  V(Object_ToUint32)                                       \
  V(Persistent_New)                                        \
  V(Private_New)                                           \
  V(Promise_Catch)                                         \
  V(Promise_Chain)                                         \
  V(Promise_HasRejectHandler)                              \
  V(Promise_Resolver_New)                                  \
833
  V(Promise_Resolver_Reject)                               \
834
  V(Promise_Resolver_Resolve)                              \
835 836
  V(Promise_Result)                                        \
  V(Promise_Status)                                        \
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
  V(Promise_Then)                                          \
  V(Proxy_New)                                             \
  V(RangeError_New)                                        \
  V(ReferenceError_New)                                    \
  V(RegExp_New)                                            \
  V(ScriptCompiler_Compile)                                \
  V(ScriptCompiler_CompileFunctionInContext)               \
  V(ScriptCompiler_CompileUnbound)                         \
  V(Script_Run)                                            \
  V(Set_Add)                                               \
  V(Set_AsArray)                                           \
  V(Set_Clear)                                             \
  V(Set_Delete)                                            \
  V(Set_Has)                                               \
  V(Set_New)                                               \
  V(SharedArrayBuffer_New)                                 \
  V(String_Concat)                                         \
  V(String_NewExternalOneByte)                             \
  V(String_NewExternalTwoByte)                             \
  V(String_NewFromOneByte)                                 \
  V(String_NewFromTwoByte)                                 \
  V(String_NewFromUtf8)                                    \
  V(StringObject_New)                                      \
  V(StringObject_StringValue)                              \
  V(String_Write)                                          \
  V(String_WriteUtf8)                                      \
  V(Symbol_New)                                            \
  V(SymbolObject_New)                                      \
  V(SymbolObject_SymbolValue)                              \
  V(SyntaxError_New)                                       \
867
  V(TracedGlobal_New)                                      \
868 869 870 871 872 873 874 875 876 877 878
  V(TryCatch_StackTrace)                                   \
  V(TypeError_New)                                         \
  V(Uint16Array_New)                                       \
  V(Uint32Array_New)                                       \
  V(Uint8Array_New)                                        \
  V(Uint8ClampedArray_New)                                 \
  V(UnboundScript_GetId)                                   \
  V(UnboundScript_GetLineNumber)                           \
  V(UnboundScript_GetName)                                 \
  V(UnboundScript_GetSourceMappingURL)                     \
  V(UnboundScript_GetSourceURL)                            \
879 880 881
  V(ValueDeserializer_ReadHeader)                          \
  V(ValueDeserializer_ReadValue)                           \
  V(ValueSerializer_WriteValue)                            \
882
  V(Value_InstanceOf)                                      \
883
  V(Value_Int32Value)                                      \
884
  V(Value_IntegerValue)                                    \
885
  V(Value_NumberValue)                                     \
886
  V(Value_TypeOf)                                          \
887
  V(Value_Uint32Value)                                     \
888 889 890
  V(WeakMap_Get)                                           \
  V(WeakMap_New)                                           \
  V(WeakMap_Set)
891

892 893
#define FOR_EACH_MANUAL_COUNTER(V)             \
  V(AccessorGetterCallback)                    \
894
  V(AccessorSetterCallback)                    \
895 896 897
  V(ArrayLengthGetter)                         \
  V(ArrayLengthSetter)                         \
  V(BoundFunctionLengthGetter)                 \
898 899
  V(BoundFunctionNameGetter)                   \
  V(CompileAnalyse)                            \
900
  V(CompileBackgroundAnalyse)                  \
901
  V(CompileBackgroundCompileTask)              \
902
  V(CompileBackgroundEval)                     \
903
  V(CompileBackgroundFunction)                 \
904
  V(CompileBackgroundIgnition)                 \
905 906
  V(CompileBackgroundRewriteReturnResult)      \
  V(CompileBackgroundScopeAnalysis)            \
907
  V(CompileBackgroundScript)                   \
908
  V(CompileCollectSourcePositions)             \
909
  V(CompileDeserialize)                        \
910
  V(CompileEnqueueOnDispatcher)                \
911
  V(CompileEval)                               \
912
  V(CompileFinalizeBackgroundCompileTask)      \
913
  V(CompileFinishNowOnDispatcher)              \
914 915 916 917 918 919 920 921 922 923
  V(CompileFunction)                           \
  V(CompileGetFromOptimizedCodeMap)            \
  V(CompileIgnition)                           \
  V(CompileIgnitionFinalization)               \
  V(CompileRewriteReturnResult)                \
  V(CompileScopeAnalysis)                      \
  V(CompileScript)                             \
  V(CompileSerialize)                          \
  V(CompileWaitForDispatcher)                  \
  V(DeoptimizeCode)                            \
924 925
  V(DeserializeContext)                        \
  V(DeserializeIsolate)                        \
926
  V(FunctionCallback)                          \
927
  V(FunctionLengthGetter)                      \
928 929 930 931 932 933 934
  V(FunctionPrototypeGetter)                   \
  V(FunctionPrototypeSetter)                   \
  V(GC_Custom_AllAvailableGarbage)             \
  V(GC_Custom_IncrementalMarkingObserver)      \
  V(GC_Custom_SlowAllocateRaw)                 \
  V(GCEpilogueCallback)                        \
  V(GCPrologueCallback)                        \
935
  V(Genesis)                                   \
936
  V(GetMoreDataCallback)                       \
937 938 939
  V(IndexedDefinerCallback)                    \
  V(IndexedDeleterCallback)                    \
  V(IndexedDescriptorCallback)                 \
940
  V(IndexedEnumeratorCallback)                 \
941 942 943
  V(IndexedGetterCallback)                     \
  V(IndexedQueryCallback)                      \
  V(IndexedSetterCallback)                     \
944 945
  V(Invoke)                                    \
  V(InvokeApiFunction)                         \
946 947 948 949 950 951
  V(InvokeApiInterruptCallbacks)               \
  V(InvokeFunctionCallback)                    \
  V(JS_Execution)                              \
  V(Map_SetPrototype)                          \
  V(Map_TransitionToAccessorProperty)          \
  V(Map_TransitionToDataProperty)              \
952 953 954 955 956 957 958 959
  V(MessageListenerCallback)                   \
  V(NamedDefinerCallback)                      \
  V(NamedDeleterCallback)                      \
  V(NamedDescriptorCallback)                   \
  V(NamedEnumeratorCallback)                   \
  V(NamedGetterCallback)                       \
  V(NamedQueryCallback)                        \
  V(NamedSetterCallback)                       \
960
  V(Object_DeleteProperty)                     \
961
  V(ObjectVerify)                              \
962 963 964 965
  V(OptimizeCode)                              \
  V(ParseArrowFunctionLiteral)                 \
  V(ParseBackgroundArrowFunctionLiteral)       \
  V(ParseBackgroundFunctionLiteral)            \
966
  V(ParseBackgroundProgram)                    \
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
  V(ParseEval)                                 \
  V(ParseFunction)                             \
  V(ParseFunctionLiteral)                      \
  V(ParseProgram)                              \
  V(PreParseArrowFunctionLiteral)              \
  V(PreParseBackgroundArrowFunctionLiteral)    \
  V(PreParseBackgroundWithVariableResolution)  \
  V(PreParseWithVariableResolution)            \
  V(PropertyCallback)                          \
  V(PrototypeMap_TransitionToAccessorProperty) \
  V(PrototypeMap_TransitionToDataProperty)     \
  V(PrototypeObject_DeleteProperty)            \
  V(RecompileConcurrent)                       \
  V(RecompileSynchronous)                      \
  V(ReconfigureToDataProperty)                 \
  V(StringLengthGetter)                        \
  V(TestCounter1)                              \
  V(TestCounter2)                              \
  V(TestCounter3)
986

987 988 989
#define FOR_EACH_HANDLER_COUNTER(V)               \
  V(KeyedLoadIC_KeyedLoadSloppyArgumentsStub)     \
  V(KeyedLoadIC_LoadElementDH)                    \
990
  V(KeyedLoadIC_LoadIndexedInterceptorStub)       \
991 992 993 994 995 996
  V(KeyedLoadIC_LoadIndexedStringDH)              \
  V(KeyedLoadIC_SlowStub)                         \
  V(KeyedStoreIC_ElementsTransitionAndStoreStub)  \
  V(KeyedStoreIC_KeyedStoreSloppyArgumentsStub)   \
  V(KeyedStoreIC_SlowStub)                        \
  V(KeyedStoreIC_StoreElementStub)                \
997
  V(KeyedStoreIC_StoreFastElementStub)            \
998 999
  V(LoadGlobalIC_LoadScriptContextField)          \
  V(LoadGlobalIC_SlowStub)                        \
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
  V(LoadIC_FunctionPrototypeStub)                 \
  V(LoadIC_HandlerCacheHit_Accessor)              \
  V(LoadIC_LoadAccessorDH)                        \
  V(LoadIC_LoadAccessorFromPrototypeDH)           \
  V(LoadIC_LoadApiGetterFromPrototypeDH)          \
  V(LoadIC_LoadCallback)                          \
  V(LoadIC_LoadConstantDH)                        \
  V(LoadIC_LoadConstantFromPrototypeDH)           \
  V(LoadIC_LoadFieldDH)                           \
  V(LoadIC_LoadFieldFromPrototypeDH)              \
  V(LoadIC_LoadGlobalDH)                          \
  V(LoadIC_LoadGlobalFromPrototypeDH)             \
  V(LoadIC_LoadIntegerIndexedExoticDH)            \
  V(LoadIC_LoadInterceptorDH)                     \
  V(LoadIC_LoadInterceptorFromPrototypeDH)        \
  V(LoadIC_LoadNativeDataPropertyDH)              \
  V(LoadIC_LoadNativeDataPropertyFromPrototypeDH) \
  V(LoadIC_LoadNonexistentDH)                     \
1018
  V(LoadIC_LoadNonMaskingInterceptorDH)           \
1019 1020 1021 1022 1023 1024
  V(LoadIC_LoadNormalDH)                          \
  V(LoadIC_LoadNormalFromPrototypeDH)             \
  V(LoadIC_NonReceiver)                           \
  V(LoadIC_Premonomorphic)                        \
  V(LoadIC_SlowStub)                              \
  V(LoadIC_StringLength)                          \
1025
  V(LoadIC_StringWrapperLength)                   \
1026
  V(StoreGlobalIC_SlowStub)                       \
1027
  V(StoreGlobalIC_StoreScriptContextField)        \
1028
  V(StoreGlobalIC_Premonomorphic)                 \
1029 1030 1031 1032
  V(StoreIC_HandlerCacheHit_Accessor)             \
  V(StoreIC_NonReceiver)                          \
  V(StoreIC_Premonomorphic)                       \
  V(StoreIC_SlowStub)                             \
1033 1034
  V(StoreIC_StoreAccessorDH)                      \
  V(StoreIC_StoreAccessorOnPrototypeDH)           \
1035
  V(StoreIC_StoreApiSetterOnPrototypeDH)          \
1036 1037 1038 1039
  V(StoreIC_StoreFieldDH)                         \
  V(StoreIC_StoreGlobalDH)                        \
  V(StoreIC_StoreGlobalTransitionDH)              \
  V(StoreIC_StoreInterceptorStub)                 \
1040 1041
  V(StoreIC_StoreNativeDataPropertyDH)            \
  V(StoreIC_StoreNativeDataPropertyOnPrototypeDH) \
1042
  V(StoreIC_StoreNormalDH)                        \
1043 1044
  V(StoreIC_StoreTransitionDH)                    \
  V(StoreInArrayLiteralIC_SlowStub)
1045

1046 1047
enum RuntimeCallCounterId {
#define CALL_RUNTIME_COUNTER(name) kGC_##name,
1048 1049
  FOR_EACH_GC_COUNTER(CALL_RUNTIME_COUNTER)
#undef CALL_RUNTIME_COUNTER
1050 1051
#define CALL_RUNTIME_COUNTER(name) k##name,
      FOR_EACH_MANUAL_COUNTER(CALL_RUNTIME_COUNTER)
1052
#undef CALL_RUNTIME_COUNTER
1053 1054
#define CALL_RUNTIME_COUNTER(name, nargs, ressize) kRuntime_##name,
          FOR_EACH_INTRINSIC(CALL_RUNTIME_COUNTER)
1055
#undef CALL_RUNTIME_COUNTER
1056 1057
#define CALL_BUILTIN_COUNTER(name) kBuiltin_##name,
              BUILTIN_LIST_C(CALL_BUILTIN_COUNTER)
1058
#undef CALL_BUILTIN_COUNTER
1059 1060
#define CALL_BUILTIN_COUNTER(name) kAPI_##name,
                  FOR_EACH_API_COUNTER(CALL_BUILTIN_COUNTER)
1061
#undef CALL_BUILTIN_COUNTER
1062 1063
#define CALL_BUILTIN_COUNTER(name) kHandler_##name,
                      FOR_EACH_HANDLER_COUNTER(CALL_BUILTIN_COUNTER)
1064
#undef CALL_BUILTIN_COUNTER
1065 1066
                          kNumberOfCounters
};
1067

1068
class RuntimeCallStats final {
1069 1070
 public:
  V8_EXPORT_PRIVATE RuntimeCallStats();
1071

1072 1073
  // Starting measuring the time for a function. This will establish the
  // connection to the parent counter for properly calculating the own times.
1074 1075
  V8_EXPORT_PRIVATE void Enter(RuntimeCallTimer* timer,
                               RuntimeCallCounterId counter_id);
1076

1077 1078 1079
  // Leave a scope for a measured runtime function. This will properly add
  // the time delta to the current_counter and subtract the delta from its
  // parent.
1080
  V8_EXPORT_PRIVATE void Leave(RuntimeCallTimer* timer);
1081

1082 1083
  // Set counter id for the innermost measurement. It can be used to refine
  // event kind when a runtime entry counter is too generic.
1084 1085
  V8_EXPORT_PRIVATE void CorrectCurrentCounterId(
      RuntimeCallCounterId counter_id);
1086

1087
  V8_EXPORT_PRIVATE void Reset();
1088 1089
  // Add all entries from another stats object.
  void Add(RuntimeCallStats* other);
1090
  V8_EXPORT_PRIVATE void Print(std::ostream& os);
1091
  V8_EXPORT_PRIVATE void Print();
1092
  V8_NOINLINE void Dump(v8::tracing::TracedValue* value);
1093

1094
  ThreadId thread_id() const { return thread_id_; }
1095
  RuntimeCallTimer* current_timer() { return current_timer_.Value(); }
1096
  RuntimeCallCounter* current_counter() { return current_counter_.Value(); }
1097
  bool InUse() { return in_use_; }
1098
  bool IsCalledOnTheSameThread();
1099

1100 1101 1102 1103 1104 1105 1106 1107 1108
  static const int kNumberOfCounters =
      static_cast<int>(RuntimeCallCounterId::kNumberOfCounters);
  RuntimeCallCounter* GetCounter(RuntimeCallCounterId counter_id) {
    return &counters_[static_cast<int>(counter_id)];
  }
  RuntimeCallCounter* GetCounter(int counter_id) {
    return &counters_[counter_id];
  }

1109
 private:
1110
  // Top of a stack of active timers.
1111
  base::AtomicValue<RuntimeCallTimer*> current_timer_;
1112 1113
  // Active counter object associated with current timer.
  base::AtomicValue<RuntimeCallCounter*> current_counter_;
1114
  // Used to track nested tracing scopes.
1115
  bool in_use_;
1116
  ThreadId thread_id_;
1117
  RuntimeCallCounter counters_[kNumberOfCounters];
1118 1119
};

1120 1121 1122 1123 1124 1125
class WorkerThreadRuntimeCallStats final {
 public:
  WorkerThreadRuntimeCallStats();
  ~WorkerThreadRuntimeCallStats();

  // Returns the TLS key associated with this WorkerThreadRuntimeCallStats.
1126
  base::Thread::LocalStorageKey GetKey();
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137

  // Returns a new worker thread runtime call stats table managed by this
  // WorkerThreadRuntimeCallStats.
  RuntimeCallStats* NewTable();

  // Adds the counters from the worker thread tables to |main_call_stats|.
  void AddToMainTable(RuntimeCallStats* main_call_stats);

 private:
  base::Mutex mutex_;
  std::vector<std::unique_ptr<RuntimeCallStats>> tables_;
1138
  base::Optional<base::Thread::LocalStorageKey> tls_key_;
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
};

// Creating a WorkerThreadRuntimeCallStatsScope will provide a thread-local
// runtime call stats table, and will dump the table to an immediate trace event
// when it is destroyed.
class WorkerThreadRuntimeCallStatsScope final {
 public:
  WorkerThreadRuntimeCallStatsScope(
      WorkerThreadRuntimeCallStats* off_thread_stats);
  ~WorkerThreadRuntimeCallStatsScope();

  RuntimeCallStats* Get() const { return table_; }

 private:
  RuntimeCallStats* table_;
};

1156 1157
#define CHANGE_CURRENT_RUNTIME_COUNTER(runtime_call_stats, counter_id) \
  do {                                                                 \
1158 1159
    if (V8_UNLIKELY(TracingFlags::is_runtime_stats_enabled()) &&       \
        runtime_call_stats) {                                          \
1160
      runtime_call_stats->CorrectCurrentCounterId(counter_id);         \
1161
    }                                                                  \
1162 1163
  } while (false)

1164 1165 1166 1167
#define TRACE_HANDLER_STATS(isolate, counter_name) \
  CHANGE_CURRENT_RUNTIME_COUNTER(                  \
      isolate->counters()->runtime_call_stats(),   \
      RuntimeCallCounterId::kHandler_##counter_name)
1168

1169 1170 1171 1172 1173
// A RuntimeCallTimerScopes wraps around a RuntimeCallTimer to measure the
// the time of C++ scope.
class RuntimeCallTimerScope {
 public:
  inline RuntimeCallTimerScope(Isolate* isolate,
1174
                               RuntimeCallCounterId counter_id);
1175 1176
  // This constructor is here just to avoid calling GetIsolate() when the
  // stats are disabled and the isolate is not directly available.
1177
  inline RuntimeCallTimerScope(Isolate* isolate, HeapObject heap_object,
1178
                               RuntimeCallCounterId counter_id);
1179
  inline RuntimeCallTimerScope(RuntimeCallStats* stats,
1180
                               RuntimeCallCounterId counter_id) {
1181 1182 1183
    if (V8_LIKELY(!TracingFlags::is_runtime_stats_enabled() ||
                  stats == nullptr))
      return;
1184
    stats_ = stats;
1185
    stats_->Enter(&timer_, counter_id);
1186
  }
1187 1188 1189

  inline ~RuntimeCallTimerScope() {
    if (V8_UNLIKELY(stats_ != nullptr)) {
1190
      stats_->Leave(&timer_);
1191 1192
    }
  }
1193 1194 1195 1196

 private:
  RuntimeCallStats* stats_ = nullptr;
  RuntimeCallTimer timer_;
1197 1198

  DISALLOW_COPY_AND_ASSIGN(RuntimeCallTimerScope);
1199 1200
};

1201
// This file contains all the v8 counters that are in use.
1202
class Counters : public std::enable_shared_from_this<Counters> {
1203
 public:
1204 1205
  explicit Counters(Isolate* isolate);

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
  // Register an application-defined function for recording
  // subsequent counter statistics. Note: Must be called on the main
  // thread.
  void ResetCounterFunction(CounterLookupCallback f);

  // Register an application-defined function to create histograms for
  // recording subsequent histogram samples. Note: Must be called on
  // the main thread.
  void ResetCreateHistogramFunction(CreateHistogramCallback f);

  // Register an application-defined function to add a sample
  // to a histogram. Will be used in all subsequent sample additions.
  // Note: Must be called on the main thread.
  void SetAddHistogramSampleFunction(AddHistogramSampleCallback f) {
    stats_table_.SetAddHistogramSampleFunction(f);
  }

1223 1224 1225 1226 1227
#define HR(name, caption, min, max, num_buckets) \
  Histogram* name() { return &name##_; }
  HISTOGRAM_RANGE_LIST(HR)
#undef HR

yangguo's avatar
yangguo committed
1228
#define HT(name, caption, max, res) \
1229 1230 1231 1232
  HistogramTimer* name() { return &name##_; }
  HISTOGRAM_TIMER_LIST(HT)
#undef HT

1233 1234 1235 1236 1237
#define HT(name, caption, max, res) \
  TimedHistogram* name() { return &name##_; }
  TIMED_HISTOGRAM_LIST(HT)
#undef HT

1238 1239 1240 1241 1242
#define AHT(name, caption) \
  AggregatableHistogramTimer* name() { return &name##_; }
  AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT)
#undef AHT

1243 1244 1245 1246 1247 1248 1249
#define HP(name, caption) \
  Histogram* name() { return &name##_; }
  HISTOGRAM_PERCENTAGE_LIST(HP)
#undef HP

#define HM(name, caption) \
  Histogram* name() { return &name##_; }
1250
  HISTOGRAM_LEGACY_MEMORY_LIST(HM)
1251 1252 1253 1254 1255 1256
#undef HM

#define SC(name, caption) \
  StatsCounter* name() { return &name##_; }
  STATS_COUNTER_LIST_1(SC)
  STATS_COUNTER_LIST_2(SC)
1257
  STATS_COUNTER_NATIVE_CODE_LIST(SC)
1258 1259
#undef SC

1260 1261 1262 1263 1264 1265
#define SC(name, caption) \
  StatsCounterThreadSafe* name() { return &name##_; }
  STATS_COUNTER_TS_LIST(SC)
#undef SC

  // clang-format off
1266
  enum Id {
yangguo's avatar
yangguo committed
1267
#define RATE_ID(name, caption, max, res) k_##name,
1268
    HISTOGRAM_TIMER_LIST(RATE_ID)
1269
    TIMED_HISTOGRAM_LIST(RATE_ID)
1270
#undef RATE_ID
1271 1272 1273
#define AGGREGATABLE_ID(name, caption) k_##name,
    AGGREGATABLE_HISTOGRAM_TIMER_LIST(AGGREGATABLE_ID)
#undef AGGREGATABLE_ID
1274 1275 1276 1277
#define PERCENTAGE_ID(name, caption) k_##name,
    HISTOGRAM_PERCENTAGE_LIST(PERCENTAGE_ID)
#undef PERCENTAGE_ID
#define MEMORY_ID(name, caption) k_##name,
1278
    HISTOGRAM_LEGACY_MEMORY_LIST(MEMORY_ID)
1279 1280 1281 1282
#undef MEMORY_ID
#define COUNTER_ID(name, caption) k_##name,
    STATS_COUNTER_LIST_1(COUNTER_ID)
    STATS_COUNTER_LIST_2(COUNTER_ID)
1283
    STATS_COUNTER_TS_LIST(COUNTER_ID)
1284
    STATS_COUNTER_NATIVE_CODE_LIST(COUNTER_ID)
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
#undef COUNTER_ID
#define COUNTER_ID(name) kCountOf##name, kSizeOf##name,
    INSTANCE_TYPE_LIST(COUNTER_ID)
#undef COUNTER_ID
#define COUNTER_ID(name) kCountOfCODE_TYPE_##name, \
    kSizeOfCODE_TYPE_##name,
    CODE_KIND_LIST(COUNTER_ID)
#undef COUNTER_ID
#define COUNTER_ID(name) kCountOfFIXED_ARRAY__##name, \
    kSizeOfFIXED_ARRAY__##name,
    FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(COUNTER_ID)
#undef COUNTER_ID
    stats_counter_count
  };
1299
  // clang-format on
1300

1301
  RuntimeCallStats* runtime_call_stats() { return &runtime_call_stats_; }
1302

1303 1304 1305 1306
  WorkerThreadRuntimeCallStats* worker_thread_runtime_call_stats() {
    return &worker_thread_runtime_call_stats_;
  }

1307
 private:
1308 1309 1310 1311 1312
  friend class StatsTable;
  friend class StatsCounterBase;
  friend class Histogram;
  friend class HistogramTimer;

1313 1314 1315
  Isolate* isolate_;
  StatsTable stats_table_;

1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
  int* FindLocation(const char* name) {
    return stats_table_.FindLocation(name);
  }

  void* CreateHistogram(const char* name, int min, int max, size_t buckets) {
    return stats_table_.CreateHistogram(name, min, max, buckets);
  }

  void AddHistogramSample(void* histogram, int sample) {
    stats_table_.AddHistogramSample(histogram, sample);
  }

  Isolate* isolate() { return isolate_; }

1330 1331 1332 1333
#define HR(name, caption, min, max, num_buckets) Histogram name##_;
  HISTOGRAM_RANGE_LIST(HR)
#undef HR

yangguo's avatar
yangguo committed
1334
#define HT(name, caption, max, res) HistogramTimer name##_;
1335 1336 1337
  HISTOGRAM_TIMER_LIST(HT)
#undef HT

1338 1339 1340 1341
#define HT(name, caption, max, res) TimedHistogram name##_;
  TIMED_HISTOGRAM_LIST(HT)
#undef HT

1342 1343 1344 1345 1346
#define AHT(name, caption) \
  AggregatableHistogramTimer name##_;
  AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT)
#undef AHT

1347 1348 1349 1350 1351 1352 1353
#define HP(name, caption) \
  Histogram name##_;
  HISTOGRAM_PERCENTAGE_LIST(HP)
#undef HP

#define HM(name, caption) \
  Histogram name##_;
1354
  HISTOGRAM_LEGACY_MEMORY_LIST(HM)
1355 1356 1357 1358 1359 1360
#undef HM

#define SC(name, caption) \
  StatsCounter name##_;
  STATS_COUNTER_LIST_1(SC)
  STATS_COUNTER_LIST_2(SC)
1361
  STATS_COUNTER_NATIVE_CODE_LIST(SC)
1362 1363
#undef SC

1364 1365 1366 1367
#define SC(name, caption) StatsCounterThreadSafe name##_;
  STATS_COUNTER_TS_LIST(SC)
#undef SC

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
#define SC(name) \
  StatsCounter size_of_##name##_; \
  StatsCounter count_of_##name##_;
  INSTANCE_TYPE_LIST(SC)
#undef SC

#define SC(name) \
  StatsCounter size_of_CODE_TYPE_##name##_; \
  StatsCounter count_of_CODE_TYPE_##name##_;
  CODE_KIND_LIST(SC)
#undef SC

#define SC(name) \
  StatsCounter size_of_FIXED_ARRAY_##name##_; \
  StatsCounter count_of_FIXED_ARRAY_##name##_;
  FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(SC)
#undef SC

1386
  RuntimeCallStats runtime_call_stats_;
1387
  WorkerThreadRuntimeCallStats worker_thread_runtime_call_stats_;
1388

1389 1390 1391
  DISALLOW_IMPLICIT_CONSTRUCTORS(Counters);
};

1392 1393 1394 1395 1396 1397 1398 1399
void HistogramTimer::Start() {
  TimedHistogram::Start(&timer_, counters()->isolate());
}

void HistogramTimer::Stop() {
  TimedHistogram::Stop(&timer_, counters()->isolate());
}

1400 1401
RuntimeCallTimerScope::RuntimeCallTimerScope(Isolate* isolate,
                                             RuntimeCallCounterId counter_id) {
1402
  if (V8_LIKELY(!TracingFlags::is_runtime_stats_enabled())) return;
1403
  stats_ = isolate->counters()->runtime_call_stats();
1404
  stats_->Enter(&timer_, counter_id);
1405 1406
}

1407 1408
}  // namespace internal
}  // namespace v8
1409 1410

#endif  // V8_COUNTERS_H_