• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef V8_COUNTERS_H_
6 #define V8_COUNTERS_H_
7 
8 #include "include/v8.h"
9 #include "src/allocation.h"
10 #include "src/base/platform/elapsed-timer.h"
11 #include "src/base/platform/time.h"
12 #include "src/builtins.h"
13 #include "src/globals.h"
14 #include "src/objects.h"
15 #include "src/runtime/runtime.h"
16 
17 namespace v8 {
18 namespace internal {
19 
20 // StatsCounters is an interface for plugging into external
21 // counters for monitoring.  Counters can be looked up and
22 // manipulated by name.
23 
24 class StatsTable {
25  public:
26   // Register an application-defined function where
27   // counters can be looked up.
SetCounterFunction(CounterLookupCallback f)28   void SetCounterFunction(CounterLookupCallback f) {
29     lookup_function_ = f;
30   }
31 
32   // Register an application-defined function to create
33   // a histogram for passing to the AddHistogramSample function
SetCreateHistogramFunction(CreateHistogramCallback f)34   void SetCreateHistogramFunction(CreateHistogramCallback f) {
35     create_histogram_function_ = f;
36   }
37 
38   // Register an application-defined function to add a sample
39   // to a histogram created with CreateHistogram function
SetAddHistogramSampleFunction(AddHistogramSampleCallback f)40   void SetAddHistogramSampleFunction(AddHistogramSampleCallback f) {
41     add_histogram_sample_function_ = f;
42   }
43 
HasCounterFunction()44   bool HasCounterFunction() const {
45     return lookup_function_ != NULL;
46   }
47 
48   // Lookup the location of a counter by name.  If the lookup
49   // is successful, returns a non-NULL pointer for writing the
50   // value of the counter.  Each thread calling this function
51   // may receive a different location to store it's counter.
52   // The return value must not be cached and re-used across
53   // threads, although a single thread is free to cache it.
FindLocation(const char * name)54   int* FindLocation(const char* name) {
55     if (!lookup_function_) return NULL;
56     return lookup_function_(name);
57   }
58 
59   // Create a histogram by name. If the create is successful,
60   // returns a non-NULL pointer for use with AddHistogramSample
61   // function. min and max define the expected minimum and maximum
62   // sample values. buckets is the maximum number of buckets
63   // that the samples will be grouped into.
CreateHistogram(const char * name,int min,int max,size_t buckets)64   void* CreateHistogram(const char* name,
65                         int min,
66                         int max,
67                         size_t buckets) {
68     if (!create_histogram_function_) return NULL;
69     return create_histogram_function_(name, min, max, buckets);
70   }
71 
72   // Add a sample to a histogram created with the CreateHistogram
73   // function.
AddHistogramSample(void * histogram,int sample)74   void AddHistogramSample(void* histogram, int sample) {
75     if (!add_histogram_sample_function_) return;
76     return add_histogram_sample_function_(histogram, sample);
77   }
78 
79  private:
80   StatsTable();
81 
82   CounterLookupCallback lookup_function_;
83   CreateHistogramCallback create_histogram_function_;
84   AddHistogramSampleCallback add_histogram_sample_function_;
85 
86   friend class Isolate;
87 
88   DISALLOW_COPY_AND_ASSIGN(StatsTable);
89 };
90 
91 // StatsCounters are dynamically created values which can be tracked in
92 // the StatsTable.  They are designed to be lightweight to create and
93 // easy to use.
94 //
95 // Internally, a counter represents a value in a row of a StatsTable.
96 // The row has a 32bit value for each process/thread in the table and also
97 // a name (stored in the table metadata).  Since the storage location can be
98 // thread-specific, this class cannot be shared across threads.
99 class StatsCounter {
100  public:
StatsCounter()101   StatsCounter() { }
StatsCounter(Isolate * isolate,const char * name)102   explicit StatsCounter(Isolate* isolate, const char* name)
103       : isolate_(isolate), name_(name), ptr_(NULL), lookup_done_(false) { }
104 
105   // Sets the counter to a specific value.
Set(int value)106   void Set(int value) {
107     int* loc = GetPtr();
108     if (loc) *loc = value;
109   }
110 
111   // Increments the counter.
Increment()112   void Increment() {
113     int* loc = GetPtr();
114     if (loc) (*loc)++;
115   }
116 
Increment(int value)117   void Increment(int value) {
118     int* loc = GetPtr();
119     if (loc)
120       (*loc) += value;
121   }
122 
123   // Decrements the counter.
Decrement()124   void Decrement() {
125     int* loc = GetPtr();
126     if (loc) (*loc)--;
127   }
128 
Decrement(int value)129   void Decrement(int value) {
130     int* loc = GetPtr();
131     if (loc) (*loc) -= value;
132   }
133 
134   // Is this counter enabled?
135   // Returns false if table is full.
Enabled()136   bool Enabled() {
137     return GetPtr() != NULL;
138   }
139 
140   // Get the internal pointer to the counter. This is used
141   // by the code generator to emit code that manipulates a
142   // given counter without calling the runtime system.
GetInternalPointer()143   int* GetInternalPointer() {
144     int* loc = GetPtr();
145     DCHECK(loc != NULL);
146     return loc;
147   }
148 
149   // Reset the cached internal pointer.
Reset()150   void Reset() { lookup_done_ = false; }
151 
152  protected:
153   // Returns the cached address of this counter location.
GetPtr()154   int* GetPtr() {
155     if (lookup_done_) return ptr_;
156     lookup_done_ = true;
157     ptr_ = FindLocationInStatsTable();
158     return ptr_;
159   }
160 
161  private:
162   int* FindLocationInStatsTable() const;
163 
164   Isolate* isolate_;
165   const char* name_;
166   int* ptr_;
167   bool lookup_done_;
168 };
169 
170 // A Histogram represents a dynamically created histogram in the StatsTable.
171 // It will be registered with the histogram system on first use.
172 class Histogram {
173  public:
Histogram()174   Histogram() { }
Histogram(const char * name,int min,int max,int num_buckets,Isolate * isolate)175   Histogram(const char* name,
176             int min,
177             int max,
178             int num_buckets,
179             Isolate* isolate)
180       : name_(name),
181         min_(min),
182         max_(max),
183         num_buckets_(num_buckets),
184         histogram_(NULL),
185         lookup_done_(false),
186         isolate_(isolate) { }
187 
188   // Add a single sample to this histogram.
189   void AddSample(int sample);
190 
191   // Returns true if this histogram is enabled.
Enabled()192   bool Enabled() {
193     return GetHistogram() != NULL;
194   }
195 
196   // Reset the cached internal pointer.
Reset()197   void Reset() {
198     lookup_done_ = false;
199   }
200 
name()201   const char* name() { return name_; }
202 
203  protected:
204   // Returns the handle to the histogram.
GetHistogram()205   void* GetHistogram() {
206     if (!lookup_done_) {
207       lookup_done_ = true;
208       histogram_ = CreateHistogram();
209     }
210     return histogram_;
211   }
212 
isolate()213   Isolate* isolate() const { return isolate_; }
214 
215  private:
216   void* CreateHistogram() const;
217 
218   const char* name_;
219   int min_;
220   int max_;
221   int num_buckets_;
222   void* histogram_;
223   bool lookup_done_;
224   Isolate* isolate_;
225 };
226 
227 // A HistogramTimer allows distributions of results to be created.
228 class HistogramTimer : public Histogram {
229  public:
230   enum Resolution {
231     MILLISECOND,
232     MICROSECOND
233   };
234 
HistogramTimer()235   HistogramTimer() {}
HistogramTimer(const char * name,int min,int max,Resolution resolution,int num_buckets,Isolate * isolate)236   HistogramTimer(const char* name, int min, int max, Resolution resolution,
237                  int num_buckets, Isolate* isolate)
238       : Histogram(name, min, max, num_buckets, isolate),
239         resolution_(resolution) {}
240 
241   // Start the timer.
242   void Start();
243 
244   // Stop the timer and record the results.
245   void Stop();
246 
247   // Returns true if the timer is running.
Running()248   bool Running() {
249     return Enabled() && timer_.IsStarted();
250   }
251 
252   // TODO(bmeurer): Remove this when HistogramTimerScope is fixed.
253 #ifdef DEBUG
timer()254   base::ElapsedTimer* timer() { return &timer_; }
255 #endif
256 
257  private:
258   base::ElapsedTimer timer_;
259   Resolution resolution_;
260 };
261 
262 // Helper class for scoping a HistogramTimer.
263 // TODO(bmeurer): The ifdeffery is an ugly hack around the fact that the
264 // Parser is currently reentrant (when it throws an error, we call back
265 // into JavaScript and all bets are off), but ElapsedTimer is not
266 // reentry-safe. Fix this properly and remove |allow_nesting|.
267 class HistogramTimerScope BASE_EMBEDDED {
268  public:
269   explicit HistogramTimerScope(HistogramTimer* timer,
270                                bool allow_nesting = false)
271 #ifdef DEBUG
timer_(timer)272       : timer_(timer),
273         skipped_timer_start_(false) {
274     if (timer_->timer()->IsStarted() && allow_nesting) {
275       skipped_timer_start_ = true;
276     } else {
277       timer_->Start();
278     }
279   }
280 #else
281       : timer_(timer) {
282     timer_->Start();
283   }
284 #endif
~HistogramTimerScope()285   ~HistogramTimerScope() {
286 #ifdef DEBUG
287     if (!skipped_timer_start_) {
288       timer_->Stop();
289     }
290 #else
291     timer_->Stop();
292 #endif
293   }
294 
295  private:
296   HistogramTimer* timer_;
297 #ifdef DEBUG
298   bool skipped_timer_start_;
299 #endif
300 };
301 
302 
303 // A histogram timer that can aggregate events within a larger scope.
304 //
305 // Intended use of this timer is to have an outer (aggregating) and an inner
306 // (to be aggregated) scope, where the inner scope measure the time of events,
307 // and all those inner scope measurements will be summed up by the outer scope.
308 // An example use might be to aggregate the time spent in lazy compilation
309 // while running a script.
310 //
311 // Helpers:
312 // - AggregatingHistogramTimerScope, the "outer" scope within which
313 //     times will be summed up.
314 // - AggregatedHistogramTimerScope, the "inner" scope which defines the
315 //     events to be timed.
316 class AggregatableHistogramTimer : public Histogram {
317  public:
AggregatableHistogramTimer()318   AggregatableHistogramTimer() {}
AggregatableHistogramTimer(const char * name,int min,int max,int num_buckets,Isolate * isolate)319   AggregatableHistogramTimer(const char* name, int min, int max,
320                              int num_buckets, Isolate* isolate)
321       : Histogram(name, min, max, num_buckets, isolate) {}
322 
323   // Start/stop the "outer" scope.
Start()324   void Start() { time_ = base::TimeDelta(); }
Stop()325   void Stop() { AddSample(static_cast<int>(time_.InMicroseconds())); }
326 
327   // Add a time value ("inner" scope).
Add(base::TimeDelta other)328   void Add(base::TimeDelta other) { time_ += other; }
329 
330  private:
331   base::TimeDelta time_;
332 };
333 
334 // A helper class for use with AggregatableHistogramTimer. This is the
335 // // outer-most timer scope used with an AggregatableHistogramTimer. It will
336 // // aggregate the information from the inner AggregatedHistogramTimerScope.
337 class AggregatingHistogramTimerScope {
338  public:
AggregatingHistogramTimerScope(AggregatableHistogramTimer * histogram)339   explicit AggregatingHistogramTimerScope(AggregatableHistogramTimer* histogram)
340       : histogram_(histogram) {
341     histogram_->Start();
342   }
~AggregatingHistogramTimerScope()343   ~AggregatingHistogramTimerScope() { histogram_->Stop(); }
344 
345  private:
346   AggregatableHistogramTimer* histogram_;
347 };
348 
349 // A helper class for use with AggregatableHistogramTimer, the "inner" scope
350 // // which defines the events to be timed.
351 class AggregatedHistogramTimerScope {
352  public:
AggregatedHistogramTimerScope(AggregatableHistogramTimer * histogram)353   explicit AggregatedHistogramTimerScope(AggregatableHistogramTimer* histogram)
354       : histogram_(histogram) {
355     timer_.Start();
356   }
~AggregatedHistogramTimerScope()357   ~AggregatedHistogramTimerScope() { histogram_->Add(timer_.Elapsed()); }
358 
359  private:
360   base::ElapsedTimer timer_;
361   AggregatableHistogramTimer* histogram_;
362 };
363 
364 
365 // AggretatedMemoryHistogram collects (time, value) sample pairs and turns
366 // them into time-uniform samples for the backing historgram, such that the
367 // backing histogram receives one sample every T ms, where the T is controlled
368 // by the FLAG_histogram_interval.
369 //
370 // More formally: let F be a real-valued function that maps time to sample
371 // values. We define F as a linear interpolation between adjacent samples. For
372 // each time interval [x; x + T) the backing histogram gets one sample value
373 // that is the average of F(t) in the interval.
374 template <typename Histogram>
375 class AggregatedMemoryHistogram {
376  public:
AggregatedMemoryHistogram()377   AggregatedMemoryHistogram()
378       : is_initialized_(false),
379         start_ms_(0.0),
380         last_ms_(0.0),
381         aggregate_value_(0.0),
382         last_value_(0.0),
383         backing_histogram_(NULL) {}
384 
AggregatedMemoryHistogram(Histogram * backing_histogram)385   explicit AggregatedMemoryHistogram(Histogram* backing_histogram)
386       : AggregatedMemoryHistogram() {
387     backing_histogram_ = backing_histogram;
388   }
389 
390   // Invariants that hold before and after AddSample if
391   // is_initialized_ is true:
392   //
393   // 1) For we processed samples that came in before start_ms_ and sent the
394   // corresponding aggregated samples to backing histogram.
395   // 2) (last_ms_, last_value_) is the last received sample.
396   // 3) last_ms_ < start_ms_ + FLAG_histogram_interval.
397   // 4) aggregate_value_ is the average of the function that is constructed by
398   // linearly interpolating samples received between start_ms_ and last_ms_.
399   void AddSample(double current_ms, double current_value);
400 
401  private:
402   double Aggregate(double current_ms, double current_value);
403   bool is_initialized_;
404   double start_ms_;
405   double last_ms_;
406   double aggregate_value_;
407   double last_value_;
408   Histogram* backing_histogram_;
409 };
410 
411 
412 template <typename Histogram>
AddSample(double current_ms,double current_value)413 void AggregatedMemoryHistogram<Histogram>::AddSample(double current_ms,
414                                                      double current_value) {
415   if (!is_initialized_) {
416     aggregate_value_ = current_value;
417     start_ms_ = current_ms;
418     last_value_ = current_value;
419     last_ms_ = current_ms;
420     is_initialized_ = true;
421   } else {
422     const double kEpsilon = 1e-6;
423     const int kMaxSamples = 1000;
424     if (current_ms < last_ms_ + kEpsilon) {
425       // Two samples have the same time, remember the last one.
426       last_value_ = current_value;
427     } else {
428       double sample_interval_ms = FLAG_histogram_interval;
429       double end_ms = start_ms_ + sample_interval_ms;
430       if (end_ms <= current_ms + kEpsilon) {
431         // Linearly interpolate between the last_ms_ and the current_ms.
432         double slope = (current_value - last_value_) / (current_ms - last_ms_);
433         int i;
434         // Send aggregated samples to the backing histogram from the start_ms
435         // to the current_ms.
436         for (i = 0; i < kMaxSamples && end_ms <= current_ms + kEpsilon; i++) {
437           double end_value = last_value_ + (end_ms - last_ms_) * slope;
438           double sample_value;
439           if (i == 0) {
440             // Take aggregate_value_ into account.
441             sample_value = Aggregate(end_ms, end_value);
442           } else {
443             // There is no aggregate_value_ for i > 0.
444             sample_value = (last_value_ + end_value) / 2;
445           }
446           backing_histogram_->AddSample(static_cast<int>(sample_value + 0.5));
447           last_value_ = end_value;
448           last_ms_ = end_ms;
449           end_ms += sample_interval_ms;
450         }
451         if (i == kMaxSamples) {
452           // We hit the sample limit, ignore the remaining samples.
453           aggregate_value_ = current_value;
454           start_ms_ = current_ms;
455         } else {
456           aggregate_value_ = last_value_;
457           start_ms_ = last_ms_;
458         }
459       }
460       aggregate_value_ = current_ms > start_ms_ + kEpsilon
461                              ? Aggregate(current_ms, current_value)
462                              : aggregate_value_;
463       last_value_ = current_value;
464       last_ms_ = current_ms;
465     }
466   }
467 }
468 
469 
470 template <typename Histogram>
Aggregate(double current_ms,double current_value)471 double AggregatedMemoryHistogram<Histogram>::Aggregate(double current_ms,
472                                                        double current_value) {
473   double interval_ms = current_ms - start_ms_;
474   double value = (current_value + last_value_) / 2;
475   // The aggregate_value_ is the average for [start_ms_; last_ms_].
476   // The value is the average for [last_ms_; current_ms].
477   // Return the weighted average of the aggregate_value_ and the value.
478   return aggregate_value_ * ((last_ms_ - start_ms_) / interval_ms) +
479          value * ((current_ms - last_ms_) / interval_ms);
480 }
481 
482 struct RuntimeCallCounter {
RuntimeCallCounterRuntimeCallCounter483   explicit RuntimeCallCounter(const char* name) : name(name) {}
484   void Reset();
485 
486   const char* name;
487   int64_t count = 0;
488   base::TimeDelta time;
489 };
490 
491 // RuntimeCallTimer is used to keep track of the stack of currently active
492 // timers used for properly measuring the own time of a RuntimeCallCounter.
493 class RuntimeCallTimer {
494  public:
RuntimeCallTimer()495   RuntimeCallTimer() {}
counter()496   RuntimeCallCounter* counter() { return counter_; }
timer()497   base::ElapsedTimer timer() { return timer_; }
498 
499  private:
500   friend class RuntimeCallStats;
501 
Start(RuntimeCallCounter * counter,RuntimeCallTimer * parent)502   inline void Start(RuntimeCallCounter* counter, RuntimeCallTimer* parent) {
503     counter_ = counter;
504     parent_ = parent;
505     timer_.Start();
506   }
507 
Stop()508   inline RuntimeCallTimer* Stop() {
509     base::TimeDelta delta = timer_.Elapsed();
510     timer_.Stop();
511     counter_->count++;
512     counter_->time += delta;
513     if (parent_ != NULL) {
514       // Adjust parent timer so that it does not include sub timer's time.
515       parent_->counter_->time -= delta;
516     }
517     return parent_;
518   }
519 
520   RuntimeCallCounter* counter_ = nullptr;
521   RuntimeCallTimer* parent_ = nullptr;
522   base::ElapsedTimer timer_;
523 };
524 
525 #define FOR_EACH_API_COUNTER(V)                            \
526   V(ArrayBuffer_Cast)                                      \
527   V(ArrayBuffer_Neuter)                                    \
528   V(ArrayBuffer_New)                                       \
529   V(Array_CloneElementAt)                                  \
530   V(Array_New)                                             \
531   V(BooleanObject_BooleanValue)                            \
532   V(BooleanObject_New)                                     \
533   V(Context_New)                                           \
534   V(DataView_New)                                          \
535   V(Date_DateTimeConfigurationChangeNotification)          \
536   V(Date_New)                                              \
537   V(Date_NumberValue)                                      \
538   V(Debug_Call)                                            \
539   V(Debug_GetMirror)                                       \
540   V(Error_New)                                             \
541   V(External_New)                                          \
542   V(Float32Array_New)                                      \
543   V(Float64Array_New)                                      \
544   V(Function_Call)                                         \
545   V(Function_New)                                          \
546   V(Function_NewInstance)                                  \
547   V(FunctionTemplate_GetFunction)                          \
548   V(FunctionTemplate_New)                                  \
549   V(FunctionTemplate_NewWithFastHandler)                   \
550   V(Int16Array_New)                                        \
551   V(Int32Array_New)                                        \
552   V(Int8Array_New)                                         \
553   V(JSON_Parse)                                            \
554   V(JSON_Stringify)                                        \
555   V(Map_AsArray)                                           \
556   V(Map_Clear)                                             \
557   V(Map_Delete)                                            \
558   V(Map_Get)                                               \
559   V(Map_Has)                                               \
560   V(Map_New)                                               \
561   V(Map_Set)                                               \
562   V(Message_GetEndColumn)                                  \
563   V(Message_GetLineNumber)                                 \
564   V(Message_GetSourceLine)                                 \
565   V(Message_GetStartColumn)                                \
566   V(NumberObject_New)                                      \
567   V(NumberObject_NumberValue)                              \
568   V(Object_CallAsConstructor)                              \
569   V(Object_CallAsFunction)                                 \
570   V(Object_CreateDataProperty)                             \
571   V(Object_DefineOwnProperty)                              \
572   V(Object_Delete)                                         \
573   V(Object_DeleteProperty)                                 \
574   V(Object_ForceSet)                                       \
575   V(Object_Get)                                            \
576   V(Object_GetOwnPropertyDescriptor)                       \
577   V(Object_GetOwnPropertyNames)                            \
578   V(Object_GetPropertyAttributes)                          \
579   V(Object_GetPropertyNames)                               \
580   V(Object_GetRealNamedProperty)                           \
581   V(Object_GetRealNamedPropertyAttributes)                 \
582   V(Object_GetRealNamedPropertyAttributesInPrototypeChain) \
583   V(Object_GetRealNamedPropertyInPrototypeChain)           \
584   V(Object_HasOwnProperty)                                 \
585   V(Object_HasRealIndexedProperty)                         \
586   V(Object_HasRealNamedCallbackProperty)                   \
587   V(Object_HasRealNamedProperty)                           \
588   V(Object_Int32Value)                                     \
589   V(Object_IntegerValue)                                   \
590   V(Object_New)                                            \
591   V(Object_NumberValue)                                    \
592   V(Object_ObjectProtoToString)                            \
593   V(Object_Set)                                            \
594   V(Object_SetAccessor)                                    \
595   V(Object_SetIntegrityLevel)                              \
596   V(Object_SetPrivate)                                     \
597   V(Object_SetPrototype)                                   \
598   V(ObjectTemplate_New)                                    \
599   V(ObjectTemplate_NewInstance)                            \
600   V(Object_ToArrayIndex)                                   \
601   V(Object_ToDetailString)                                 \
602   V(Object_ToInt32)                                        \
603   V(Object_ToInteger)                                      \
604   V(Object_ToNumber)                                       \
605   V(Object_ToObject)                                       \
606   V(Object_ToString)                                       \
607   V(Object_ToUint32)                                       \
608   V(Object_Uint32Value)                                    \
609   V(Persistent_New)                                        \
610   V(Private_New)                                           \
611   V(Promise_Catch)                                         \
612   V(Promise_Chain)                                         \
613   V(Promise_HasRejectHandler)                              \
614   V(Promise_Resolver_New)                                  \
615   V(Promise_Resolver_Resolve)                              \
616   V(Promise_Then)                                          \
617   V(Proxy_New)                                             \
618   V(RangeError_New)                                        \
619   V(ReferenceError_New)                                    \
620   V(RegExp_New)                                            \
621   V(ScriptCompiler_Compile)                                \
622   V(ScriptCompiler_CompileFunctionInContext)               \
623   V(ScriptCompiler_CompileUnbound)                         \
624   V(Script_Run)                                            \
625   V(Set_Add)                                               \
626   V(Set_AsArray)                                           \
627   V(Set_Clear)                                             \
628   V(Set_Delete)                                            \
629   V(Set_Has)                                               \
630   V(Set_New)                                               \
631   V(SharedArrayBuffer_New)                                 \
632   V(String_Concat)                                         \
633   V(String_NewExternalOneByte)                             \
634   V(String_NewExternalTwoByte)                             \
635   V(String_NewFromOneByte)                                 \
636   V(String_NewFromTwoByte)                                 \
637   V(String_NewFromUtf8)                                    \
638   V(StringObject_New)                                      \
639   V(StringObject_StringValue)                              \
640   V(String_Write)                                          \
641   V(String_WriteUtf8)                                      \
642   V(Symbol_New)                                            \
643   V(SymbolObject_New)                                      \
644   V(SymbolObject_SymbolValue)                              \
645   V(SyntaxError_New)                                       \
646   V(TryCatch_StackTrace)                                   \
647   V(TypeError_New)                                         \
648   V(Uint16Array_New)                                       \
649   V(Uint32Array_New)                                       \
650   V(Uint8Array_New)                                        \
651   V(Uint8ClampedArray_New)                                 \
652   V(UnboundScript_GetId)                                   \
653   V(UnboundScript_GetLineNumber)                           \
654   V(UnboundScript_GetName)                                 \
655   V(UnboundScript_GetSourceMappingURL)                     \
656   V(UnboundScript_GetSourceURL)                            \
657   V(Value_TypeOf)
658 
659 #define FOR_EACH_MANUAL_COUNTER(V)                  \
660   V(AccessorGetterCallback)                         \
661   V(AccessorNameGetterCallback)                     \
662   V(AccessorNameSetterCallback)                     \
663   V(Compile)                                        \
664   V(CompileCode)                                    \
665   V(CompileCodeLazy)                                \
666   V(CompileDeserialize)                             \
667   V(CompileEval)                                    \
668   V(CompileFullCode)                                \
669   V(CompileIgnition)                                \
670   V(CompileSerialize)                               \
671   V(DeoptimizeCode)                                 \
672   V(FunctionCallback)                               \
673   V(GC)                                             \
674   V(GenericNamedPropertyDeleterCallback)            \
675   V(GenericNamedPropertyQueryCallback)              \
676   V(GenericNamedPropertySetterCallback)             \
677   V(IndexedPropertyDeleterCallback)                 \
678   V(IndexedPropertyGetterCallback)                  \
679   V(IndexedPropertyQueryCallback)                   \
680   V(IndexedPropertySetterCallback)                  \
681   V(InvokeFunctionCallback)                         \
682   V(JS_Execution)                                   \
683   V(Map_SetPrototype)                               \
684   V(Map_TransitionToAccessorProperty)               \
685   V(Map_TransitionToDataProperty)                   \
686   V(Object_DeleteProperty)                          \
687   V(OptimizeCode)                                   \
688   V(Parse)                                          \
689   V(ParseLazy)                                      \
690   V(PropertyCallback)                               \
691   V(PrototypeMap_TransitionToAccessorProperty)      \
692   V(PrototypeMap_TransitionToDataProperty)          \
693   V(PrototypeObject_DeleteProperty)                 \
694   V(RecompileConcurrent)                            \
695   V(RecompileSynchronous)                           \
696   /* Dummy counter for the unexpected stub miss. */ \
697   V(UnexpectedStubMiss)
698 
699 #define FOR_EACH_HANDLER_COUNTER(V)             \
700   V(IC_HandlerCacheHit)                         \
701   V(KeyedLoadIC_LoadIndexedStringStub)          \
702   V(KeyedLoadIC_LoadIndexedInterceptorStub)     \
703   V(KeyedLoadIC_KeyedLoadSloppyArgumentsStub)   \
704   V(KeyedLoadIC_LoadFastElementStub)            \
705   V(KeyedLoadIC_LoadDictionaryElementStub)      \
706   V(KeyedLoadIC_PolymorphicElement)             \
707   V(KeyedStoreIC_KeyedStoreSloppyArgumentsStub) \
708   V(KeyedStoreIC_StoreFastElementStub)          \
709   V(KeyedStoreIC_StoreElementStub)              \
710   V(KeyedStoreIC_Polymorphic)                   \
711   V(LoadIC_FunctionPrototypeStub)               \
712   V(LoadIC_LoadApiGetterStub)                   \
713   V(LoadIC_LoadCallback)                        \
714   V(LoadIC_LoadConstant)                        \
715   V(LoadIC_LoadConstantStub)                    \
716   V(LoadIC_LoadField)                           \
717   V(LoadIC_LoadFieldStub)                       \
718   V(LoadIC_LoadGlobal)                          \
719   V(LoadIC_LoadInterceptor)                     \
720   V(LoadIC_LoadNonexistent)                     \
721   V(LoadIC_LoadNormal)                          \
722   V(LoadIC_LoadScriptContextFieldStub)          \
723   V(LoadIC_LoadViaGetter)                       \
724   V(LoadIC_SlowStub)                            \
725   V(LoadIC_StringLengthStub)                    \
726   V(StoreIC_SlowStub)                           \
727   V(StoreIC_StoreCallback)                      \
728   V(StoreIC_StoreField)                         \
729   V(StoreIC_StoreFieldStub)                     \
730   V(StoreIC_StoreGlobal)                        \
731   V(StoreIC_StoreGlobalTransition)              \
732   V(StoreIC_StoreInterceptorStub)               \
733   V(StoreIC_StoreNormal)                        \
734   V(StoreIC_StoreScriptContextFieldStub)        \
735   V(StoreIC_StoreTransition)                    \
736   V(StoreIC_StoreViaSetter)
737 
738 class RuntimeCallStats {
739  public:
740   typedef RuntimeCallCounter RuntimeCallStats::*CounterId;
741 
742 #define CALL_RUNTIME_COUNTER(name) \
743   RuntimeCallCounter name = RuntimeCallCounter(#name);
744   FOR_EACH_MANUAL_COUNTER(CALL_RUNTIME_COUNTER)
745 #undef CALL_RUNTIME_COUNTER
746 #define CALL_RUNTIME_COUNTER(name, nargs, ressize) \
747   RuntimeCallCounter Runtime_##name = RuntimeCallCounter(#name);
748   FOR_EACH_INTRINSIC(CALL_RUNTIME_COUNTER)
749 #undef CALL_RUNTIME_COUNTER
750 #define CALL_BUILTIN_COUNTER(name) \
751   RuntimeCallCounter Builtin_##name = RuntimeCallCounter(#name);
752   BUILTIN_LIST_C(CALL_BUILTIN_COUNTER)
753 #undef CALL_BUILTIN_COUNTER
754 #define CALL_BUILTIN_COUNTER(name) \
755   RuntimeCallCounter API_##name = RuntimeCallCounter("API_" #name);
756   FOR_EACH_API_COUNTER(CALL_BUILTIN_COUNTER)
757 #undef CALL_BUILTIN_COUNTER
758 #define CALL_BUILTIN_COUNTER(name) \
759   RuntimeCallCounter Handler_##name = RuntimeCallCounter(#name);
760   FOR_EACH_HANDLER_COUNTER(CALL_BUILTIN_COUNTER)
761 #undef CALL_BUILTIN_COUNTER
762 
763   // Starting measuring the time for a function. This will establish the
764   // connection to the parent counter for properly calculating the own times.
765   static void Enter(Isolate* isolate, RuntimeCallTimer* timer,
766                     CounterId counter_id);
767 
768   // Leave a scope for a measured runtime function. This will properly add
769   // the time delta to the current_counter and subtract the delta from its
770   // parent.
771   static void Leave(Isolate* isolate, RuntimeCallTimer* timer);
772 
773   // Set counter id for the innermost measurement. It can be used to refine
774   // event kind when a runtime entry counter is too generic.
775   static void CorrectCurrentCounterId(Isolate* isolate, CounterId counter_id);
776 
777   void Reset();
778   void Print(std::ostream& os);
779 
RuntimeCallStats()780   RuntimeCallStats() { Reset(); }
current_timer()781   RuntimeCallTimer* current_timer() { return current_timer_; }
782 
783  private:
784   // Counter to track recursive time events.
785   RuntimeCallTimer* current_timer_ = NULL;
786 };
787 
788 #define TRACE_RUNTIME_CALL_STATS(isolate, counter_name) \
789   do {                                                  \
790     if (FLAG_runtime_call_stats) {                      \
791       RuntimeCallStats::CorrectCurrentCounterId(        \
792           isolate, &RuntimeCallStats::counter_name);    \
793     }                                                   \
794   } while (false)
795 
796 #define TRACE_HANDLER_STATS(isolate, counter_name) \
797   TRACE_RUNTIME_CALL_STATS(isolate, Handler_##counter_name)
798 
799 // A RuntimeCallTimerScopes wraps around a RuntimeCallTimer to measure the
800 // the time of C++ scope.
801 class RuntimeCallTimerScope {
802  public:
RuntimeCallTimerScope(Isolate * isolate,RuntimeCallStats::CounterId counter_id)803   inline RuntimeCallTimerScope(Isolate* isolate,
804                                RuntimeCallStats::CounterId counter_id) {
805     if (V8_UNLIKELY(FLAG_runtime_call_stats)) {
806       isolate_ = isolate;
807       RuntimeCallStats::Enter(isolate_, &timer_, counter_id);
808     }
809   }
810   // This constructor is here just to avoid calling GetIsolate() when the
811   // stats are disabled and the isolate is not directly available.
812   inline RuntimeCallTimerScope(HeapObject* heap_object,
813                                RuntimeCallStats::CounterId counter_id);
814 
~RuntimeCallTimerScope()815   inline ~RuntimeCallTimerScope() {
816     if (V8_UNLIKELY(FLAG_runtime_call_stats)) {
817       RuntimeCallStats::Leave(isolate_, &timer_);
818     }
819   }
820 
821  private:
822   Isolate* isolate_;
823   RuntimeCallTimer timer_;
824 };
825 
826 #define HISTOGRAM_RANGE_LIST(HR)                                              \
827   /* Generic range histograms */                                              \
828   HR(detached_context_age_in_gc, V8.DetachedContextAgeInGC, 0, 20, 21)        \
829   HR(gc_idle_time_allotted_in_ms, V8.GCIdleTimeAllottedInMS, 0, 10000, 101)   \
830   HR(gc_idle_time_limit_overshot, V8.GCIdleTimeLimit.Overshot, 0, 10000, 101) \
831   HR(gc_idle_time_limit_undershot, V8.GCIdleTimeLimit.Undershot, 0, 10000,    \
832      101)                                                                     \
833   HR(code_cache_reject_reason, V8.CodeCacheRejectReason, 1, 6, 6)             \
834   HR(errors_thrown_per_context, V8.ErrorsThrownPerContext, 0, 200, 20)        \
835   HR(debug_feature_usage, V8.DebugFeatureUsage, 1, 7, 7)                      \
836   /* Asm/Wasm. */                                                             \
837   HR(wasm_functions_per_module, V8.WasmFunctionsPerModule, 1, 10000, 51)
838 
839 #define HISTOGRAM_TIMER_LIST(HT)                                               \
840   /* Garbage collection timers. */                                             \
841   HT(gc_compactor, V8.GCCompactor, 10000, MILLISECOND)                         \
842   HT(gc_finalize, V8.GCFinalizeMC, 10000, MILLISECOND)                         \
843   HT(gc_finalize_reduce_memory, V8.GCFinalizeMCReduceMemory, 10000,            \
844      MILLISECOND)                                                              \
845   HT(gc_scavenger, V8.GCScavenger, 10000, MILLISECOND)                         \
846   HT(gc_context, V8.GCContext, 10000,                                          \
847      MILLISECOND) /* GC context cleanup time */                                \
848   HT(gc_idle_notification, V8.GCIdleNotification, 10000, MILLISECOND)          \
849   HT(gc_incremental_marking, V8.GCIncrementalMarking, 10000, MILLISECOND)      \
850   HT(gc_incremental_marking_start, V8.GCIncrementalMarkingStart, 10000,        \
851      MILLISECOND)                                                              \
852   HT(gc_incremental_marking_finalize, V8.GCIncrementalMarkingFinalize, 10000,  \
853      MILLISECOND)                                                              \
854   HT(gc_low_memory_notification, V8.GCLowMemoryNotification, 10000,            \
855      MILLISECOND)                                                              \
856   /* Parsing timers. */                                                        \
857   HT(parse, V8.ParseMicroSeconds, 1000000, MICROSECOND)                        \
858   HT(parse_lazy, V8.ParseLazyMicroSeconds, 1000000, MICROSECOND)               \
859   HT(pre_parse, V8.PreParseMicroSeconds, 1000000, MICROSECOND)                 \
860   /* Compilation times. */                                                     \
861   HT(compile, V8.CompileMicroSeconds, 1000000, MICROSECOND)                    \
862   HT(compile_eval, V8.CompileEvalMicroSeconds, 1000000, MICROSECOND)           \
863   /* Serialization as part of compilation (code caching) */                    \
864   HT(compile_serialize, V8.CompileSerializeMicroSeconds, 100000, MICROSECOND)  \
865   HT(compile_deserialize, V8.CompileDeserializeMicroSeconds, 1000000,          \
866      MICROSECOND)                                                              \
867   /* Total compilation time incl. caching/parsing */                           \
868   HT(compile_script, V8.CompileScriptMicroSeconds, 1000000, MICROSECOND)       \
869   /* Total JavaScript execution time (including callbacks and runtime calls */ \
870   HT(execute, V8.Execute, 1000000, MICROSECOND)                                \
871   /* Asm/Wasm */                                                               \
872   HT(wasm_instantiate_module_time, V8.WasmInstantiateModuleMicroSeconds,       \
873      1000000, MICROSECOND)                                                     \
874   HT(wasm_decode_module_time, V8.WasmDecodeModuleMicroSeconds, 1000000,        \
875      MICROSECOND)                                                              \
876   HT(wasm_decode_function_time, V8.WasmDecodeFunctionMicroSeconds, 1000000,    \
877      MICROSECOND)                                                              \
878   HT(wasm_compile_module_time, V8.WasmCompileModuleMicroSeconds, 1000000,      \
879      MICROSECOND)                                                              \
880   HT(wasm_compile_function_time, V8.WasmCompileFunctionMicroSeconds, 1000000,  \
881      MICROSECOND)
882 
883 #define AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT) \
884   AHT(compile_lazy, V8.CompileLazyMicroSeconds)
885 
886 
887 #define HISTOGRAM_PERCENTAGE_LIST(HP)                                          \
888   /* Heap fragmentation. */                                                    \
889   HP(external_fragmentation_total, V8.MemoryExternalFragmentationTotal)        \
890   HP(external_fragmentation_old_space, V8.MemoryExternalFragmentationOldSpace) \
891   HP(external_fragmentation_code_space,                                        \
892      V8.MemoryExternalFragmentationCodeSpace)                                  \
893   HP(external_fragmentation_map_space, V8.MemoryExternalFragmentationMapSpace) \
894   HP(external_fragmentation_lo_space, V8.MemoryExternalFragmentationLoSpace)   \
895   /* Percentages of heap committed to each space. */                           \
896   HP(heap_fraction_new_space, V8.MemoryHeapFractionNewSpace)                   \
897   HP(heap_fraction_old_space, V8.MemoryHeapFractionOldSpace)                   \
898   HP(heap_fraction_code_space, V8.MemoryHeapFractionCodeSpace)                 \
899   HP(heap_fraction_map_space, V8.MemoryHeapFractionMapSpace)                   \
900   HP(heap_fraction_lo_space, V8.MemoryHeapFractionLoSpace)                     \
901   /* Percentage of crankshafted codegen. */                                    \
902   HP(codegen_fraction_crankshaft, V8.CodegenFractionCrankshaft)
903 
904 
905 #define HISTOGRAM_LEGACY_MEMORY_LIST(HM)                                      \
906   HM(heap_sample_total_committed, V8.MemoryHeapSampleTotalCommitted)          \
907   HM(heap_sample_total_used, V8.MemoryHeapSampleTotalUsed)                    \
908   HM(heap_sample_map_space_committed, V8.MemoryHeapSampleMapSpaceCommitted)   \
909   HM(heap_sample_code_space_committed, V8.MemoryHeapSampleCodeSpaceCommitted) \
910   HM(heap_sample_maximum_committed, V8.MemoryHeapSampleMaximumCommitted)
911 
912 #define HISTOGRAM_MEMORY_LIST(HM)                                              \
913   HM(memory_heap_committed, V8.MemoryHeapCommitted)                            \
914   HM(memory_heap_used, V8.MemoryHeapUsed)                                      \
915   /* Asm/Wasm */                                                               \
916   HM(wasm_decode_module_peak_memory_bytes, V8.WasmDecodeModulePeakMemoryBytes) \
917   HM(wasm_compile_function_peak_memory_bytes,                                  \
918      V8.WasmCompileFunctionPeakMemoryBytes)                                    \
919   HM(wasm_min_mem_pages_count, V8.WasmMinMemPagesCount)                        \
920   HM(wasm_max_mem_pages_count, V8.WasmMaxMemPagesCount)                        \
921   HM(wasm_function_size_bytes, V8.WasmFunctionSizeBytes)                       \
922   HM(wasm_module_size_bytes, V8.WasmModuleSizeBytes)
923 
924 // WARNING: STATS_COUNTER_LIST_* is a very large macro that is causing MSVC
925 // Intellisense to crash.  It was broken into two macros (each of length 40
926 // lines) rather than one macro (of length about 80 lines) to work around
927 // this problem.  Please avoid using recursive macros of this length when
928 // possible.
929 #define STATS_COUNTER_LIST_1(SC)                                      \
930   /* Global Handle Count*/                                            \
931   SC(global_handles, V8.GlobalHandles)                                \
932   /* OS Memory allocated */                                           \
933   SC(memory_allocated, V8.OsMemoryAllocated)                          \
934   SC(maps_normalized, V8.MapsNormalized)                            \
935   SC(maps_created, V8.MapsCreated)                                  \
936   SC(elements_transitions, V8.ObjectElementsTransitions)            \
937   SC(props_to_dictionary, V8.ObjectPropertiesToDictionary)            \
938   SC(elements_to_dictionary, V8.ObjectElementsToDictionary)           \
939   SC(alive_after_last_gc, V8.AliveAfterLastGC)                        \
940   SC(objs_since_last_young, V8.ObjsSinceLastYoung)                    \
941   SC(objs_since_last_full, V8.ObjsSinceLastFull)                      \
942   SC(string_table_capacity, V8.StringTableCapacity)                   \
943   SC(number_of_symbols, V8.NumberOfSymbols)                           \
944   SC(script_wrappers, V8.ScriptWrappers)                              \
945   SC(inlined_copied_elements, V8.InlinedCopiedElements)               \
946   SC(arguments_adaptors, V8.ArgumentsAdaptors)                        \
947   SC(compilation_cache_hits, V8.CompilationCacheHits)                 \
948   SC(compilation_cache_misses, V8.CompilationCacheMisses)             \
949   /* Amount of evaled source code. */                                 \
950   SC(total_eval_size, V8.TotalEvalSize)                               \
951   /* Amount of loaded source code. */                                 \
952   SC(total_load_size, V8.TotalLoadSize)                               \
953   /* Amount of parsed source code. */                                 \
954   SC(total_parse_size, V8.TotalParseSize)                             \
955   /* Amount of source code skipped over using preparsing. */          \
956   SC(total_preparse_skipped, V8.TotalPreparseSkipped)                 \
957   /* Amount of compiled source code. */                               \
958   SC(total_compile_size, V8.TotalCompileSize)                         \
959   /* Amount of source code compiled with the full codegen. */         \
960   SC(total_full_codegen_source_size, V8.TotalFullCodegenSourceSize)   \
961   /* Number of contexts created from scratch. */                      \
962   SC(contexts_created_from_scratch, V8.ContextsCreatedFromScratch)    \
963   /* Number of contexts created by partial snapshot. */               \
964   SC(contexts_created_by_snapshot, V8.ContextsCreatedBySnapshot)      \
965   /* Number of code objects found from pc. */                         \
966   SC(pc_to_code, V8.PcToCode)                                         \
967   SC(pc_to_code_cached, V8.PcToCodeCached)                            \
968   /* The store-buffer implementation of the write barrier. */         \
969   SC(store_buffer_overflows, V8.StoreBufferOverflows)
970 
971 #define STATS_COUNTER_LIST_2(SC)                                               \
972   /* Number of code stubs. */                                                  \
973   SC(code_stubs, V8.CodeStubs)                                                 \
974   /* Amount of stub code. */                                                   \
975   SC(total_stubs_code_size, V8.TotalStubsCodeSize)                             \
976   /* Amount of (JS) compiled code. */                                          \
977   SC(total_compiled_code_size, V8.TotalCompiledCodeSize)                       \
978   SC(gc_compactor_caused_by_request, V8.GCCompactorCausedByRequest)            \
979   SC(gc_compactor_caused_by_promoted_data, V8.GCCompactorCausedByPromotedData) \
980   SC(gc_compactor_caused_by_oldspace_exhaustion,                               \
981      V8.GCCompactorCausedByOldspaceExhaustion)                                 \
982   SC(gc_last_resort_from_js, V8.GCLastResortFromJS)                            \
983   SC(gc_last_resort_from_handles, V8.GCLastResortFromHandles)                  \
984   SC(ic_keyed_load_generic_smi, V8.ICKeyedLoadGenericSmi)                      \
985   SC(ic_keyed_load_generic_symbol, V8.ICKeyedLoadGenericSymbol)                \
986   SC(ic_keyed_load_generic_slow, V8.ICKeyedLoadGenericSlow)                    \
987   SC(ic_named_load_global_stub, V8.ICNamedLoadGlobalStub)                      \
988   SC(ic_store_normal_miss, V8.ICStoreNormalMiss)                               \
989   SC(ic_store_normal_hit, V8.ICStoreNormalHit)                                 \
990   SC(ic_binary_op_miss, V8.ICBinaryOpMiss)                                     \
991   SC(ic_compare_miss, V8.ICCompareMiss)                                        \
992   SC(ic_call_miss, V8.ICCallMiss)                                              \
993   SC(ic_keyed_call_miss, V8.ICKeyedCallMiss)                                   \
994   SC(ic_load_miss, V8.ICLoadMiss)                                              \
995   SC(ic_keyed_load_miss, V8.ICKeyedLoadMiss)                                   \
996   SC(ic_store_miss, V8.ICStoreMiss)                                            \
997   SC(ic_keyed_store_miss, V8.ICKeyedStoreMiss)                                 \
998   SC(cow_arrays_created_runtime, V8.COWArraysCreatedRuntime)                   \
999   SC(cow_arrays_converted, V8.COWArraysConverted)                              \
1000   SC(constructed_objects, V8.ConstructedObjects)                               \
1001   SC(constructed_objects_runtime, V8.ConstructedObjectsRuntime)                \
1002   SC(negative_lookups, V8.NegativeLookups)                                     \
1003   SC(negative_lookups_miss, V8.NegativeLookupsMiss)                            \
1004   SC(megamorphic_stub_cache_probes, V8.MegamorphicStubCacheProbes)             \
1005   SC(megamorphic_stub_cache_misses, V8.MegamorphicStubCacheMisses)             \
1006   SC(megamorphic_stub_cache_updates, V8.MegamorphicStubCacheUpdates)           \
1007   SC(enum_cache_hits, V8.EnumCacheHits)                                        \
1008   SC(enum_cache_misses, V8.EnumCacheMisses)                                    \
1009   SC(fast_new_closure_total, V8.FastNewClosureTotal)                           \
1010   SC(string_add_runtime, V8.StringAddRuntime)                                  \
1011   SC(string_add_native, V8.StringAddNative)                                    \
1012   SC(string_add_runtime_ext_to_one_byte, V8.StringAddRuntimeExtToOneByte)      \
1013   SC(sub_string_runtime, V8.SubStringRuntime)                                  \
1014   SC(sub_string_native, V8.SubStringNative)                                    \
1015   SC(string_compare_native, V8.StringCompareNative)                            \
1016   SC(string_compare_runtime, V8.StringCompareRuntime)                          \
1017   SC(regexp_entry_runtime, V8.RegExpEntryRuntime)                              \
1018   SC(regexp_entry_native, V8.RegExpEntryNative)                                \
1019   SC(number_to_string_native, V8.NumberToStringNative)                         \
1020   SC(number_to_string_runtime, V8.NumberToStringRuntime)                       \
1021   SC(math_exp_runtime, V8.MathExpRuntime)                                      \
1022   SC(math_log_runtime, V8.MathLogRuntime)                                      \
1023   SC(math_pow_runtime, V8.MathPowRuntime)                                      \
1024   SC(stack_interrupts, V8.StackInterrupts)                                     \
1025   SC(runtime_profiler_ticks, V8.RuntimeProfilerTicks)                          \
1026   SC(runtime_calls, V8.RuntimeCalls)                                           \
1027   SC(bounds_checks_eliminated, V8.BoundsChecksEliminated)                      \
1028   SC(bounds_checks_hoisted, V8.BoundsChecksHoisted)                            \
1029   SC(soft_deopts_requested, V8.SoftDeoptsRequested)                            \
1030   SC(soft_deopts_inserted, V8.SoftDeoptsInserted)                              \
1031   SC(soft_deopts_executed, V8.SoftDeoptsExecuted)                              \
1032   /* Number of write barriers in generated code. */                            \
1033   SC(write_barriers_dynamic, V8.WriteBarriersDynamic)                          \
1034   SC(write_barriers_static, V8.WriteBarriersStatic)                            \
1035   SC(new_space_bytes_available, V8.MemoryNewSpaceBytesAvailable)               \
1036   SC(new_space_bytes_committed, V8.MemoryNewSpaceBytesCommitted)               \
1037   SC(new_space_bytes_used, V8.MemoryNewSpaceBytesUsed)                         \
1038   SC(old_space_bytes_available, V8.MemoryOldSpaceBytesAvailable)               \
1039   SC(old_space_bytes_committed, V8.MemoryOldSpaceBytesCommitted)               \
1040   SC(old_space_bytes_used, V8.MemoryOldSpaceBytesUsed)                         \
1041   SC(code_space_bytes_available, V8.MemoryCodeSpaceBytesAvailable)             \
1042   SC(code_space_bytes_committed, V8.MemoryCodeSpaceBytesCommitted)             \
1043   SC(code_space_bytes_used, V8.MemoryCodeSpaceBytesUsed)                       \
1044   SC(map_space_bytes_available, V8.MemoryMapSpaceBytesAvailable)               \
1045   SC(map_space_bytes_committed, V8.MemoryMapSpaceBytesCommitted)               \
1046   SC(map_space_bytes_used, V8.MemoryMapSpaceBytesUsed)                         \
1047   SC(lo_space_bytes_available, V8.MemoryLoSpaceBytesAvailable)                 \
1048   SC(lo_space_bytes_committed, V8.MemoryLoSpaceBytesCommitted)                 \
1049   SC(lo_space_bytes_used, V8.MemoryLoSpaceBytesUsed)                           \
1050   SC(turbo_escape_allocs_replaced, V8.TurboEscapeAllocsReplaced)               \
1051   SC(crankshaft_escape_allocs_replaced, V8.CrankshaftEscapeAllocsReplaced)     \
1052   SC(turbo_escape_loads_replaced, V8.TurboEscapeLoadsReplaced)                 \
1053   SC(crankshaft_escape_loads_replaced, V8.CrankshaftEscapeLoadsReplaced)       \
1054   /* Total code size (including metadata) of baseline code or bytecode. */     \
1055   SC(total_baseline_code_size, V8.TotalBaselineCodeSize)                       \
1056   /* Total count of functions compiled using the baseline compiler. */         \
1057   SC(total_baseline_compile_count, V8.TotalBaselineCompileCount)
1058 
1059 // This file contains all the v8 counters that are in use.
1060 class Counters {
1061  public:
1062 #define HR(name, caption, min, max, num_buckets) \
1063   Histogram* name() { return &name##_; }
1064   HISTOGRAM_RANGE_LIST(HR)
1065 #undef HR
1066 
1067 #define HT(name, caption, max, res) \
1068   HistogramTimer* name() { return &name##_; }
1069   HISTOGRAM_TIMER_LIST(HT)
1070 #undef HT
1071 
1072 #define AHT(name, caption) \
1073   AggregatableHistogramTimer* name() { return &name##_; }
1074   AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT)
1075 #undef AHT
1076 
1077 #define HP(name, caption) \
1078   Histogram* name() { return &name##_; }
1079   HISTOGRAM_PERCENTAGE_LIST(HP)
1080 #undef HP
1081 
1082 #define HM(name, caption) \
1083   Histogram* name() { return &name##_; }
1084   HISTOGRAM_LEGACY_MEMORY_LIST(HM)
1085   HISTOGRAM_MEMORY_LIST(HM)
1086 #undef HM
1087 
1088 #define HM(name, caption)                                     \
1089   AggregatedMemoryHistogram<Histogram>* aggregated_##name() { \
1090     return &aggregated_##name##_;                             \
1091   }
1092   HISTOGRAM_MEMORY_LIST(HM)
1093 #undef HM
1094 
1095 #define SC(name, caption) \
1096   StatsCounter* name() { return &name##_; }
1097   STATS_COUNTER_LIST_1(SC)
1098   STATS_COUNTER_LIST_2(SC)
1099 #undef SC
1100 
1101 #define SC(name) \
1102   StatsCounter* count_of_##name() { return &count_of_##name##_; } \
1103   StatsCounter* size_of_##name() { return &size_of_##name##_; }
1104   INSTANCE_TYPE_LIST(SC)
1105 #undef SC
1106 
1107 #define SC(name) \
1108   StatsCounter* count_of_CODE_TYPE_##name() \
1109     { return &count_of_CODE_TYPE_##name##_; } \
1110   StatsCounter* size_of_CODE_TYPE_##name() \
1111     { return &size_of_CODE_TYPE_##name##_; }
1112   CODE_KIND_LIST(SC)
1113 #undef SC
1114 
1115 #define SC(name) \
1116   StatsCounter* count_of_FIXED_ARRAY_##name() \
1117     { return &count_of_FIXED_ARRAY_##name##_; } \
1118   StatsCounter* size_of_FIXED_ARRAY_##name() \
1119     { return &size_of_FIXED_ARRAY_##name##_; }
1120   FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(SC)
1121 #undef SC
1122 
1123 #define SC(name) \
1124   StatsCounter* count_of_CODE_AGE_##name() \
1125     { return &count_of_CODE_AGE_##name##_; } \
1126   StatsCounter* size_of_CODE_AGE_##name() \
1127     { return &size_of_CODE_AGE_##name##_; }
1128   CODE_AGE_LIST_COMPLETE(SC)
1129 #undef SC
1130 
1131   enum Id {
1132 #define RATE_ID(name, caption, max, res) k_##name,
1133     HISTOGRAM_TIMER_LIST(RATE_ID)
1134 #undef RATE_ID
1135 #define AGGREGATABLE_ID(name, caption) k_##name,
1136     AGGREGATABLE_HISTOGRAM_TIMER_LIST(AGGREGATABLE_ID)
1137 #undef AGGREGATABLE_ID
1138 #define PERCENTAGE_ID(name, caption) k_##name,
1139     HISTOGRAM_PERCENTAGE_LIST(PERCENTAGE_ID)
1140 #undef PERCENTAGE_ID
1141 #define MEMORY_ID(name, caption) k_##name,
1142     HISTOGRAM_LEGACY_MEMORY_LIST(MEMORY_ID)
1143     HISTOGRAM_MEMORY_LIST(MEMORY_ID)
1144 #undef MEMORY_ID
1145 #define COUNTER_ID(name, caption) k_##name,
1146     STATS_COUNTER_LIST_1(COUNTER_ID)
1147     STATS_COUNTER_LIST_2(COUNTER_ID)
1148 #undef COUNTER_ID
1149 #define COUNTER_ID(name) kCountOf##name, kSizeOf##name,
1150     INSTANCE_TYPE_LIST(COUNTER_ID)
1151 #undef COUNTER_ID
1152 #define COUNTER_ID(name) kCountOfCODE_TYPE_##name, \
1153     kSizeOfCODE_TYPE_##name,
1154     CODE_KIND_LIST(COUNTER_ID)
1155 #undef COUNTER_ID
1156 #define COUNTER_ID(name) kCountOfFIXED_ARRAY__##name, \
1157     kSizeOfFIXED_ARRAY__##name,
1158     FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(COUNTER_ID)
1159 #undef COUNTER_ID
1160 #define COUNTER_ID(name) kCountOfCODE_AGE__##name, \
1161     kSizeOfCODE_AGE__##name,
1162     CODE_AGE_LIST_COMPLETE(COUNTER_ID)
1163 #undef COUNTER_ID
1164     stats_counter_count
1165   };
1166 
1167   void ResetCounters();
1168   void ResetHistograms();
runtime_call_stats()1169   RuntimeCallStats* runtime_call_stats() { return &runtime_call_stats_; }
1170 
1171  private:
1172 #define HR(name, caption, min, max, num_buckets) Histogram name##_;
1173   HISTOGRAM_RANGE_LIST(HR)
1174 #undef HR
1175 
1176 #define HT(name, caption, max, res) HistogramTimer name##_;
1177   HISTOGRAM_TIMER_LIST(HT)
1178 #undef HT
1179 
1180 #define AHT(name, caption) \
1181   AggregatableHistogramTimer name##_;
1182   AGGREGATABLE_HISTOGRAM_TIMER_LIST(AHT)
1183 #undef AHT
1184 
1185 #define HP(name, caption) \
1186   Histogram name##_;
1187   HISTOGRAM_PERCENTAGE_LIST(HP)
1188 #undef HP
1189 
1190 #define HM(name, caption) \
1191   Histogram name##_;
1192   HISTOGRAM_LEGACY_MEMORY_LIST(HM)
1193   HISTOGRAM_MEMORY_LIST(HM)
1194 #undef HM
1195 
1196 #define HM(name, caption) \
1197   AggregatedMemoryHistogram<Histogram> aggregated_##name##_;
1198   HISTOGRAM_MEMORY_LIST(HM)
1199 #undef HM
1200 
1201 #define SC(name, caption) \
1202   StatsCounter name##_;
1203   STATS_COUNTER_LIST_1(SC)
1204   STATS_COUNTER_LIST_2(SC)
1205 #undef SC
1206 
1207 #define SC(name) \
1208   StatsCounter size_of_##name##_; \
1209   StatsCounter count_of_##name##_;
1210   INSTANCE_TYPE_LIST(SC)
1211 #undef SC
1212 
1213 #define SC(name) \
1214   StatsCounter size_of_CODE_TYPE_##name##_; \
1215   StatsCounter count_of_CODE_TYPE_##name##_;
1216   CODE_KIND_LIST(SC)
1217 #undef SC
1218 
1219 #define SC(name) \
1220   StatsCounter size_of_FIXED_ARRAY_##name##_; \
1221   StatsCounter count_of_FIXED_ARRAY_##name##_;
1222   FIXED_ARRAY_SUB_INSTANCE_TYPE_LIST(SC)
1223 #undef SC
1224 
1225 #define SC(name) \
1226   StatsCounter size_of_CODE_AGE_##name##_; \
1227   StatsCounter count_of_CODE_AGE_##name##_;
1228   CODE_AGE_LIST_COMPLETE(SC)
1229 #undef SC
1230 
1231   RuntimeCallStats runtime_call_stats_;
1232 
1233   friend class Isolate;
1234 
1235   explicit Counters(Isolate* isolate);
1236 
1237   DISALLOW_IMPLICIT_CONSTRUCTORS(Counters);
1238 };
1239 
1240 }  // namespace internal
1241 }  // namespace v8
1242 
1243 #endif  // V8_COUNTERS_H_
1244