test-cpu-profiler.cc 125 KB
Newer Older
1
// Copyright 2010 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 28 29
//
// Tests of profiles generator and utilities.

30 31 32
#include <limits>
#include <memory>

33
#include "src/init/v8.h"
34 35

#include "include/v8-profiler.h"
36
#include "src/api/api-inl.h"
37
#include "src/base/platform/platform.h"
38
#include "src/codegen/source-position-table.h"
39
#include "src/deoptimizer/deoptimizer.h"
40
#include "src/libplatform/default-platform.h"
41
#include "src/logging/log.h"
42
#include "src/objects/objects-inl.h"
43
#include "src/profiler/cpu-profiler-inl.h"
lpy's avatar
lpy committed
44
#include "src/profiler/profiler-listener.h"
45
#include "src/profiler/tracing-cpu-profiler.h"
46
#include "src/utils/utils.h"
47 48
#include "test/cctest/cctest.h"
#include "test/cctest/profiler-extension.h"
49

50
#include "include/libplatform/v8-tracing.h"
51
#include "src/libplatform/tracing/trace-event-listener.h"
52 53
#include "src/tracing/trace-event.h"

54 55 56 57 58
#ifdef V8_USE_PERFETTO
#include "perfetto/trace/chrome/chrome_trace_event.pb.h"
#include "perfetto/trace/trace.pb.h"
#endif

59 60 61
namespace v8 {
namespace internal {
namespace test_cpu_profiler {
62

63
// Helper methods
64 65 66 67
static v8::Local<v8::Function> GetFunction(v8::Local<v8::Context> env,
                                           const char* name) {
  return v8::Local<v8::Function>::Cast(
      env->Global()->Get(env, v8_str(name)).ToLocalChecked());
68 69
}

70 71 72 73
static size_t offset(const char* src, const char* substring) {
  const char* it = strstr(src, substring);
  CHECK(it);
  return static_cast<size_t>(it - src);
74 75
}

76 77 78 79 80
template <typename A, typename B>
static int dist(A a, B b) {
  return abs(static_cast<int>(a) - static_cast<int>(b));
}

81 82
static const char* reason(const i::DeoptimizeReason reason) {
  return i::DeoptimizeReasonToString(reason);
loislo's avatar
loislo committed
83 84
}

85
TEST(StartStop) {
86 87
  i::Isolate* isolate = CcTest::i_isolate();
  CpuProfilesCollection profiles(isolate);
88 89
  ProfilerCodeObserver code_observer(isolate);
  ProfileGenerator generator(&profiles, code_observer.code_map());
90
  std::unique_ptr<ProfilerEventsProcessor> processor(
91
      new SamplingEventsProcessor(isolate, &generator, &code_observer,
92 93
                                  v8::base::TimeDelta::FromMicroseconds(100),
                                  true));
94
  CHECK(processor->Start());
95
  processor->StopSynchronously();
96 97
}

98 99
static void EnqueueTickSampleEvent(ProfilerEventsProcessor* proc,
                                   i::Address frame1,
100 101
                                   i::Address frame2 = kNullAddress,
                                   i::Address frame3 = kNullAddress) {
102 103 104 105
  v8::internal::TickSample sample;
  sample.pc = reinterpret_cast<void*>(frame1);
  sample.tos = reinterpret_cast<void*>(frame1);
  sample.frames_count = 0;
106
  if (frame2 != kNullAddress) {
107 108
    sample.stack[0] = reinterpret_cast<void*>(frame2);
    sample.frames_count = 1;
109
  }
110
  if (frame3 != kNullAddress) {
111 112
    sample.stack[1] = reinterpret_cast<void*>(frame3);
    sample.frames_count = 2;
113
  }
114 115
  sample.timestamp = base::TimeTicks::HighResolutionNow();
  proc->AddSample(sample);
116 117
}

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
namespace {

class TestSetup {
 public:
  TestSetup()
      : old_flag_prof_browser_mode_(i::FLAG_prof_browser_mode) {
    i::FLAG_prof_browser_mode = false;
  }

  ~TestSetup() {
    i::FLAG_prof_browser_mode = old_flag_prof_browser_mode_;
  }

 private:
  bool old_flag_prof_browser_mode_;
};

}  // namespace

137
i::AbstractCode CreateCode(LocalContext* env) {
138 139 140 141
  static int counter = 0;
  i::EmbeddedVector<char, 256> script;
  i::EmbeddedVector<char, 32> name;

142
  i::SNPrintF(name, "function_%d", ++counter);
143
  const char* name_start = name.begin();
144
  i::SNPrintF(script,
145 146 147 148 149 150
      "function %s() {\n"
           "var counter = 0;\n"
           "for (var i = 0; i < %d; ++i) counter += i;\n"
           "return '%s_' + counter;\n"
       "}\n"
       "%s();\n", name_start, counter, name_start, name_start);
151
  CompileRun(script.begin());
152

153
  i::Handle<i::JSFunction> fun = i::Handle<i::JSFunction>::cast(
154
      v8::Utils::OpenHandle(*GetFunction(env->local(), name_start)));
155
  return fun->abstract_code();
156 157
}

158
TEST(CodeEvents) {
159
  CcTest::InitializeVM();
160
  LocalContext env;
161
  i::Isolate* isolate = CcTest::i_isolate();
162
  i::Factory* factory = isolate->factory();
163
  TestSetup test_setup;
164 165 166

  i::HandleScope scope(isolate);

167 168 169 170
  i::AbstractCode aaa_code = CreateCode(&env);
  i::AbstractCode comment_code = CreateCode(&env);
  i::AbstractCode comment2_code = CreateCode(&env);
  i::AbstractCode moved_code = CreateCode(&env);
171

172
  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
173 174 175
  ProfilerCodeObserver code_observer(isolate);
  ProfileGenerator* generator =
      new ProfileGenerator(profiles, code_observer.code_map());
176
  ProfilerEventsProcessor* processor = new SamplingEventsProcessor(
177 178
      isolate, generator, &code_observer,
      v8::base::TimeDelta::FromMicroseconds(100), true);
179
  CHECK(processor->Start());
180
  ProfilerListener profiler_listener(isolate, processor);
181
  isolate->logger()->AddCodeEventListener(&profiler_listener);
182 183 184

  // Enqueue code creation events.
  const char* aaa_str = "aaa";
185
  i::Handle<i::String> aaa_name = factory->NewStringFromAsciiChecked(aaa_str);
lpy's avatar
lpy committed
186 187 188 189 190 191
  profiler_listener.CodeCreateEvent(i::Logger::FUNCTION_TAG, aaa_code,
                                    *aaa_name);
  profiler_listener.CodeCreateEvent(i::Logger::BUILTIN_TAG, comment_code,
                                    "comment");
  profiler_listener.CodeCreateEvent(i::Logger::BUILTIN_TAG, comment2_code,
                                    "comment2");
192
  profiler_listener.CodeMoveEvent(comment2_code, moved_code);
193

194
  // Enqueue a tick event to enable code events processing.
195
  EnqueueTickSampleEvent(processor, aaa_code.InstructionStart());
196

197
  isolate->logger()->RemoveCodeEventListener(&profiler_listener);
198
  processor->StopSynchronously();
199 200

  // Check the state of profile generator.
201
  CodeEntry* aaa =
202
      generator->code_map()->FindEntry(aaa_code.InstructionStart());
203
  CHECK(aaa);
204
  CHECK_EQ(0, strcmp(aaa_str, aaa->name()));
205

206
  CodeEntry* comment =
207
      generator->code_map()->FindEntry(comment_code.InstructionStart());
208
  CHECK(comment);
209
  CHECK_EQ(0, strcmp("comment", comment->name()));
210

211
  CHECK(!generator->code_map()->FindEntry(comment2_code.InstructionStart()));
212

213
  CodeEntry* comment2 =
214
      generator->code_map()->FindEntry(moved_code.InstructionStart());
215
  CHECK(comment2);
216
  CHECK_EQ(0, strcmp("comment2", comment2->name()));
217 218 219 220 221 222 223 224
}

template<typename T>
static int CompareProfileNodes(const T* p1, const T* p2) {
  return strcmp((*p1)->entry()->name(), (*p2)->entry()->name());
}

TEST(TickEvents) {
225
  TestSetup test_setup;
226
  LocalContext env;
227
  i::Isolate* isolate = CcTest::i_isolate();
228 229
  i::HandleScope scope(isolate);

230 231 232
  i::AbstractCode frame1_code = CreateCode(&env);
  i::AbstractCode frame2_code = CreateCode(&env);
  i::AbstractCode frame3_code = CreateCode(&env);
233

234
  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
235 236 237
  ProfilerCodeObserver code_observer(isolate);
  ProfileGenerator* generator =
      new ProfileGenerator(profiles, code_observer.code_map());
238
  ProfilerEventsProcessor* processor = new SamplingEventsProcessor(
239
      CcTest::i_isolate(), generator, &code_observer,
240
      v8::base::TimeDelta::FromMicroseconds(100), true);
241 242
  CpuProfiler profiler(isolate, kDebugNaming, kLazyLogging, profiles, generator,
                       processor);
243
  profiles->StartProfiling("");
244
  CHECK(processor->Start());
245
  ProfilerListener profiler_listener(isolate, processor);
246
  isolate->logger()->AddCodeEventListener(&profiler_listener);
247

lpy's avatar
lpy committed
248
  profiler_listener.CodeCreateEvent(i::Logger::BUILTIN_TAG, frame1_code, "bbb");
249
  profiler_listener.CodeCreateEvent(i::Logger::STUB_TAG, frame2_code, "ccc");
lpy's avatar
lpy committed
250
  profiler_listener.CodeCreateEvent(i::Logger::BUILTIN_TAG, frame3_code, "ddd");
251

252
  EnqueueTickSampleEvent(processor, frame1_code.raw_instruction_start());
253
  EnqueueTickSampleEvent(
254
      processor,
255 256 257 258 259
      frame2_code.raw_instruction_start() + frame2_code.ExecutableSize() / 2,
      frame1_code.raw_instruction_start() + frame1_code.ExecutableSize() / 2);
  EnqueueTickSampleEvent(processor, frame3_code.raw_instruction_end() - 1,
                         frame2_code.raw_instruction_end() - 1,
                         frame1_code.raw_instruction_end() - 1);
260

261
  isolate->logger()->RemoveCodeEventListener(&profiler_listener);
262
  processor->StopSynchronously();
263
  CpuProfile* profile = profiles->StopProfiling("");
264
  CHECK(profile);
265 266

  // Check call trees.
267
  const std::vector<ProfileNode*>* top_down_root_children =
268
      profile->top_down()->root()->children();
269 270 271 272 273
  CHECK_EQ(1, top_down_root_children->size());
  CHECK_EQ(0, strcmp("bbb", top_down_root_children->back()->entry()->name()));
  const std::vector<ProfileNode*>* top_down_bbb_children =
      top_down_root_children->back()->children();
  CHECK_EQ(1, top_down_bbb_children->size());
274
  CHECK_EQ(0, strcmp("ccc", top_down_bbb_children->back()->entry()->name()));
275 276 277 278 279 280 281
  const std::vector<ProfileNode*>* top_down_stub_children =
      top_down_bbb_children->back()->children();
  CHECK_EQ(1, top_down_stub_children->size());
  CHECK_EQ(0, strcmp("ddd", top_down_stub_children->back()->entry()->name()));
  const std::vector<ProfileNode*>* top_down_ddd_children =
      top_down_stub_children->back()->children();
  CHECK(top_down_ddd_children->empty());
282
}
283

284 285 286
// http://crbug/51594
// This test must not crash.
TEST(CrashIfStoppingLastNonExistentProfile) {
287
  CcTest::InitializeVM();
288
  TestSetup test_setup;
289
  std::unique_ptr<CpuProfiler> profiler(new CpuProfiler(CcTest::i_isolate()));
290 291 292 293
  profiler->StartProfiling("1");
  profiler->StopProfiling("2");
  profiler->StartProfiling("1");
  profiler->StopProfiling("");
294 295
}

296 297 298 299
// http://code.google.com/p/v8/issues/detail?id=1398
// Long stacks (exceeding max frames limit) must not be erased.
TEST(Issue1398) {
  TestSetup test_setup;
300
  LocalContext env;
301
  i::Isolate* isolate = CcTest::i_isolate();
302 303
  i::HandleScope scope(isolate);

304
  i::AbstractCode code = CreateCode(&env);
305

306
  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
307 308 309
  ProfilerCodeObserver code_observer(isolate);
  ProfileGenerator* generator =
      new ProfileGenerator(profiles, code_observer.code_map());
310
  ProfilerEventsProcessor* processor = new SamplingEventsProcessor(
311
      CcTest::i_isolate(), generator, &code_observer,
312
      v8::base::TimeDelta::FromMicroseconds(100), true);
313 314
  CpuProfiler profiler(isolate, kDebugNaming, kLazyLogging, profiles, generator,
                       processor);
315
  profiles->StartProfiling("");
316
  CHECK(processor->Start());
317
  ProfilerListener profiler_listener(isolate, processor);
318

lpy's avatar
lpy committed
319
  profiler_listener.CodeCreateEvent(i::Logger::BUILTIN_TAG, code, "bbb");
320

321
  v8::internal::TickSample sample;
322
  sample.pc = reinterpret_cast<void*>(code.InstructionStart());
323 324 325
  sample.tos = nullptr;
  sample.frames_count = v8::TickSample::kMaxFramesCount;
  for (unsigned i = 0; i < sample.frames_count; ++i) {
326
    sample.stack[i] = reinterpret_cast<void*>(code.InstructionStart());
327
  }
328 329
  sample.timestamp = base::TimeTicks::HighResolutionNow();
  processor->AddSample(sample);
330

331
  processor->StopSynchronously();
332
  CpuProfile* profile = profiles->StopProfiling("");
333
  CHECK(profile);
334

335
  unsigned actual_depth = 0;
336
  const ProfileNode* node = profile->top_down()->root();
337 338
  while (!node->children()->empty()) {
    node = node->children()->back();
339 340 341
    ++actual_depth;
  }

342
  CHECK_EQ(1 + v8::TickSample::kMaxFramesCount, actual_depth);  // +1 for PC.
343 344
}

345
TEST(DeleteAllCpuProfiles) {
346
  CcTest::InitializeVM();
347
  TestSetup test_setup;
348
  std::unique_ptr<CpuProfiler> profiler(new CpuProfiler(CcTest::i_isolate()));
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  CHECK_EQ(0, profiler->GetProfilesCount());
  profiler->DeleteAllProfiles();
  CHECK_EQ(0, profiler->GetProfilesCount());

  profiler->StartProfiling("1");
  profiler->StopProfiling("1");
  CHECK_EQ(1, profiler->GetProfilesCount());
  profiler->DeleteAllProfiles();
  CHECK_EQ(0, profiler->GetProfilesCount());
  profiler->StartProfiling("1");
  profiler->StartProfiling("2");
  profiler->StopProfiling("2");
  profiler->StopProfiling("1");
  CHECK_EQ(2, profiler->GetProfilesCount());
  profiler->DeleteAllProfiles();
  CHECK_EQ(0, profiler->GetProfilesCount());
365 366

  // Test profiling cancellation by the 'delete' command.
367 368 369 370 371
  profiler->StartProfiling("1");
  profiler->StartProfiling("2");
  CHECK_EQ(0, profiler->GetProfilesCount());
  profiler->DeleteAllProfiles();
  CHECK_EQ(0, profiler->GetProfilesCount());
372 373 374
}


375 376 377 378 379 380
static bool FindCpuProfile(v8::CpuProfiler* v8profiler,
                           const v8::CpuProfile* v8profile) {
  i::CpuProfiler* profiler = reinterpret_cast<i::CpuProfiler*>(v8profiler);
  const i::CpuProfile* profile =
      reinterpret_cast<const i::CpuProfile*>(v8profile);
  int length = profiler->GetProfilesCount();
381
  for (int i = 0; i < length; i++) {
382 383
    if (profile == profiler->GetProfile(i))
      return true;
384
  }
385
  return false;
386 387 388
}


389 390
TEST(DeleteCpuProfile) {
  LocalContext env;
391
  v8::HandleScope scope(env->GetIsolate());
392
  v8::CpuProfiler* cpu_profiler = v8::CpuProfiler::New(env->GetIsolate());
393
  i::CpuProfiler* iprofiler = reinterpret_cast<i::CpuProfiler*>(cpu_profiler);
394

395
  CHECK_EQ(0, iprofiler->GetProfilesCount());
396
  v8::Local<v8::String> name1 = v8_str("1");
397 398
  cpu_profiler->StartProfiling(name1);
  v8::CpuProfile* p1 = cpu_profiler->StopProfiling(name1);
399
  CHECK(p1);
400 401
  CHECK_EQ(1, iprofiler->GetProfilesCount());
  CHECK(FindCpuProfile(cpu_profiler, p1));
402
  p1->Delete();
403
  CHECK_EQ(0, iprofiler->GetProfilesCount());
404

405
  v8::Local<v8::String> name2 = v8_str("2");
406 407
  cpu_profiler->StartProfiling(name2);
  v8::CpuProfile* p2 = cpu_profiler->StopProfiling(name2);
408
  CHECK(p2);
409 410
  CHECK_EQ(1, iprofiler->GetProfilesCount());
  CHECK(FindCpuProfile(cpu_profiler, p2));
411
  v8::Local<v8::String> name3 = v8_str("3");
412 413
  cpu_profiler->StartProfiling(name3);
  v8::CpuProfile* p3 = cpu_profiler->StopProfiling(name3);
414
  CHECK(p3);
415 416 417 418
  CHECK_EQ(2, iprofiler->GetProfilesCount());
  CHECK_NE(p2, p3);
  CHECK(FindCpuProfile(cpu_profiler, p3));
  CHECK(FindCpuProfile(cpu_profiler, p2));
419
  p2->Delete();
420 421 422
  CHECK_EQ(1, iprofiler->GetProfilesCount());
  CHECK(!FindCpuProfile(cpu_profiler, p2));
  CHECK(FindCpuProfile(cpu_profiler, p3));
423
  p3->Delete();
424
  CHECK_EQ(0, iprofiler->GetProfilesCount());
425
  cpu_profiler->Dispose();
426 427 428
}


429 430 431
TEST(ProfileStartEndTime) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
432
  v8::CpuProfiler* cpu_profiler = v8::CpuProfiler::New(env->GetIsolate());
433

434
  v8::Local<v8::String> profile_name = v8_str("test");
435 436
  cpu_profiler->StartProfiling(profile_name);
  const v8::CpuProfile* profile = cpu_profiler->StopProfiling(profile_name);
437
  CHECK(profile->GetStartTime() <= profile->GetEndTime());
438
  cpu_profiler->Dispose();
439 440
}

441 442 443 444 445 446 447 448 449 450 451 452
class ProfilerHelper {
 public:
  explicit ProfilerHelper(const v8::Local<v8::Context>& context)
      : context_(context),
        profiler_(v8::CpuProfiler::New(context->GetIsolate())) {
    i::ProfilerExtension::set_profiler(profiler_);
  }
  ~ProfilerHelper() {
    i::ProfilerExtension::set_profiler(static_cast<CpuProfiler*>(nullptr));
    profiler_->Dispose();
  }

453
  using ProfilingMode = v8::CpuProfilingMode;
454

455 456 457 458 459
  v8::CpuProfile* Run(
      v8::Local<v8::Function> function, v8::Local<v8::Value> argv[], int argc,
      unsigned min_js_samples = 0, unsigned min_external_samples = 0,
      ProfilingMode mode = ProfilingMode::kLeafNodeLineNumbers,
      unsigned max_samples = CpuProfilingOptions::kNoSampleLimit);
460 461 462 463 464 465 466 467 468 469 470 471

  v8::CpuProfiler* profiler() { return profiler_; }

 private:
  v8::Local<v8::Context> context_;
  v8::CpuProfiler* profiler_;
};

v8::CpuProfile* ProfilerHelper::Run(v8::Local<v8::Function> function,
                                    v8::Local<v8::Value> argv[], int argc,
                                    unsigned min_js_samples,
                                    unsigned min_external_samples,
472
                                    ProfilingMode mode, unsigned max_samples) {
473
  v8::Local<v8::String> profile_name = v8_str("my_profile");
474

475
  profiler_->SetSamplingInterval(100);
476
  profiler_->StartProfiling(profile_name, {mode, max_samples});
477

478 479
  v8::internal::CpuProfiler* iprofiler =
      reinterpret_cast<v8::internal::CpuProfiler*>(profiler_);
480 481 482
  v8::sampler::Sampler* sampler =
      reinterpret_cast<i::SamplingEventsProcessor*>(iprofiler->processor())
          ->sampler();
483 484
  sampler->StartCountingSamples();
  do {
485
    function->Call(context_, context_->Global(), argc, argv).ToLocalChecked();
486 487
  } while (sampler->js_sample_count() < min_js_samples ||
           sampler->external_sample_count() < min_external_samples);
488

489
  v8::CpuProfile* profile = profiler_->StopProfiling(profile_name);
490

491
  CHECK(profile);
492
  // Dump collected profile to have a better diagnostic in case of failure.
493
  reinterpret_cast<i::CpuProfile*>(profile)->Print();
494 495 496 497

  return profile;
}

498 499 500 501 502 503 504
static unsigned TotalHitCount(const v8::CpuProfileNode* node) {
  unsigned hit_count = node->GetHitCount();
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i)
    hit_count += TotalHitCount(node->GetChild(i));
  return hit_count;
}

505 506
static const v8::CpuProfileNode* FindChild(v8::Local<v8::Context> context,
                                           const v8::CpuProfileNode* node,
507 508
                                           const char* name) {
  int count = node->GetChildrenCount();
alph's avatar
alph committed
509
  v8::Local<v8::String> name_handle = v8_str(name);
510 511
  for (int i = 0; i < count; i++) {
    const v8::CpuProfileNode* child = node->GetChild(i);
alph's avatar
alph committed
512
    if (name_handle->Equals(context, child->GetFunctionName()).FromJust()) {
513 514
      return child;
    }
515
  }
516
  return nullptr;
517 518
}

519 520 521 522 523 524 525 526 527 528
static const v8::CpuProfileNode* FindChild(const v8::CpuProfileNode* node,
                                           const char* name) {
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {
    const v8::CpuProfileNode* child = node->GetChild(i);
    if (strcmp(child->GetFunctionNameStr(), name) == 0) {
      return child;
    }
  }
  return nullptr;
}
529

530 531
static const v8::CpuProfileNode* GetChild(v8::Local<v8::Context> context,
                                          const v8::CpuProfileNode* node,
532
                                          const char* name) {
533
  const v8::CpuProfileNode* result = FindChild(context, node, name);
534
  if (!result) FATAL("Failed to GetChild: %s", name);
535 536 537
  return result;
}

538 539
static void CheckSimpleBranch(v8::Local<v8::Context> context,
                              const v8::CpuProfileNode* node,
540 541 542
                              const char* names[], int length) {
  for (int i = 0; i < length; i++) {
    const char* name = names[i];
543
    node = GetChild(context, node, name);
544 545 546
  }
}

547 548
static const ProfileNode* GetSimpleBranch(v8::Local<v8::Context> context,
                                          v8::CpuProfile* profile,
loislo's avatar
loislo committed
549 550
                                          const char* names[], int length) {
  const v8::CpuProfileNode* node = profile->GetTopDownRoot();
551
  for (int i = 0; i < length; i++) {
552
    node = GetChild(context, node, names[i]);
553
  }
loislo's avatar
loislo committed
554
  return reinterpret_cast<const ProfileNode*>(node);
555 556
}

557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
struct NameLinePair {
  const char* name;
  int line_number;
};

static const v8::CpuProfileNode* FindChild(const v8::CpuProfileNode* node,
                                           NameLinePair pair) {
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {
    const v8::CpuProfileNode* child = node->GetChild(i);
    // The name and line number must match, or if the requested line number was
    // -1, then match any function of the same name.
    if (strcmp(child->GetFunctionNameStr(), pair.name) == 0 &&
        (child->GetLineNumber() == pair.line_number ||
         pair.line_number == -1)) {
      return child;
    }
  }
  return nullptr;
}

static const v8::CpuProfileNode* GetChild(const v8::CpuProfileNode* node,
                                          NameLinePair pair) {
  const v8::CpuProfileNode* result = FindChild(node, pair);
  if (!result) FATAL("Failed to GetChild: %s:%d", pair.name, pair.line_number);
  return result;
}

static void CheckBranch(const v8::CpuProfileNode* node, NameLinePair path[],
                        int length) {
  for (int i = 0; i < length; i++) {
    NameLinePair pair = path[i];
    node = GetChild(node, pair);
  }
}

alph's avatar
alph committed
592 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
static const char* cpu_profiler_test_source =
    "%NeverOptimizeFunction(loop);\n"
    "%NeverOptimizeFunction(delay);\n"
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(baz);\n"
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(start);\n"
    "function loop(timeout) {\n"
    "  this.mmm = 0;\n"
    "  var start = Date.now();\n"
    "  do {\n"
    "    var n = 1000;\n"
    "    while(n > 1) {\n"
    "      n--;\n"
    "      this.mmm += n * n * n;\n"
    "    }\n"
    "  } while (Date.now() - start < timeout);\n"
    "}\n"
    "function delay() { loop(10); }\n"
    "function bar() { delay(); }\n"
    "function baz() { delay(); }\n"
    "function foo() {\n"
    "  delay();\n"
    "  bar();\n"
    "  delay();\n"
    "  baz();\n"
    "}\n"
    "function start(duration) {\n"
    "  var start = Date.now();\n"
    "  do {\n"
    "    foo();\n"
    "  } while (Date.now() - start < duration);\n"
    "}\n";
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643

// Check that the profile tree for the script above will look like the
// following:
//
// [Top down]:
//  1062     0   (root) [-1]
//  1054     0    start [-1]
//  1054     1      foo [-1]
//   265     0        baz [-1]
//   265     1          delay [-1]
//   264   264            loop [-1]
//   525     3        delay [-1]
//   522   522          loop [-1]
//   263     0        bar [-1]
//   263     1          delay [-1]
//   262   262            loop [-1]
//     2     2    (program) [-1]
//     6     6    (garbage collector) [-1]
TEST(CollectCpuProfile) {
alph's avatar
alph committed
644
  i::FLAG_allow_natives_syntax = true;
645 646 647
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

648
  CompileRun(cpu_profiler_test_source);
649
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
650

651
  int32_t profiling_interval_ms = 200;
652 653
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), profiling_interval_ms)};
654 655
  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 1000);
656 657

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
658 659
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  const v8::CpuProfileNode* foo_node = GetChild(env.local(), start_node, "foo");
660

alph's avatar
alph committed
661 662 663 664 665 666 667
  const char* bar_branch[] = {"bar", "delay", "loop"};
  CheckSimpleBranch(env.local(), foo_node, bar_branch, arraysize(bar_branch));
  const char* baz_branch[] = {"baz", "delay", "loop"};
  CheckSimpleBranch(env.local(), foo_node, baz_branch, arraysize(baz_branch));
  const char* delay_branch[] = {"delay", "loop"};
  CheckSimpleBranch(env.local(), foo_node, delay_branch,
                    arraysize(delay_branch));
668

669
  profile->Delete();
670
}
671

672 673 674 675 676 677 678 679 680 681 682 683
TEST(CollectCpuProfileCallerLineNumbers) {
  i::FLAG_allow_natives_syntax = true;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

  CompileRun(cpu_profiler_test_source);
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");

  int32_t profiling_interval_ms = 200;
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), profiling_interval_ms)};
  ProfilerHelper helper(env.local());
684 685
  helper.Run(function, args, arraysize(args), 1000, 0,
             v8::CpuProfilingMode::kCallerLineNumbers, 0);
686
  v8::CpuProfile* profile =
687 688
      helper.Run(function, args, arraysize(args), 1000, 0,
                 v8::CpuProfilingMode::kCallerLineNumbers, 0);
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* start_node = GetChild(root, {"start", 27});
  const v8::CpuProfileNode* foo_node = GetChild(start_node, {"foo", 30});

  NameLinePair bar_branch[] = {{"bar", 23}, {"delay", 19}, {"loop", 18}};
  CheckBranch(foo_node, bar_branch, arraysize(bar_branch));
  NameLinePair baz_branch[] = {{"baz", 25}, {"delay", 20}, {"loop", 18}};
  CheckBranch(foo_node, baz_branch, arraysize(baz_branch));
  NameLinePair delay_at22_branch[] = {{"delay", 22}, {"loop", 18}};
  CheckBranch(foo_node, delay_at22_branch, arraysize(delay_at22_branch));
  NameLinePair delay_at24_branch[] = {{"delay", 24}, {"loop", 18}};
  CheckBranch(foo_node, delay_at24_branch, arraysize(delay_at24_branch));

  profile->Delete();
}

706
static const char* hot_deopt_no_frame_entry_test_source =
alph's avatar
alph committed
707 708 709 710 711 712 713 714 715 716 717 718 719
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(start);\n"
    "function foo(a, b) {\n"
    "  return a + b;\n"
    "}\n"
    "function start(timeout) {\n"
    "  var start = Date.now();\n"
    "  do {\n"
    "    for (var i = 1; i < 1000; ++i) foo(1, i);\n"
    "    var duration = Date.now() - start;\n"
    "  } while (duration < timeout);\n"
    "  return duration;\n"
    "}\n";
720 721 722 723 724 725 726 727 728 729 730

// Check that the profile tree for the script above will look like the
// following:
//
// [Top down]:
//  1062     0  (root) [-1]
//  1054     0    start [-1]
//  1054     1      foo [-1]
//     2     2    (program) [-1]
//     6     6    (garbage collector) [-1]
//
731
// The test checks no FP ranges are present in a deoptimized function.
732 733 734
// If 'foo' has no ranges the samples falling into the prologue will miss the
// 'start' function on the stack, so 'foo' will be attached to the (root).
TEST(HotDeoptNoFrameEntry) {
alph's avatar
alph committed
735
  i::FLAG_allow_natives_syntax = true;
736 737 738
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

739
  CompileRun(hot_deopt_no_frame_entry_test_source);
740
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
741 742

  int32_t profiling_interval_ms = 200;
743 744
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), profiling_interval_ms)};
745 746
  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 1000);
747 748
  function->Call(env.local(), env->Global(), arraysize(args), args)
      .ToLocalChecked();
749 750

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
751 752
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "foo");
753 754 755 756

  profile->Delete();
}

757
TEST(CollectCpuProfileSamples) {
alph's avatar
alph committed
758
  i::FLAG_allow_natives_syntax = true;
759 760 761
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

762
  CompileRun(cpu_profiler_test_source);
763
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
764 765

  int32_t profiling_interval_ms = 200;
766 767
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), profiling_interval_ms)};
768
  ProfilerHelper helper(env.local());
769
  v8::CpuProfile* profile =
770
      helper.Run(function, args, arraysize(args), 1000, 0);
771 772 773 774 775 776

  CHECK_LE(200, profile->GetSamplesCount());
  uint64_t end_time = profile->GetEndTime();
  uint64_t current_time = profile->GetStartTime();
  CHECK_LE(current_time, end_time);
  for (int i = 0; i < profile->GetSamplesCount(); i++) {
777
    CHECK(profile->GetSample(i));
778 779 780 781 782 783 784 785 786
    uint64_t timestamp = profile->GetSampleTimestamp(i);
    CHECK_LE(current_time, timestamp);
    CHECK_LE(timestamp, end_time);
    current_time = timestamp;
  }

  profile->Delete();
}

alph's avatar
alph committed
787 788 789 790 791 792 793 794 795 796 797 798
static const char* cpu_profiler_test_source2 =
    "%NeverOptimizeFunction(loop);\n"
    "%NeverOptimizeFunction(delay);\n"
    "%NeverOptimizeFunction(start);\n"
    "function loop() {}\n"
    "function delay() { loop(); }\n"
    "function start(duration) {\n"
    "  var start = Date.now();\n"
    "  do {\n"
    "    for (var i = 0; i < 10000; ++i) delay();\n"
    "  } while (Date.now() - start < duration);\n"
    "}";
799

800
// Check that the profile tree doesn't contain unexpected traces:
801 802 803 804 805 806 807 808 809 810 811
//  - 'loop' can be called only by 'delay'
//  - 'delay' may be called only by 'start'
// The profile will look like the following:
//
// [Top down]:
//   135     0   (root) [-1] #1
//   121    72    start [-1] #3
//    49    33      delay [-1] #4
//    16    16        loop [-1] #5
//    14    14    (program) [-1] #2
TEST(SampleWhenFrameIsNotSetup) {
alph's avatar
alph committed
812
  i::FLAG_allow_natives_syntax = true;
813 814 815
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

816
  CompileRun(cpu_profiler_test_source2);
817
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
818

alph's avatar
alph committed
819
  int32_t duration_ms = 100;
820
  v8::Local<v8::Value> args[] = {
alph's avatar
alph committed
821
      v8::Integer::New(env->GetIsolate(), duration_ms)};
822 823
  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 1000);
824 825

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
826 827 828 829
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  const v8::CpuProfileNode* delay_node =
      GetChild(env.local(), start_node, "delay");
  GetChild(env.local(), delay_node, "loop");
830

831
  profile->Delete();
832
}
833 834 835 836 837 838 839 840

static const char* native_accessor_test_source = "function start(count) {\n"
"  for (var i = 0; i < count; i++) {\n"
"    var o = instance.foo;\n"
"    instance.foo = o + 1;\n"
"  }\n"
"}\n";

841
class TestApiCallbacks {
842
 public:
843
  explicit TestApiCallbacks(int min_duration_ms)
844
      : min_duration_ms_(min_duration_ms),
845
        is_warming_up_(false) {}
846

847 848
  static void Getter(v8::Local<v8::String> name,
                     const v8::PropertyCallbackInfo<v8::Value>& info) {
alph's avatar
alph committed
849
    TestApiCallbacks* data = FromInfo(info);
850
    data->Wait();
851 852 853 854
  }

  static void Setter(v8::Local<v8::String> name,
                     v8::Local<v8::Value> value,
855
                     const v8::PropertyCallbackInfo<void>& info) {
alph's avatar
alph committed
856
    TestApiCallbacks* data = FromInfo(info);
857 858 859 860
    data->Wait();
  }

  static void Callback(const v8::FunctionCallbackInfo<v8::Value>& info) {
alph's avatar
alph committed
861
    TestApiCallbacks* data = FromInfo(info);
862
    data->Wait();
863 864
  }

865
  void set_warming_up(bool value) { is_warming_up_ = value; }
866 867

 private:
868 869
  void Wait() {
    if (is_warming_up_) return;
870 871
    v8::Platform* platform = v8::internal::V8::GetCurrentPlatform();
    double start = platform->CurrentClockTimeMillis();
872 873
    double duration = 0;
    while (duration < min_duration_ms_) {
874
      v8::base::OS::Sleep(v8::base::TimeDelta::FromMilliseconds(1));
875
      duration = platform->CurrentClockTimeMillis() - start;
876 877 878
    }
  }

alph's avatar
alph committed
879 880
  template <typename T>
  static TestApiCallbacks* FromInfo(const T& info) {
881
    void* data = v8::External::Cast(*info.Data())->Value();
882
    return reinterpret_cast<TestApiCallbacks*>(data);
883 884 885
  }

  int min_duration_ms_;
886
  bool is_warming_up_;
887 888 889 890 891 892 893
};


// Test that native accessors are properly reported in the CPU profile.
// This test checks the case when the long-running accessors are called
// only once and the optimizer doesn't have chance to change the invocation
// code.
894
TEST(NativeAccessorUninitializedIC) {
895
  LocalContext env;
896 897
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
898

899 900
  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(isolate);
901 902 903
  v8::Local<v8::ObjectTemplate> instance_template =
      func_template->InstanceTemplate();

904
  TestApiCallbacks accessors(100);
905
  v8::Local<v8::External> data = v8::External::New(isolate, &accessors);
906 907
  instance_template->SetAccessor(v8_str("foo"), &TestApiCallbacks::Getter,
                                 &TestApiCallbacks::Setter, data);
908 909 910 911 912
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  v8::Local<v8::Object> instance =
      func->NewInstance(env.local()).ToLocalChecked();
  env->Global()->Set(env.local(), v8_str("instance"), instance).FromJust();
913

914
  CompileRun(native_accessor_test_source);
915
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
916

917
  ProfilerHelper helper(env.local());
918
  int32_t repeat_count = 1;
919
  v8::Local<v8::Value> args[] = {v8::Integer::New(isolate, repeat_count)};
920
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 0, 100);
921 922

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
923 924 925
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "get foo");
  GetChild(env.local(), start_node, "set foo");
926

927
  profile->Delete();
928 929 930 931 932 933
}


// Test that native accessors are properly reported in the CPU profile.
// This test makes sure that the accessors are called enough times to become
// hot and to trigger optimizations.
934
TEST(NativeAccessorMonomorphicIC) {
935
  LocalContext env;
936 937
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
938

939 940
  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(isolate);
941 942 943
  v8::Local<v8::ObjectTemplate> instance_template =
      func_template->InstanceTemplate();

944
  TestApiCallbacks accessors(1);
945
  v8::Local<v8::External> data =
946
      v8::External::New(isolate, &accessors);
947 948
  instance_template->SetAccessor(v8_str("foo"), &TestApiCallbacks::Getter,
                                 &TestApiCallbacks::Setter, data);
949 950 951 952 953
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  v8::Local<v8::Object> instance =
      func->NewInstance(env.local()).ToLocalChecked();
  env->Global()->Set(env.local(), v8_str("instance"), instance).FromJust();
954

955
  CompileRun(native_accessor_test_source);
956
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
957

958 959 960 961 962
  {
    // Make sure accessors ICs are in monomorphic state before starting
    // profiling.
    accessors.set_warming_up(true);
    int32_t warm_up_iterations = 3;
963 964 965 966
    v8::Local<v8::Value> args[] = {
        v8::Integer::New(isolate, warm_up_iterations)};
    function->Call(env.local(), env->Global(), arraysize(args), args)
        .ToLocalChecked();
967 968 969
    accessors.set_warming_up(false);
  }

970
  int32_t repeat_count = 100;
971
  v8::Local<v8::Value> args[] = {v8::Integer::New(isolate, repeat_count)};
972 973
  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 0, 100);
974 975

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
976 977 978
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "get foo");
  GetChild(env.local(), start_node, "set foo");
979

980
  profile->Delete();
981
}
982 983 984 985 986 987 988 989 990 991 992


static const char* native_method_test_source = "function start(count) {\n"
"  for (var i = 0; i < count; i++) {\n"
"    instance.fooMethod();\n"
"  }\n"
"}\n";


TEST(NativeMethodUninitializedIC) {
  LocalContext env;
993 994
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
995 996

  TestApiCallbacks callbacks(100);
997
  v8::Local<v8::External> data = v8::External::New(isolate, &callbacks);
998

999 1000
  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(isolate);
1001
  func_template->SetClassName(v8_str("Test_InstanceConstructor"));
1002 1003
  v8::Local<v8::ObjectTemplate> proto_template =
      func_template->PrototypeTemplate();
1004
  v8::Local<v8::Signature> signature =
1005
      v8::Signature::New(isolate, func_template);
1006 1007 1008 1009
  proto_template->Set(
      v8_str("fooMethod"),
      v8::FunctionTemplate::New(isolate, &TestApiCallbacks::Callback, data,
                                signature, 0));
1010

1011 1012 1013 1014 1015
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  v8::Local<v8::Object> instance =
      func->NewInstance(env.local()).ToLocalChecked();
  env->Global()->Set(env.local(), v8_str("instance"), instance).FromJust();
1016

1017
  CompileRun(native_method_test_source);
1018
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
1019

1020
  ProfilerHelper helper(env.local());
1021
  int32_t repeat_count = 1;
1022
  v8::Local<v8::Value> args[] = {v8::Integer::New(isolate, repeat_count)};
1023
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 0, 100);
1024 1025

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1026 1027
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "fooMethod");
1028

1029
  profile->Delete();
1030 1031 1032 1033 1034
}


TEST(NativeMethodMonomorphicIC) {
  LocalContext env;
1035 1036
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
1037 1038

  TestApiCallbacks callbacks(1);
1039
  v8::Local<v8::External> data =
1040
      v8::External::New(isolate, &callbacks);
1041

1042 1043
  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(isolate);
1044
  func_template->SetClassName(v8_str("Test_InstanceCostructor"));
1045 1046
  v8::Local<v8::ObjectTemplate> proto_template =
      func_template->PrototypeTemplate();
1047
  v8::Local<v8::Signature> signature =
1048
      v8::Signature::New(isolate, func_template);
1049 1050 1051 1052
  proto_template->Set(
      v8_str("fooMethod"),
      v8::FunctionTemplate::New(isolate, &TestApiCallbacks::Callback, data,
                                signature, 0));
1053

1054 1055 1056 1057 1058
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  v8::Local<v8::Object> instance =
      func->NewInstance(env.local()).ToLocalChecked();
  env->Global()->Set(env.local(), v8_str("instance"), instance).FromJust();
1059

1060
  CompileRun(native_method_test_source);
1061
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
1062 1063 1064 1065 1066
  {
    // Make sure method ICs are in monomorphic state before starting
    // profiling.
    callbacks.set_warming_up(true);
    int32_t warm_up_iterations = 3;
1067 1068 1069 1070
    v8::Local<v8::Value> args[] = {
        v8::Integer::New(isolate, warm_up_iterations)};
    function->Call(env.local(), env->Global(), arraysize(args), args)
        .ToLocalChecked();
1071 1072 1073
    callbacks.set_warming_up(false);
  }

1074
  ProfilerHelper helper(env.local());
1075
  int32_t repeat_count = 100;
1076
  v8::Local<v8::Value> args[] = {v8::Integer::New(isolate, repeat_count)};
1077
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 0, 200);
1078 1079

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
1080
  GetChild(env.local(), root, "start");
alph's avatar
alph committed
1081 1082
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "fooMethod");
1083

1084
  profile->Delete();
1085
}
1086 1087


1088 1089 1090 1091 1092 1093 1094 1095
static const char* bound_function_test_source =
    "function foo() {\n"
    "  startProfiling('my_profile');\n"
    "}\n"
    "function start() {\n"
    "  var callback = foo.bind(this);\n"
    "  callback();\n"
    "}";
1096 1097 1098


TEST(BoundFunctionCall) {
1099
  v8::HandleScope scope(CcTest::isolate());
1100
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
1101
  v8::Context::Scope context_scope(env);
1102

1103
  CompileRun(bound_function_test_source);
1104
  v8::Local<v8::Function> function = GetFunction(env, "start");
1105

1106 1107
  ProfilerHelper helper(env);
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0);
1108 1109 1110

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();

alph's avatar
alph committed
1111 1112
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  GetChild(env, start_node, "foo");
1113

1114
  profile->Delete();
1115
}
1116

1117
// This tests checks distribution of the samples through the source lines.
1118
static void TickLines(bool optimize) {
1119 1120 1121
#ifndef V8_LITE_MODE
  FLAG_opt = optimize;
#endif  // V8_LITE_MODE
1122 1123
  CcTest::InitializeVM();
  LocalContext env;
1124
  i::FLAG_allow_natives_syntax = true;
1125 1126 1127 1128 1129
  i::Isolate* isolate = CcTest::i_isolate();
  i::Factory* factory = isolate->factory();
  i::HandleScope scope(isolate);

  i::EmbeddedVector<char, 512> script;
1130
  i::EmbeddedVector<char, 64> prepare_opt;
1131
  i::EmbeddedVector<char, 64> optimize_call;
1132 1133

  const char* func_name = "func";
1134
  if (optimize) {
1135 1136
    i::SNPrintF(prepare_opt, "%%PrepareFunctionForOptimization(%s);\n",
                func_name);
1137 1138 1139
    i::SNPrintF(optimize_call, "%%OptimizeFunctionOnNextCall(%s);\n",
                func_name);
  } else {
1140
    prepare_opt[0] = '\0';
1141
    optimize_call[0] = '\0';
1142
  }
1143 1144 1145 1146 1147 1148 1149 1150 1151
  i::SNPrintF(script,
              "function %s() {\n"
              "  var n = 0;\n"
              "  var m = 100*100;\n"
              "  while (m > 1) {\n"
              "    m--;\n"
              "    n += m * m * m;\n"
              "  }\n"
              "}\n"
1152
              "%s"
1153 1154
              "%s();\n"
              "%s"
1155
              "%s();\n",
1156 1157
              func_name, prepare_opt.begin(), func_name, optimize_call.begin(),
              func_name);
1158

1159
  CompileRun(script.begin());
1160

1161
  i::Handle<i::JSFunction> func = i::Handle<i::JSFunction>::cast(
1162
      v8::Utils::OpenHandle(*GetFunction(env.local(), func_name)));
1163
  CHECK(!func->shared().is_null());
1164
  CHECK(!func->shared().abstract_code().is_null());
1165
  CHECK(!optimize || func->IsOptimized() ||
Mythri's avatar
Mythri committed
1166
        !CcTest::i_isolate()->use_optimizer());
1167 1168
  i::AbstractCode code = func->abstract_code();
  CHECK(!code.is_null());
1169
  i::Address code_address = code.raw_instruction_start();
1170
  CHECK_NE(code_address, kNullAddress);
1171

1172
  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
1173 1174 1175
  ProfilerCodeObserver code_observer(isolate);
  ProfileGenerator* generator =
      new ProfileGenerator(profiles, code_observer.code_map());
1176
  ProfilerEventsProcessor* processor = new SamplingEventsProcessor(
1177
      CcTest::i_isolate(), generator, &code_observer,
1178
      v8::base::TimeDelta::FromMicroseconds(100), true);
1179 1180
  CpuProfiler profiler(isolate, kDebugNaming, kLazyLogging, profiles, generator,
                       processor);
1181
  profiles->StartProfiling("");
1182 1183 1184 1185 1186
  // TODO(delphick): Stop using the CpuProfiler internals here: This forces
  // LogCompiledFunctions so that source positions are collected everywhere.
  // This would normally happen automatically with CpuProfiler::StartProfiling
  // but doesn't because it's constructed with a generator and a processor.
  isolate->logger()->LogCompiledFunctions();
1187
  CHECK(processor->Start());
1188
  ProfilerListener profiler_listener(isolate, processor);
1189 1190 1191 1192 1193

  // Enqueue code creation events.
  i::Handle<i::String> str = factory->NewStringFromAsciiChecked(func_name);
  int line = 1;
  int column = 1;
lpy's avatar
lpy committed
1194 1195
  profiler_listener.CodeCreateEvent(i::Logger::FUNCTION_TAG, code,
                                    func->shared(), *str, line, column);
1196 1197

  // Enqueue a tick event to enable code events processing.
1198
  EnqueueTickSampleEvent(processor, code_address);
1199 1200 1201 1202

  processor->StopSynchronously();

  CpuProfile* profile = profiles->StopProfiling("");
1203
  CHECK(profile);
1204 1205

  // Check the state of profile generator.
1206
  CodeEntry* func_entry = generator->code_map()->FindEntry(code_address);
1207
  CHECK(func_entry);
1208
  CHECK_EQ(0, strcmp(func_name, func_entry->name()));
1209
  const i::SourcePositionTable* line_info = func_entry->line_info();
1210
  CHECK(line_info);
1211 1212
  CHECK_NE(v8::CpuProfileNode::kNoLineNumberInfo,
           line_info->GetSourceLineNumber(100));
1213 1214 1215 1216

  // Check the hit source lines using V8 Public APIs.
  const i::ProfileTree* tree = profile->top_down();
  ProfileNode* root = tree->root();
1217
  CHECK(root);
1218
  ProfileNode* func_node = root->FindChild(func_entry);
1219
  CHECK(func_node);
1220 1221 1222 1223 1224 1225 1226

  // Add 10 faked ticks to source line #5.
  int hit_line = 5;
  int hit_count = 10;
  for (int i = 0; i < hit_count; i++) func_node->IncrementLineTicks(hit_line);

  unsigned int line_count = func_node->GetHitLineCount();
1227
  CHECK_EQ(2u, line_count);  // Expect two hit source lines - #1 and #5.
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
  ScopedVector<v8::CpuProfileNode::LineTick> entries(line_count);
  CHECK(func_node->GetLineTicks(&entries[0], line_count));
  int value = 0;
  for (int i = 0; i < entries.length(); i++)
    if (entries[i].line == hit_line) {
      value = entries[i].hit_count;
      break;
    }
  CHECK_EQ(hit_count, value);
}

1239 1240 1241 1242
TEST(TickLinesBaseline) { TickLines(false); }

TEST(TickLinesOptimized) { TickLines(true); }

alph's avatar
alph committed
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
static const char* call_function_test_source =
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(start);\n"
    "function bar(n) {\n"
    "  var s = 0;\n"
    "  for (var i = 0; i < n; i++) s += i * i * i;\n"
    "  return s;\n"
    "}\n"
    "function start(duration) {\n"
    "  var start = Date.now();\n"
    "  do {\n"
    "    for (var i = 0; i < 100; ++i)\n"
    "      bar.call(this, 1000);\n"
    "  } while (Date.now() - start < duration);\n"
    "}";
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271

// Test that if we sampled thread when it was inside FunctionCall buitin then
// its caller frame will be '(unresolved function)' as we have no reliable way
// to resolve it.
//
// [Top down]:
//    96     0   (root) [-1] #1
//     1     1    (garbage collector) [-1] #4
//     5     0    (unresolved function) [-1] #5
//     5     5      call [-1] #6
//    71    70    start [-1] #3
//     1     1      bar [-1] #7
//    19    19    (program) [-1] #2
TEST(FunctionCallSample) {
alph's avatar
alph committed
1272
  i::FLAG_allow_natives_syntax = true;
1273 1274 1275
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

1276 1277
  // Collect garbage that might have be generated while installing
  // extensions.
1278
  CcTest::CollectAllGarbage();
1279

1280
  CompileRun(call_function_test_source);
1281
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
1282

1283
  ProfilerHelper helper(env.local());
1284
  int32_t duration_ms = 100;
1285 1286
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), duration_ms)};
1287
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 1000);
1288 1289

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1290 1291
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "bar");
1292

lpy's avatar
lpy committed
1293 1294
  const v8::CpuProfileNode* unresolved_node =
      FindChild(env.local(), root, i::CodeEntry::kUnresolvedFunctionName);
alph's avatar
alph committed
1295
  CHECK(!unresolved_node || GetChild(env.local(), unresolved_node, "call"));
1296

1297
  profile->Delete();
1298 1299
}

1300
static const char* function_apply_test_source =
alph's avatar
alph committed
1301 1302 1303 1304 1305 1306 1307
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(test);\n"
    "%NeverOptimizeFunction(start);\n"
    "function bar(n) {\n"
    "  var s = 0;\n"
    "  for (var i = 0; i < n; i++) s += i * i * i;\n"
    "  return s;\n"
1308 1309
    "}\n"
    "function test() {\n"
alph's avatar
alph committed
1310
    "  bar.apply(this, [1000]);\n"
1311 1312 1313
    "}\n"
    "function start(duration) {\n"
    "  var start = Date.now();\n"
alph's avatar
alph committed
1314 1315 1316
    "  do {\n"
    "    for (var i = 0; i < 100; ++i) test();\n"
    "  } while (Date.now() - start < duration);\n"
1317
    "}";
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328

// [Top down]:
//    94     0   (root) [-1] #0 1
//     2     2    (garbage collector) [-1] #0 7
//    82    49    start [-1] #16 3
//     1     0      (unresolved function) [-1] #0 8
//     1     1        apply [-1] #0 9
//    32    21      test [-1] #16 4
//     2     2        bar [-1] #16 6
//    10    10    (program) [-1] #0 2
TEST(FunctionApplySample) {
alph's avatar
alph committed
1329
  i::FLAG_allow_natives_syntax = true;
1330 1331 1332
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

1333
  CompileRun(function_apply_test_source);
1334
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
1335

1336
  ProfilerHelper helper(env.local());
1337
  int32_t duration_ms = 100;
1338 1339
  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), duration_ms)};
1340
  v8::CpuProfile* profile = helper.Run(function, args, arraysize(args), 1000);
1341 1342

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1343 1344 1345 1346
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  const v8::CpuProfileNode* test_node =
      GetChild(env.local(), start_node, "test");
  GetChild(env.local(), test_node, "bar");
1347

lpy's avatar
lpy committed
1348 1349
  const v8::CpuProfileNode* unresolved_node =
      FindChild(env.local(), start_node, CodeEntry::kUnresolvedFunctionName);
alph's avatar
alph committed
1350
  CHECK(!unresolved_node || GetChild(env.local(), unresolved_node, "apply"));
1351

1352
  profile->Delete();
1353
}
1354

1355
static const char* cpu_profiler_deep_stack_test_source =
alph's avatar
alph committed
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
    "function foo(n) {\n"
    "  if (n)\n"
    "    foo(n - 1);\n"
    "  else\n"
    "    collectSample();\n"
    "}\n"
    "function start() {\n"
    "  startProfiling('my_profile');\n"
    "  foo(250);\n"
    "}\n";
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375

// Check a deep stack
//
// [Top down]:
//    0  (root) 0 #1
//    2    (program) 0 #2
//    0    start 21 #3 no reason
//    0      foo 21 #4 no reason
//    0        foo 21 #5 no reason
//                ....
alph's avatar
alph committed
1376
//    0          foo 21 #254 no reason
1377 1378
TEST(CpuProfileDeepStack) {
  v8::HandleScope scope(CcTest::isolate());
1379
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
1380
  v8::Context::Scope context_scope(env);
1381
  ProfilerHelper helper(env);
1382

1383
  CompileRun(cpu_profiler_deep_stack_test_source);
1384
  v8::Local<v8::Function> function = GetFunction(env, "start");
1385

1386
  v8::Local<v8::String> profile_name = v8_str("my_profile");
1387
  function->Call(env, env->Global(), 0, nullptr).ToLocalChecked();
1388
  v8::CpuProfile* profile = helper.profiler()->StopProfiling(profile_name);
1389
  CHECK(profile);
1390 1391 1392 1393
  // Dump collected profile to have a better diagnostic in case of failure.
  reinterpret_cast<i::CpuProfile*>(profile)->Print();

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
1394
  const v8::CpuProfileNode* node = GetChild(env, root, "start");
alph's avatar
alph committed
1395
  for (int i = 0; i <= 250; ++i) {
1396
    node = GetChild(env, node, "foo");
1397
  }
alph's avatar
alph committed
1398
  CHECK(!FindChild(env, node, "foo"));
1399 1400 1401 1402

  profile->Delete();
}

1403
static const char* js_native_js_test_source =
alph's avatar
alph committed
1404 1405 1406 1407 1408 1409 1410
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(start);\n"
    "function foo(n) {\n"
    "  var s = 0;\n"
    "  for (var i = 0; i < n; i++) s += i * i * i;\n"
    "  return s;\n"
1411 1412
    "}\n"
    "function bar() {\n"
alph's avatar
alph committed
1413
    "  foo(1000);\n"
1414 1415
    "}\n"
    "function start() {\n"
alph's avatar
alph committed
1416
    "  CallJsFunction(bar);\n"
1417
    "}";
1418 1419

static void CallJsFunction(const v8::FunctionCallbackInfo<v8::Value>& info) {
1420 1421 1422 1423 1424
  v8::Local<v8::Function> function = info[0].As<v8::Function>();
  v8::Local<v8::Value> argv[] = {info[1]};
  function->Call(info.GetIsolate()->GetCurrentContext(), info.This(),
                 arraysize(argv), argv)
      .ToLocalChecked();
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
}

// [Top down]:
//    58     0   (root) #0 1
//     2     2    (program) #0 2
//    56     1    start #16 3
//    55     0      CallJsFunction #0 4
//    55     1        bar #16 5
//    54    54          foo #16 6
TEST(JsNativeJsSample) {
alph's avatar
alph committed
1435
  i::FLAG_allow_natives_syntax = true;
1436
  v8::HandleScope scope(CcTest::isolate());
1437
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
1438
  v8::Context::Scope context_scope(env);
1439 1440

  v8::Local<v8::FunctionTemplate> func_template = v8::FunctionTemplate::New(
1441
      env->GetIsolate(), CallJsFunction);
1442 1443
  v8::Local<v8::Function> func =
      func_template->GetFunction(env).ToLocalChecked();
1444
  func->SetName(v8_str("CallJsFunction"));
1445
  env->Global()->Set(env, v8_str("CallJsFunction"), func).FromJust();
1446

1447
  CompileRun(js_native_js_test_source);
1448
  v8::Local<v8::Function> function = GetFunction(env, "start");
1449

1450 1451
  ProfilerHelper helper(env);
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 1000);
1452 1453

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1454 1455 1456 1457 1458
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  const v8::CpuProfileNode* native_node =
      GetChild(env, start_node, "CallJsFunction");
  const v8::CpuProfileNode* bar_node = GetChild(env, native_node, "bar");
  GetChild(env, bar_node, "foo");
1459

1460
  profile->Delete();
1461 1462 1463
}

static const char* js_native_js_runtime_js_test_source =
alph's avatar
alph committed
1464 1465 1466 1467 1468 1469 1470
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(start);\n"
    "function foo(n) {\n"
    "  var s = 0;\n"
    "  for (var i = 0; i < n; i++) s += i * i * i;\n"
    "  return s;\n"
1471 1472 1473
    "}\n"
    "var bound = foo.bind(this);\n"
    "function bar() {\n"
alph's avatar
alph committed
1474
    "  bound(1000);\n"
1475 1476
    "}\n"
    "function start() {\n"
alph's avatar
alph committed
1477
    "  CallJsFunction(bar);\n"
1478
    "}";
1479 1480 1481 1482 1483 1484 1485 1486 1487

// [Top down]:
//    57     0   (root) #0 1
//    55     1    start #16 3
//    54     0      CallJsFunction #0 4
//    54     3        bar #16 5
//    51    51          foo #16 6
//     2     2    (program) #0 2
TEST(JsNativeJsRuntimeJsSample) {
alph's avatar
alph committed
1488
  i::FLAG_allow_natives_syntax = true;
1489
  v8::HandleScope scope(CcTest::isolate());
1490
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
1491
  v8::Context::Scope context_scope(env);
1492 1493

  v8::Local<v8::FunctionTemplate> func_template = v8::FunctionTemplate::New(
1494
      env->GetIsolate(), CallJsFunction);
1495 1496
  v8::Local<v8::Function> func =
      func_template->GetFunction(env).ToLocalChecked();
1497
  func->SetName(v8_str("CallJsFunction"));
1498
  env->Global()->Set(env, v8_str("CallJsFunction"), func).FromJust();
1499

1500
  CompileRun(js_native_js_runtime_js_test_source);
1501
  ProfilerHelper helper(env);
1502
  v8::Local<v8::Function> function = GetFunction(env, "start");
1503
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 1000);
1504 1505

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1506 1507 1508 1509 1510
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  const v8::CpuProfileNode* native_node =
      GetChild(env, start_node, "CallJsFunction");
  const v8::CpuProfileNode* bar_node = GetChild(env, native_node, "bar");
  GetChild(env, bar_node, "foo");
1511

1512
  profile->Delete();
1513 1514 1515
}

static void CallJsFunction2(const v8::FunctionCallbackInfo<v8::Value>& info) {
1516
  v8::base::OS::Print("In CallJsFunction2\n");
1517 1518 1519 1520
  CallJsFunction(info);
}

static const char* js_native1_js_native2_js_test_source =
alph's avatar
alph committed
1521 1522 1523
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(start);\n"
1524
    "function foo() {\n"
alph's avatar
alph committed
1525 1526 1527
    "  var s = 0;\n"
    "  for (var i = 0; i < 1000; i++) s += i * i * i;\n"
    "  return s;\n"
1528 1529 1530 1531 1532
    "}\n"
    "function bar() {\n"
    "  CallJsFunction2(foo);\n"
    "}\n"
    "function start() {\n"
alph's avatar
alph committed
1533
    "  CallJsFunction1(bar);\n"
1534
    "}";
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544

// [Top down]:
//    57     0   (root) #0 1
//    55     1    start #16 3
//    54     0      CallJsFunction1 #0 4
//    54     0        bar #16 5
//    54     0          CallJsFunction2 #0 6
//    54    54            foo #16 7
//     2     2    (program) #0 2
TEST(JsNative1JsNative2JsSample) {
alph's avatar
alph committed
1545
  i::FLAG_allow_natives_syntax = true;
1546
  v8::HandleScope scope(CcTest::isolate());
1547
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
1548
  v8::Context::Scope context_scope(env);
1549

1550
  v8::Local<v8::Function> func1 =
alph's avatar
alph committed
1551 1552 1553
      v8::FunctionTemplate::New(env->GetIsolate(), CallJsFunction)
          ->GetFunction(env)
          .ToLocalChecked();
1554
  func1->SetName(v8_str("CallJsFunction1"));
1555
  env->Global()->Set(env, v8_str("CallJsFunction1"), func1).FromJust();
1556

1557 1558 1559 1560
  v8::Local<v8::Function> func2 =
      v8::FunctionTemplate::New(env->GetIsolate(), CallJsFunction2)
          ->GetFunction(env)
          .ToLocalChecked();
1561
  func2->SetName(v8_str("CallJsFunction2"));
1562
  env->Global()->Set(env, v8_str("CallJsFunction2"), func2).FromJust();
1563

1564
  CompileRun(js_native1_js_native2_js_test_source);
1565

1566 1567 1568
  ProfilerHelper helper(env);
  v8::Local<v8::Function> function = GetFunction(env, "start");
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 1000);
1569 1570

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1571 1572 1573 1574 1575 1576 1577
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  const v8::CpuProfileNode* native_node1 =
      GetChild(env, start_node, "CallJsFunction1");
  const v8::CpuProfileNode* bar_node = GetChild(env, native_node1, "bar");
  const v8::CpuProfileNode* native_node2 =
      GetChild(env, bar_node, "CallJsFunction2");
  GetChild(env, native_node2, "foo");
1578

1579
  profile->Delete();
1580
}
1581

1582 1583 1584 1585 1586
static const char* js_force_collect_sample_source =
    "function start() {\n"
    "  CallCollectSample();\n"
    "}";

1587
static void CallCollectSample(const v8::FunctionCallbackInfo<v8::Value>& info) {
1588
  v8::CpuProfiler::CollectSample(info.GetIsolate());
1589 1590
}

1591 1592
TEST(CollectSampleAPI) {
  v8::HandleScope scope(CcTest::isolate());
1593
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
  v8::Context::Scope context_scope(env);

  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(env->GetIsolate(), CallCollectSample);
  v8::Local<v8::Function> func =
      func_template->GetFunction(env).ToLocalChecked();
  func->SetName(v8_str("CallCollectSample"));
  env->Global()->Set(env, v8_str("CallCollectSample"), func).FromJust();

  CompileRun(js_force_collect_sample_source);
1604
  ProfilerHelper helper(env);
1605
  v8::Local<v8::Function> function = GetFunction(env, "start");
1606
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 0);
1607 1608

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1609 1610 1611
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  CHECK_LE(1, start_node->GetChildrenCount());
  GetChild(env, start_node, "CallCollectSample");
1612 1613 1614

  profile->Delete();
}
1615

1616
static const char* js_native_js_runtime_multiple_test_source =
alph's avatar
alph committed
1617 1618 1619
    "%NeverOptimizeFunction(foo);\n"
    "%NeverOptimizeFunction(bar);\n"
    "%NeverOptimizeFunction(start);\n"
1620 1621 1622 1623 1624
    "function foo() {\n"
    "  return Math.sin(Math.random());\n"
    "}\n"
    "var bound = foo.bind(this);\n"
    "function bar() {\n"
alph's avatar
alph committed
1625
    "  return bound();\n"
1626 1627
    "}\n"
    "function start() {\n"
alph's avatar
alph committed
1628 1629 1630 1631 1632
    "  startProfiling('my_profile');\n"
    "  var startTime = Date.now();\n"
    "  do {\n"
    "    CallJsFunction(bar);\n"
    "  } while (Date.now() - startTime < 200);\n"
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
    "}";

// The test check multiple entrances/exits between JS and native code.
//
// [Top down]:
//    (root) #0 1
//      start #16 3
//        CallJsFunction #0 4
//          bar #16 5
//            foo #16 6
//      (program) #0 2
TEST(JsNativeJsRuntimeJsSampleMultiple) {
alph's avatar
alph committed
1645
  i::FLAG_allow_natives_syntax = true;
1646
  v8::HandleScope scope(CcTest::isolate());
1647
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
  v8::Context::Scope context_scope(env);

  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(env->GetIsolate(), CallJsFunction);
  v8::Local<v8::Function> func =
      func_template->GetFunction(env).ToLocalChecked();
  func->SetName(v8_str("CallJsFunction"));
  env->Global()->Set(env, v8_str("CallJsFunction"), func).FromJust();

  CompileRun(js_native_js_runtime_multiple_test_source);

1659 1660 1661
  ProfilerHelper helper(env);
  v8::Local<v8::Function> function = GetFunction(env, "start");
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 500, 500);
1662 1663

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
1664 1665 1666 1667 1668
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  const v8::CpuProfileNode* native_node =
      GetChild(env, start_node, "CallJsFunction");
  const v8::CpuProfileNode* bar_node = GetChild(env, native_node, "bar");
  GetChild(env, bar_node, "foo");
1669 1670 1671 1672

  profile->Delete();
}

1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
static const char* inlining_test_source =
    "var finish = false;\n"
    "function action(n) {\n"
    "  var s = 0;\n"
    "  for (var i = 0; i < n; ++i) s += i*i*i;\n"
    "  if (finish)\n"
    "    startProfiling('my_profile');\n"
    "  return s;\n"
    "}\n"
    "function level3() { return action(100); }\n"
    "function level2() { return level3() * 2; }\n"
    "function level1() { return level2(); }\n"
    "function start() {\n"
    "  var n = 100;\n"
    "  while (--n)\n"
    "    level1();\n"
    "  finish = true;\n"
    "  level1();\n"
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
    "}"
    "%PrepareFunctionForOptimization(level1);\n"
    "%PrepareFunctionForOptimization(level2);\n"
    "%PrepareFunctionForOptimization(level3);\n"
    "%NeverOptimizeFunction(action);\n"
    "%NeverOptimizeFunction(start);\n"
    "level1();\n"
    "%OptimizeFunctionOnNextCall(level1);\n"
    "%OptimizeFunctionOnNextCall(level2);\n"
    "%OptimizeFunctionOnNextCall(level3);\n";
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714

// The test check multiple entrances/exits between JS and native code.
//
// [Top down]:
//    (root) #0 1
//      start #16 3
//        level1 #0 4
//          level2 #16 5
//            level3 #16 6
//              action #16 7
//      (program) #0 2
TEST(Inlining) {
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
1715
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
1716
  v8::Context::Scope context_scope(env);
1717
  ProfilerHelper helper(env);
1718 1719 1720 1721 1722

  CompileRun(inlining_test_source);
  v8::Local<v8::Function> function = GetFunction(env, "start");

  v8::Local<v8::String> profile_name = v8_str("my_profile");
1723
  function->Call(env, env->Global(), 0, nullptr).ToLocalChecked();
1724
  v8::CpuProfile* profile = helper.profiler()->StopProfiling(profile_name);
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
  CHECK(profile);
  // Dump collected profile to have a better diagnostic in case of failure.
  reinterpret_cast<i::CpuProfile*>(profile)->Print();

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  const v8::CpuProfileNode* level1_node = GetChild(env, start_node, "level1");
  const v8::CpuProfileNode* level2_node = GetChild(env, level1_node, "level2");
  const v8::CpuProfileNode* level3_node = GetChild(env, level2_node, "level3");
  GetChild(env, level3_node, "action");

  profile->Delete();
}

1739 1740 1741 1742 1743 1744 1745
static const char* inlining_test_source2 = R"(
    function action(n) {
      var s = 0;
      for (var i = 0; i < n; ++i) s += i*i*i;
      return s;
    }
    function level4() {
1746 1747
      action(100);
      return action(100);
1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
    }
    function level3() {
      const a = level4();
      const b = level4();
      return a + b * 1.1;
    }
    function level2() {
      return level3() * 2;
    }
    function level1() {
      action(1);
      action(200);
      action(1);
      return level2();
    }
    function start(n) {
      while (--n)
        level1();
    };
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
    %NeverOptimizeFunction(action);
    %NeverOptimizeFunction(start);
    %PrepareFunctionForOptimization(level1);
    %PrepareFunctionForOptimization(level2);
    %PrepareFunctionForOptimization(level3);
    %PrepareFunctionForOptimization(level4);
    level1();
    level1();
    %OptimizeFunctionOnNextCall(level1);
    %OptimizeFunctionOnNextCall(level2);
    %OptimizeFunctionOnNextCall(level3);
    %OptimizeFunctionOnNextCall(level4);
    level1();
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
  )";

// The simulator builds are extremely slow. We run them with fewer iterations.
#ifdef USE_SIMULATOR
const double load_factor = 0.01;
#else
const double load_factor = 1.0;
#endif

// [Top down]:
//     0  (root):0 0 #1
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
//    13    start:34 6 #3
//              bailed out due to 'Optimization is always disabled'
//    19      level1:36 6 #4
//    16        action:29 6 #14
//                  bailed out due to 'Optimization is always disabled'
//  2748        action:30 6 #10
//                  bailed out due to 'Optimization is always disabled'
//    18        action:31 6 #15
//                  bailed out due to 'Optimization is always disabled'
//     0        level2:32 6 #5
//     0          level3:26 6 #6
//    12            level4:22 6 #11
//  1315              action:17 6 #13
//                        bailed out due to 'Optimization is always disabled'
//  1324              action:18 6 #12
//                        bailed out due to 'Optimization is always disabled'
//    16            level4:21 6 #7
//  1268              action:17 6 #9
//                        bailed out due to 'Optimization is always disabled'
//  1322              action:18 6 #8
//                        bailed out due to 'Optimization is always disabled'
1812 1813
//     2    (program):0 0 #2
TEST(Inlining2) {
1814
  FLAG_allow_natives_syntax = true;
1815 1816 1817
  v8::Isolate* isolate = CcTest::isolate();
  v8::CpuProfiler::UseDetailedSourcePositionsForProfiling(isolate);
  v8::HandleScope scope(isolate);
1818
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
1819 1820 1821 1822 1823 1824 1825
  v8::Context::Scope context_scope(env);

  CompileRun(inlining_test_source2);
  v8::Local<v8::Function> function = GetFunction(env, "start");

  v8::CpuProfiler* profiler = v8::CpuProfiler::New(CcTest::isolate());
  v8::Local<v8::String> profile_name = v8_str("inlining");
1826 1827 1828
  profiler->StartProfiling(
      profile_name,
      CpuProfilingOptions{v8::CpuProfilingMode::kCallerLineNumbers});
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841

  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), 50000 * load_factor)};
  function->Call(env, env->Global(), arraysize(args), args).ToLocalChecked();
  v8::CpuProfile* profile = profiler->StopProfiling(profile_name);
  CHECK(profile);

  // Dump collected profile to have a better diagnostic in case of failure.
  reinterpret_cast<i::CpuProfile*>(profile)->Print();

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");

1842 1843 1844 1845 1846
  NameLinePair l421_a17[] = {{"level1", 27},
                             {"level2", 23},
                             {"level3", 17},
                             {"level4", 12},
                             {"action", 8}};
1847
  CheckBranch(start_node, l421_a17, arraysize(l421_a17));
1848 1849 1850 1851 1852
  NameLinePair l422_a17[] = {{"level1", 27},
                             {"level2", 23},
                             {"level3", 17},
                             {"level4", 13},
                             {"action", 8}};
1853 1854
  CheckBranch(start_node, l422_a17, arraysize(l422_a17));

1855 1856 1857 1858 1859
  NameLinePair l421_a18[] = {{"level1", 27},
                             {"level2", 23},
                             {"level3", 17},
                             {"level4", 12},
                             {"action", 9}};
1860
  CheckBranch(start_node, l421_a18, arraysize(l421_a18));
1861 1862 1863 1864 1865
  NameLinePair l422_a18[] = {{"level1", 27},
                             {"level2", 23},
                             {"level3", 17},
                             {"level4", 13},
                             {"action", 9}};
1866 1867
  CheckBranch(start_node, l422_a18, arraysize(l422_a18));

1868
  NameLinePair action_direct[] = {{"level1", 27}, {"action", 21}};
1869 1870 1871 1872 1873 1874
  CheckBranch(start_node, action_direct, arraysize(action_direct));

  profile->Delete();
  profiler->Dispose();
}

1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
static const char* cross_script_source_a = R"(





    %NeverOptimizeFunction(action);
    function action(n) {
      var s = 0;
      for (var i = 0; i < n; ++i) s += i*i*i;
      return s;
    }
    function level1() {
      const a = action(1);
      const b = action(200);
      const c = action(1);
      return a + b + c;
    }
  )";

static const char* cross_script_source_b = R"(
    %PrepareFunctionForOptimization(start);
    %PrepareFunctionForOptimization(level1);
    start(1);
    start(1);
    %OptimizeFunctionOnNextCall(start);
    %OptimizeFunctionOnNextCall(level1);
    start(1);
    function start(n) {
      while (--n)
        level1();
    };
  )";

TEST(CrossScriptInliningCallerLineNumbers) {
  i::FLAG_allow_natives_syntax = true;
1911 1912 1913
  v8::Isolate* isolate = CcTest::isolate();
  v8::CpuProfiler::UseDetailedSourcePositionsForProfiling(isolate);
  v8::HandleScope scope(isolate);
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
  v8::Context::Scope context_scope(env);

  v8::Local<v8::Script> script_a =
      CompileWithOrigin(cross_script_source_a, "script_a", false);
  v8::Local<v8::Script> script_b =
      CompileWithOrigin(cross_script_source_b, "script_b", false);

  script_a->Run(env).ToLocalChecked();
  script_b->Run(env).ToLocalChecked();

  v8::Local<v8::Function> function = GetFunction(env, "start");

  v8::CpuProfiler* profiler = v8::CpuProfiler::New(CcTest::isolate());
  v8::Local<v8::String> profile_name = v8_str("inlining");
  profiler->StartProfiling(profile_name,
                           v8::CpuProfilingMode::kCallerLineNumbers);

  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), 20000 * load_factor)};
  function->Call(env, env->Global(), arraysize(args), args).ToLocalChecked();
  v8::CpuProfile* profile = profiler->StopProfiling(profile_name);
  CHECK(profile);

  // Dump collected profile to have a better diagnostic in case of failure.
  reinterpret_cast<i::CpuProfile*>(profile)->Print();

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  CHECK_EQ(0, strcmp("script_b", start_node->GetScriptResourceNameStr()));

  NameLinePair l19_a10[] = {{"level1", 11}, {"action", 15}};
  CheckBranch(start_node, l19_a10, arraysize(l19_a10));

  const v8::CpuProfileNode* level1_node = GetChild(env, start_node, "level1");
  CHECK_EQ(0, strcmp("script_a", level1_node->GetScriptResourceNameStr()));

  const v8::CpuProfileNode* action_node = GetChild(env, level1_node, "action");
  CHECK_EQ(0, strcmp("script_a", action_node->GetScriptResourceNameStr()));

  profile->Delete();
  profiler->Dispose();
}

static const char* cross_script_source_c = R"(
    function level3() {
      const a = action(1);
      const b = action(100);
      const c = action(1);
      return a + b + c;
    }
    %NeverOptimizeFunction(action);
    function action(n) {
      var s = 0;
      for (var i = 0; i < n; ++i) s += i*i*i;
      return s;
    }
  )";

static const char* cross_script_source_d = R"(
    function level2() {
      const p = level3();
      const q = level3();
      return p + q;
    }
  )";

static const char* cross_script_source_e = R"(
    function level1() {
      return level2() + 1000;
    }
  )";

static const char* cross_script_source_f = R"(
    %PrepareFunctionForOptimization(start);
    %PrepareFunctionForOptimization(level1);
    %PrepareFunctionForOptimization(level2);
    %PrepareFunctionForOptimization(level3);
    start(1);
    start(1);
    %OptimizeFunctionOnNextCall(start);
    %OptimizeFunctionOnNextCall(level1);
    %OptimizeFunctionOnNextCall(level2);
    %OptimizeFunctionOnNextCall(level3);
    start(1);
    function start(n) {
      while (--n)
        level1();
    };
  )";

TEST(CrossScriptInliningCallerLineNumbers2) {
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
  v8::Context::Scope context_scope(env);

  v8::Local<v8::Script> script_c =
      CompileWithOrigin(cross_script_source_c, "script_c", false);
  v8::Local<v8::Script> script_d =
      CompileWithOrigin(cross_script_source_d, "script_d", false);
  v8::Local<v8::Script> script_e =
      CompileWithOrigin(cross_script_source_e, "script_e", false);
  v8::Local<v8::Script> script_f =
      CompileWithOrigin(cross_script_source_f, "script_f", false);

  script_c->Run(env).ToLocalChecked();
  script_d->Run(env).ToLocalChecked();
  script_e->Run(env).ToLocalChecked();
  script_f->Run(env).ToLocalChecked();

  v8::Local<v8::Function> function = GetFunction(env, "start");

  v8::CpuProfiler* profiler = v8::CpuProfiler::New(CcTest::isolate());
  v8::Local<v8::String> profile_name = v8_str("inlining");
  profiler->StartProfiling(profile_name,
                           v8::CpuProfilingMode::kCallerLineNumbers);

  v8::Local<v8::Value> args[] = {
      v8::Integer::New(env->GetIsolate(), 20000 * load_factor)};
  function->Call(env, env->Global(), arraysize(args), args).ToLocalChecked();
  v8::CpuProfile* profile = profiler->StopProfiling(profile_name);
  CHECK(profile);

  // Dump collected profile to have a better diagnostic in case of failure.
  reinterpret_cast<i::CpuProfile*>(profile)->Print();

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* start_node = GetChild(env, root, "start");
  CHECK_EQ(0, strcmp("script_f", start_node->GetScriptResourceNameStr()));

  const v8::CpuProfileNode* level1_node = GetChild(env, start_node, "level1");
  CHECK_EQ(0, strcmp("script_e", level1_node->GetScriptResourceNameStr()));

  const v8::CpuProfileNode* level2_node = GetChild(env, level1_node, "level2");
  CHECK_EQ(0, strcmp("script_d", level2_node->GetScriptResourceNameStr()));

  const v8::CpuProfileNode* level3_node = GetChild(env, level2_node, "level3");
  CHECK_EQ(0, strcmp("script_c", level3_node->GetScriptResourceNameStr()));

  const v8::CpuProfileNode* action_node = GetChild(env, level3_node, "action");
  CHECK_EQ(0, strcmp("script_c", action_node->GetScriptResourceNameStr()));

  profile->Delete();
  profiler->Dispose();
}

2061
// [Top down]:
2062 2063 2064
//     0   (root) #0 1
//     2    (program) #0 2
//     3    (idle) #0 3
2065 2066 2067
TEST(IdleTime) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
2068
  v8::CpuProfiler* cpu_profiler = v8::CpuProfiler::New(env->GetIsolate());
2069

2070
  v8::Local<v8::String> profile_name = v8_str("my_profile");
2071
  cpu_profiler->StartProfiling(profile_name);
2072

2073
  i::Isolate* isolate = CcTest::i_isolate();
2074 2075
  i::ProfilerEventsProcessor* processor =
      reinterpret_cast<i::CpuProfiler*>(cpu_profiler)->processor();
2076

2077
  processor->AddCurrentStack(true);
2078
  isolate->SetIdle(true);
2079
  for (int i = 0; i < 3; i++) {
2080
    processor->AddCurrentStack(true);
2081
  }
2082
  isolate->SetIdle(false);
2083
  processor->AddCurrentStack(true);
2084

2085
  v8::CpuProfile* profile = cpu_profiler->StopProfiling(profile_name);
2086
  CHECK(profile);
2087
  // Dump collected profile to have a better diagnostic in case of failure.
2088
  reinterpret_cast<i::CpuProfile*>(profile)->Print();
2089 2090

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
alph's avatar
alph committed
2091
  const v8::CpuProfileNode* program_node =
lpy's avatar
lpy committed
2092
      GetChild(env.local(), root, CodeEntry::kProgramEntryName);
alph's avatar
alph committed
2093 2094
  CHECK_EQ(0, program_node->GetChildrenCount());
  CHECK_GE(program_node->GetHitCount(), 2u);
2095

alph's avatar
alph committed
2096
  const v8::CpuProfileNode* idle_node =
lpy's avatar
lpy committed
2097
      GetChild(env.local(), root, CodeEntry::kIdleEntryName);
alph's avatar
alph committed
2098 2099
  CHECK_EQ(0, idle_node->GetChildrenCount());
  CHECK_GE(idle_node->GetHitCount(), 3u);
2100

2101
  profile->Delete();
2102
  cpu_profiler->Dispose();
2103
}
2104

2105 2106 2107
static void CheckFunctionDetails(v8::Isolate* isolate,
                                 const v8::CpuProfileNode* node,
                                 const char* name, const char* script_name,
2108
                                 bool is_shared_cross_origin, int script_id,
2109 2110
                                 int line, int column,
                                 const v8::CpuProfileNode* parent) {
2111 2112
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
  CHECK(v8_str(name)->Equals(context, node->GetFunctionName()).FromJust());
2113
  CHECK_EQ(0, strcmp(name, node->GetFunctionNameStr()));
2114 2115 2116
  CHECK(v8_str(script_name)
            ->Equals(context, node->GetScriptResourceName())
            .FromJust());
2117
  CHECK_EQ(0, strcmp(script_name, node->GetScriptResourceNameStr()));
2118 2119 2120
  CHECK_EQ(script_id, node->GetScriptId());
  CHECK_EQ(line, node->GetLineNumber());
  CHECK_EQ(column, node->GetColumnNumber());
2121
  CHECK_EQ(parent, node->GetParent());
2122
  CHECK_EQ(v8::CpuProfileNode::kScript, node->GetSourceType());
2123 2124 2125
}

TEST(FunctionDetails) {
alph's avatar
alph committed
2126
  i::FLAG_allow_natives_syntax = true;
2127
  v8::HandleScope scope(CcTest::isolate());
2128
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
2129
  v8::Context::Scope context_scope(env);
2130
  ProfilerHelper helper(env);
2131

2132
  v8::Local<v8::Script> script_a = CompileWithOrigin(
alph's avatar
alph committed
2133 2134 2135
      "%NeverOptimizeFunction(foo);\n"
      "%NeverOptimizeFunction(bar);\n"
      "    function foo\n() { bar(); }\n"
2136
      " function bar() { startProfiling(); }\n",
2137
      "script_a", false);
2138 2139
  script_a->Run(env).ToLocalChecked();
  v8::Local<v8::Script> script_b = CompileWithOrigin(
alph's avatar
alph committed
2140 2141
      "%NeverOptimizeFunction(baz);"
      "\n\n   function baz() { foo(); }\n"
2142 2143
      "\n\nbaz();\n"
      "stopProfiling();\n",
2144
      "script_b", true);
2145
  script_b->Run(env).ToLocalChecked();
2146
  const v8::CpuProfile* profile = i::ProfilerExtension::last_profile;
2147 2148 2149 2150 2151
  const v8::CpuProfileNode* current = profile->GetTopDownRoot();
  reinterpret_cast<ProfileNode*>(
      const_cast<v8::CpuProfileNode*>(current))->Print(0);
  // The tree should look like this:
  //  0   (root) 0 #1
2152
  //  0    "" 19 #2 no reason script_b:1
2153 2154 2155 2156
  //  0      baz 19 #3 TryCatchStatement script_b:3
  //  0        foo 18 #4 TryCatchStatement script_a:2
  //  1          bar 18 #5 no reason script_a:3
  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
2157
  CHECK_EQ(root->GetParent(), nullptr);
2158
  const v8::CpuProfileNode* script = GetChild(env, root, "");
2159
  CheckFunctionDetails(env->GetIsolate(), script, "", "script_b", true,
2160
                       script_b->GetUnboundScript()->GetId(), 1, 1, root);
2161
  const v8::CpuProfileNode* baz = GetChild(env, script, "baz");
2162
  CheckFunctionDetails(env->GetIsolate(), baz, "baz", "script_b", true,
2163
                       script_b->GetUnboundScript()->GetId(), 3, 16, script);
2164
  const v8::CpuProfileNode* foo = GetChild(env, baz, "foo");
2165
  CheckFunctionDetails(env->GetIsolate(), foo, "foo", "script_a", false,
2166
                       script_a->GetUnboundScript()->GetId(), 4, 1, baz);
2167
  const v8::CpuProfileNode* bar = GetChild(env, foo, "bar");
2168
  CheckFunctionDetails(env->GetIsolate(), bar, "bar", "script_a", false,
2169
                       script_a->GetUnboundScript()->GetId(), 5, 14, foo);
2170
}
2171

2172 2173 2174 2175
TEST(FunctionDetailsInlining) {
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
2176
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
  v8::Context::Scope context_scope(env);
  ProfilerHelper helper(env);

  // alpha is in a_script, beta in b_script. beta is
  // inlined in alpha, but it should be attributed to b_script.

  v8::Local<v8::Script> script_b = CompileWithOrigin(
      "function beta(k) {\n"
      "  let sum = 2;\n"
      "  for(let i = 0; i < k; i ++) {\n"
      "    sum += i;\n"
      "    sum = sum + 'a';\n"
      "  }\n"
      "  return sum;\n"
      "}\n"
      "\n",
2193
      "script_b", true);
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204

  v8::Local<v8::Script> script_a = CompileWithOrigin(
      "function alpha(p) {\n"
      "  let res = beta(p);\n"
      "  res = res + res;\n"
      "  return res;\n"
      "}\n"
      "let p = 2;\n"
      "\n"
      "\n"
      "// Warm up before profiling or the inlining doesn't happen.\n"
2205
      "%PrepareFunctionForOptimization(alpha);\n"
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
      "p = alpha(p);\n"
      "p = alpha(p);\n"
      "%OptimizeFunctionOnNextCall(alpha);\n"
      "p = alpha(p);\n"
      "\n"
      "\n"
      "startProfiling();\n"
      "for(let i = 0; i < 10000; i++) {\n"
      "  p = alpha(p);\n"
      "}\n"
      "stopProfiling();\n"
      "\n"
      "\n",
2219
      "script_a", false);
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238

  script_b->Run(env).ToLocalChecked();
  script_a->Run(env).ToLocalChecked();

  const v8::CpuProfile* profile = i::ProfilerExtension::last_profile;
  const v8::CpuProfileNode* current = profile->GetTopDownRoot();
  reinterpret_cast<ProfileNode*>(const_cast<v8::CpuProfileNode*>(current))
      ->Print(0);
  //   The tree should look like this:
  //  0  (root) 0 #1
  //  5    (program) 0 #6
  //  2     14 #2 script_a:1
  //    ;;; deopted at script_id: 14 position: 299 with reason 'Insufficient
  //    type feedback for call'.
  //  1      alpha 14 #4 script_a:1
  //  9        beta 13 #5 script_b:0
  //  0      startProfiling 0 #3

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
2239
  CHECK_EQ(root->GetParent(), nullptr);
2240
  const v8::CpuProfileNode* script = GetChild(env, root, "");
2241
  CheckFunctionDetails(env->GetIsolate(), script, "", "script_a", false,
2242
                       script_a->GetUnboundScript()->GetId(), 1, 1, root);
2243 2244 2245
  const v8::CpuProfileNode* alpha = FindChild(env, script, "alpha");
  // Return early if profiling didn't sample alpha.
  if (!alpha) return;
2246
  CheckFunctionDetails(env->GetIsolate(), alpha, "alpha", "script_a", false,
2247
                       script_a->GetUnboundScript()->GetId(), 1, 15, script);
2248 2249
  const v8::CpuProfileNode* beta = FindChild(env, alpha, "beta");
  if (!beta) return;
2250
  CheckFunctionDetails(env->GetIsolate(), beta, "beta", "script_b", true,
2251
                       script_b->GetUnboundScript()->GetId(), 1, 14, alpha);
2252
}
2253 2254

TEST(DontStopOnFinishedProfileDelete) {
2255
  v8::HandleScope scope(CcTest::isolate());
2256
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
2257
  v8::Context::Scope context_scope(env);
2258

2259
  v8::CpuProfiler* profiler = v8::CpuProfiler::New(env->GetIsolate());
2260
  i::CpuProfiler* iprofiler = reinterpret_cast<i::CpuProfiler*>(profiler);
2261

2262
  CHECK_EQ(0, iprofiler->GetProfilesCount());
2263
  v8::Local<v8::String> outer = v8_str("outer");
2264
  profiler->StartProfiling(outer);
2265
  CHECK_EQ(0, iprofiler->GetProfilesCount());
2266

2267
  v8::Local<v8::String> inner = v8_str("inner");
2268
  profiler->StartProfiling(inner);
2269
  CHECK_EQ(0, iprofiler->GetProfilesCount());
2270

2271
  v8::CpuProfile* inner_profile = profiler->StopProfiling(inner);
2272
  CHECK(inner_profile);
2273
  CHECK_EQ(1, iprofiler->GetProfilesCount());
2274
  inner_profile->Delete();
2275
  inner_profile = nullptr;
2276
  CHECK_EQ(0, iprofiler->GetProfilesCount());
2277

2278
  v8::CpuProfile* outer_profile = profiler->StopProfiling(outer);
2279
  CHECK(outer_profile);
2280
  CHECK_EQ(1, iprofiler->GetProfilesCount());
2281
  outer_profile->Delete();
2282
  outer_profile = nullptr;
2283
  CHECK_EQ(0, iprofiler->GetProfilesCount());
2284
  profiler->Dispose();
2285
}
2286 2287


2288 2289
const char* GetBranchDeoptReason(v8::Local<v8::Context> context,
                                 i::CpuProfile* iprofile, const char* branch[],
2290 2291
                                 int length) {
  v8::CpuProfile* profile = reinterpret_cast<v8::CpuProfile*>(iprofile);
2292
  const ProfileNode* iopt_function = nullptr;
2293
  iopt_function = GetSimpleBranch(context, profile, branch, length);
2294
  CHECK_EQ(1U, iopt_function->deopt_infos().size());
2295 2296 2297 2298
  return iopt_function->deopt_infos()[0].deopt_reason;
}


loislo's avatar
loislo committed
2299
// deopt at top function
2300
TEST(CollectDeoptEvents) {
Mythri's avatar
Mythri committed
2301
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
2302 2303
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
2304
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
2305
  v8::Context::Scope context_scope(env);
2306 2307 2308
  ProfilerHelper helper(env);
  i::CpuProfiler* iprofiler =
      reinterpret_cast<i::CpuProfiler*>(helper.profiler());
2309

2310 2311 2312
  const char opt_source[] =
      "function opt_function%d(value, depth) {\n"
      "  if (depth) return opt_function%d(value, depth - 1);\n"
loislo's avatar
loislo committed
2313
      "\n"
2314
      "  return  10 / value;\n"
loislo's avatar
loislo committed
2315
      "}\n"
2316 2317 2318 2319 2320
      "\n";

  for (int i = 0; i < 3; ++i) {
    i::EmbeddedVector<char, sizeof(opt_source) + 100> buffer;
    i::SNPrintF(buffer, opt_source, i, i);
2321
    v8::Script::Compile(env, v8_str(buffer.begin()))
2322 2323 2324
        .ToLocalChecked()
        ->Run(env)
        .ToLocalChecked();
2325 2326 2327 2328
  }

  const char* source =
      "startProfiling();\n"
loislo's avatar
loislo committed
2329
      "\n"
2330 2331
      "%PrepareFunctionForOptimization(opt_function0);\n"
      "\n"
2332
      "opt_function0(1, 1);\n"
loislo's avatar
loislo committed
2333
      "\n"
2334 2335 2336 2337 2338
      "%OptimizeFunctionOnNextCall(opt_function0)\n"
      "\n"
      "opt_function0(1, 1);\n"
      "\n"
      "opt_function0(undefined, 1);\n"
loislo's avatar
loislo committed
2339
      "\n"
2340 2341
      "%PrepareFunctionForOptimization(opt_function1);\n"
      "\n"
2342
      "opt_function1(1, 1);\n"
loislo's avatar
loislo committed
2343
      "\n"
2344
      "%OptimizeFunctionOnNextCall(opt_function1)\n"
loislo's avatar
loislo committed
2345
      "\n"
2346
      "opt_function1(1, 1);\n"
loislo's avatar
loislo committed
2347
      "\n"
2348
      "opt_function1(NaN, 1);\n"
loislo's avatar
loislo committed
2349
      "\n"
2350 2351
      "%PrepareFunctionForOptimization(opt_function2);\n"
      "\n"
2352
      "opt_function2(1, 1);\n"
loislo's avatar
loislo committed
2353
      "\n"
2354
      "%OptimizeFunctionOnNextCall(opt_function2)\n"
loislo's avatar
loislo committed
2355
      "\n"
2356 2357 2358
      "opt_function2(1, 1);\n"
      "\n"
      "opt_function2(0, 1);\n"
loislo's avatar
loislo committed
2359 2360 2361 2362
      "\n"
      "stopProfiling();\n"
      "\n";

2363 2364 2365 2366
  v8::Script::Compile(env, v8_str(source))
      .ToLocalChecked()
      ->Run(env)
      .ToLocalChecked();
2367 2368
  i::CpuProfile* iprofile = iprofiler->GetProfile(0);
  iprofile->Print();
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
  /* The expected profile
  [Top down]:
      0  (root) 0 #1
     23     32 #2
      1      opt_function2 31 #7
      1        opt_function2 31 #8
                  ;;; deopted at script_id: 31 position: 106 with reason
  'division by zero'.
      2      opt_function0 29 #3
      4        opt_function0 29 #4
                  ;;; deopted at script_id: 29 position: 108 with reason 'not a
  heap number'.
      0      opt_function1 30 #5
      1        opt_function1 30 #6
                  ;;; deopted at script_id: 30 position: 108 with reason 'lost
  precision or NaN'.
  */

2387 2388
  {
    const char* branch[] = {"", "opt_function0", "opt_function0"};
2389 2390 2391 2392
    const char* deopt_reason =
        GetBranchDeoptReason(env, iprofile, branch, arraysize(branch));
    if (deopt_reason != reason(i::DeoptimizeReason::kNotAHeapNumber) &&
        deopt_reason != reason(i::DeoptimizeReason::kNotASmi)) {
2393
      FATAL("%s", deopt_reason);
2394
    }
2395 2396 2397
  }
  {
    const char* branch[] = {"", "opt_function1", "opt_function1"};
2398
    const char* deopt_reason =
2399
        GetBranchDeoptReason(env, iprofile, branch, arraysize(branch));
2400
    if (deopt_reason != reason(i::DeoptimizeReason::kNaN) &&
2401 2402
        deopt_reason != reason(i::DeoptimizeReason::kLostPrecisionOrNaN) &&
        deopt_reason != reason(i::DeoptimizeReason::kNotASmi)) {
2403
      FATAL("%s", deopt_reason);
2404
    }
2405 2406 2407
  }
  {
    const char* branch[] = {"", "opt_function2", "opt_function2"};
2408
    CHECK_EQ(reason(i::DeoptimizeReason::kDivisionByZero),
2409
             GetBranchDeoptReason(env, iprofile, branch, arraysize(branch)));
2410
  }
2411 2412
  iprofiler->DeleteProfile(iprofile);
}
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425


TEST(SourceLocation) {
  i::FLAG_always_opt = true;
  LocalContext env;
  v8::HandleScope scope(CcTest::isolate());

  const char* source =
      "function CompareStatementWithThis() {\n"
      "  if (this === 1) {}\n"
      "}\n"
      "CompareStatementWithThis();\n";

2426 2427 2428 2429
  v8::Script::Compile(env.local(), v8_str(source))
      .ToLocalChecked()
      ->Run(env.local())
      .ToLocalChecked();
2430
}
2431 2432

static const char* inlined_source =
2433 2434
    "function opt_function(left, right) { var k = left*right; return k + 1; "
    "}\n";
2435 2436 2437 2438 2439
//   0.........1.........2.........3.........4....*....5.........6......*..7


// deopt at the first level inlined function
TEST(DeoptAtFirstLevelInlinedSource) {
Mythri's avatar
Mythri committed
2440
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
2441 2442
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
2443
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
2444
  v8::Context::Scope context_scope(env);
2445 2446 2447
  ProfilerHelper helper(env);
  i::CpuProfiler* iprofiler =
      reinterpret_cast<i::CpuProfiler*>(helper.profiler());
2448 2449 2450

  //   0.........1.........2.........3.........4.........5.........6.........7
  const char* source =
2451
      "function test(left, right) { return opt_function(left, right); }\n"
2452 2453 2454
      "\n"
      "startProfiling();\n"
      "\n"
2455
      "%EnsureFeedbackVectorForFunction(opt_function);\n"
2456 2457
      "%PrepareFunctionForOptimization(test);\n"
      "\n"
2458
      "test(10, 10);\n"
2459 2460 2461
      "\n"
      "%OptimizeFunctionOnNextCall(test)\n"
      "\n"
2462 2463 2464
      "test(10, 10);\n"
      "\n"
      "test(undefined, 1e9);\n"
2465 2466 2467 2468
      "\n"
      "stopProfiling();\n"
      "\n";

2469 2470
  v8::Local<v8::Script> inlined_script = v8_compile(inlined_source);
  inlined_script->Run(env).ToLocalChecked();
2471 2472
  int inlined_script_id = inlined_script->GetUnboundScript()->GetId();

2473 2474
  v8::Local<v8::Script> script = v8_compile(source);
  script->Run(env).ToLocalChecked();
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
  int script_id = script->GetUnboundScript()->GetId();

  i::CpuProfile* iprofile = iprofiler->GetProfile(0);
  iprofile->Print();
  /* The expected profile output
  [Top down]:
      0  (root) 0 #1
     10     30 #2
      1      test 30 #3
                ;;; deopted at script_id: 29 position: 45 with reason 'not a
  heap number'.
                ;;;     Inline point: script_id 30 position: 36.
      4        opt_function 29 #4
  */
  v8::CpuProfile* profile = reinterpret_cast<v8::CpuProfile*>(iprofile);

  const char* branch[] = {"", "test"};
  const ProfileNode* itest_node =
2493
      GetSimpleBranch(env, profile, branch, arraysize(branch));
2494 2495
  const std::vector<v8::CpuProfileDeoptInfo>& deopt_infos =
      itest_node->deopt_infos();
2496
  CHECK_EQ(1U, deopt_infos.size());
2497

2498
  const v8::CpuProfileDeoptInfo& info = deopt_infos[0];
2499 2500
  CHECK(reason(i::DeoptimizeReason::kNotASmi) == info.deopt_reason ||
        reason(i::DeoptimizeReason::kNotAHeapNumber) == info.deopt_reason);
2501
  CHECK_EQ(2U, info.stack.size());
2502
  CHECK_EQ(inlined_script_id, info.stack[0].script_id);
2503
  CHECK_LE(dist(offset(inlined_source, "*right"), info.stack[0].position), 1);
2504
  CHECK_EQ(script_id, info.stack[1].script_id);
2505
  CHECK_EQ(offset(source, "opt_function(left,"), info.stack[1].position);
2506 2507 2508 2509 2510 2511

  iprofiler->DeleteProfile(iprofile);
}

// deopt at the second level inlined function
TEST(DeoptAtSecondLevelInlinedSource) {
Mythri's avatar
Mythri committed
2512
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
2513 2514
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
2515
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
2516
  v8::Context::Scope context_scope(env);
2517 2518 2519
  ProfilerHelper helper(env);
  i::CpuProfiler* iprofiler =
      reinterpret_cast<i::CpuProfiler*>(helper.profiler());
2520 2521 2522

  //   0.........1.........2.........3.........4.........5.........6.........7
  const char* source =
2523 2524
      "function test2(left, right) { return opt_function(left, right); }\n"
      "function test1(left, right) { return test2(left, right); } \n"
2525 2526 2527
      "\n"
      "startProfiling();\n"
      "\n"
2528 2529
      "%EnsureFeedbackVectorForFunction(opt_function);\n"
      "%EnsureFeedbackVectorForFunction(test2);\n"
2530 2531
      "%PrepareFunctionForOptimization(test1);\n"
      "\n"
2532
      "test1(10, 10);\n"
2533 2534 2535
      "\n"
      "%OptimizeFunctionOnNextCall(test1)\n"
      "\n"
2536
      "test1(10, 10);\n"
2537
      "\n"
2538
      "test1(undefined, 1e9);\n"
2539 2540 2541 2542
      "\n"
      "stopProfiling();\n"
      "\n";

2543 2544
  v8::Local<v8::Script> inlined_script = v8_compile(inlined_source);
  inlined_script->Run(env).ToLocalChecked();
2545 2546
  int inlined_script_id = inlined_script->GetUnboundScript()->GetId();

2547 2548
  v8::Local<v8::Script> script = v8_compile(source);
  script->Run(env).ToLocalChecked();
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
  int script_id = script->GetUnboundScript()->GetId();

  i::CpuProfile* iprofile = iprofiler->GetProfile(0);
  iprofile->Print();
  /* The expected profile output
  [Top down]:
      0  (root) 0 #1
     11     30 #2
      1      test1 30 #3
                ;;; deopted at script_id: 29 position: 45 with reason 'not a
  heap number'.
                ;;;     Inline point: script_id 30 position: 37.
                ;;;     Inline point: script_id 30 position: 103.
      1        test2 30 #4
      3          opt_function 29 #5
  */

  v8::CpuProfile* profile = reinterpret_cast<v8::CpuProfile*>(iprofile);

  const char* branch[] = {"", "test1"};
  const ProfileNode* itest_node =
2570
      GetSimpleBranch(env, profile, branch, arraysize(branch));
2571 2572
  const std::vector<v8::CpuProfileDeoptInfo>& deopt_infos =
      itest_node->deopt_infos();
2573
  CHECK_EQ(1U, deopt_infos.size());
2574

2575
  const v8::CpuProfileDeoptInfo info = deopt_infos[0];
2576 2577
  CHECK(reason(i::DeoptimizeReason::kNotASmi) == info.deopt_reason ||
        reason(i::DeoptimizeReason::kNotAHeapNumber) == info.deopt_reason);
2578
  CHECK_EQ(3U, info.stack.size());
2579
  CHECK_EQ(inlined_script_id, info.stack[0].script_id);
2580
  CHECK_LE(dist(offset(inlined_source, "*right"), info.stack[0].position), 1);
2581
  CHECK_EQ(script_id, info.stack[1].script_id);
2582 2583
  CHECK_EQ(offset(source, "opt_function(left,"), info.stack[1].position);
  CHECK_EQ(offset(source, "test2(left, right);"), info.stack[2].position);
2584 2585 2586 2587 2588 2589 2590

  iprofiler->DeleteProfile(iprofile);
}


// deopt in untracked function
TEST(DeoptUntrackedFunction) {
Mythri's avatar
Mythri committed
2591
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
2592 2593
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(CcTest::isolate());
2594
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
2595
  v8::Context::Scope context_scope(env);
2596 2597 2598
  ProfilerHelper helper(env);
  i::CpuProfiler* iprofiler =
      reinterpret_cast<i::CpuProfiler*>(helper.profiler());
2599 2600 2601 2602 2603

  //   0.........1.........2.........3.........4.........5.........6.........7
  const char* source =
      "function test(left, right) { return opt_function(left, right); }\n"
      "\n"
2604
      "%EnsureFeedbackVectorForFunction(opt_function);"
2605 2606
      "%PrepareFunctionForOptimization(test);\n"
      "\n"
2607
      "test(10, 10);\n"
2608 2609 2610
      "\n"
      "%OptimizeFunctionOnNextCall(test)\n"
      "\n"
2611
      "test(10, 10);\n"
2612 2613 2614
      "\n"
      "startProfiling();\n"  // profiler started after compilation.
      "\n"
2615
      "test(undefined, 10);\n"
2616 2617 2618 2619
      "\n"
      "stopProfiling();\n"
      "\n";

2620 2621
  v8::Local<v8::Script> inlined_script = v8_compile(inlined_source);
  inlined_script->Run(env).ToLocalChecked();
2622

2623 2624
  v8::Local<v8::Script> script = v8_compile(source);
  script->Run(env).ToLocalChecked();
2625 2626 2627 2628 2629 2630 2631

  i::CpuProfile* iprofile = iprofiler->GetProfile(0);
  iprofile->Print();
  v8::CpuProfile* profile = reinterpret_cast<v8::CpuProfile*>(iprofile);

  const char* branch[] = {"", "test"};
  const ProfileNode* itest_node =
2632
      GetSimpleBranch(env, profile, branch, arraysize(branch));
2633
  CHECK_EQ(0U, itest_node->deopt_infos().size());
2634 2635 2636

  iprofiler->DeleteProfile(iprofile);
}
2637 2638 2639 2640 2641 2642 2643

using v8::platform::tracing::TraceBuffer;
using v8::platform::tracing::TraceConfig;
using v8::platform::tracing::TraceObject;

namespace {

2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678
#ifdef V8_USE_PERFETTO

class CpuProfilerListener : public platform::tracing::TraceEventListener {
 public:
  void ProcessPacket(const ::perfetto::protos::TracePacket& packet) {
    for (const ::perfetto::protos::ChromeTraceEvent& trace_event :
         packet.chrome_events().trace_events()) {
      if (trace_event.name() != std::string("Profile") &&
          trace_event.name() != std::string("ProfileChunk"))
        return;
      CHECK(!profile_id_ || trace_event.id() == profile_id_);
      CHECK_EQ(1, trace_event.args_size());
      CHECK(trace_event.args()[0].has_json_value());
      profile_id_ = trace_event.id();
      result_json_ += result_json_.empty() ? "[" : ",\n";
      result_json_ += trace_event.args()[0].json_value();
    }
  }

  const std::string& result_json() {
    result_json_ += "]";
    return result_json_;
  }
  void Reset() {
    result_json_.clear();
    profile_id_ = 0;
  }

 private:
  std::string result_json_;
  uint64_t profile_id_ = 0;
};

#else

2679 2680 2681
class CpuProfileEventChecker : public v8::platform::tracing::TraceWriter {
 public:
  void AppendTraceEvent(TraceObject* trace_event) override {
2682 2683
    if (trace_event->name() != std::string("Profile") &&
        trace_event->name() != std::string("ProfileChunk"))
2684 2685 2686 2687 2688 2689 2690
      return;
    CHECK(!profile_id_ || trace_event->id() == profile_id_);
    CHECK_EQ(1, trace_event->num_args());
    CHECK_EQ(TRACE_VALUE_TYPE_CONVERTABLE, trace_event->arg_types()[0]);
    profile_id_ = trace_event->id();
    v8::ConvertableToTraceFormat* arg =
        trace_event->arg_convertables()[0].get();
2691
    result_json_ += result_json_.empty() ? "[" : ",\n";
2692 2693
    arg->AppendAsTraceFormat(&result_json_);
  }
2694
  void Flush() override { result_json_ += "]"; }
2695

2696 2697 2698 2699 2700
  const std::string& result_json() const { return result_json_; }
  void Reset() {
    result_json_.clear();
    profile_id_ = 0;
  }
2701 2702 2703 2704 2705 2706

 private:
  std::string result_json_;
  uint64_t profile_id_ = 0;
};

2707 2708
#endif  // !V8_USE_PERFETTO

2709 2710 2711
}  // namespace

TEST(TracingCpuProfiler) {
2712 2713 2714
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
  v8::Context::Scope context_scope(env);
2715

2716 2717 2718
  auto* tracing_controller =
      static_cast<v8::platform::tracing::TracingController*>(
          i::V8::GetCurrentPlatform()->GetTracingController());
2719

2720 2721 2722
#ifdef V8_USE_PERFETTO
  std::ostringstream perfetto_output;
  tracing_controller->InitializeForPerfetto(&perfetto_output);
2723 2724 2725 2726 2727 2728 2729
  CpuProfilerListener listener;
  tracing_controller->SetTraceEventListenerForTesting(&listener);
#else
  CpuProfileEventChecker* event_checker = new CpuProfileEventChecker();
  TraceBuffer* ring_buffer =
      TraceBuffer::CreateTraceBufferRingBuffer(1, event_checker);
  tracing_controller->Initialize(ring_buffer);
2730 2731
#endif

2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
  bool result = false;
  for (int run_duration = 50; !result; run_duration += 50) {
    TraceConfig* trace_config = new TraceConfig();
    trace_config->AddIncludedCategory(
        TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler"));
    trace_config->AddIncludedCategory(
        TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler.hires"));

    std::string test_code = R"(
        function foo() {
          let s = 0;
          const endTime = Date.now() + )" +
                            std::to_string(run_duration) + R"(
          while (Date.now() < endTime) s += Math.cos(s);
          return s;
        }
        foo();)";

2750
    tracing_controller->StartTracing(trace_config);
2751
    CompileRun(test_code.c_str());
2752
    tracing_controller->StopTracing();
2753

2754 2755 2756 2757
#ifdef V8_USE_PERFETTO
    std::string profile_json = listener.result_json();
    listener.Reset();
#else
2758 2759
    std::string profile_json = event_checker->result_json();
    event_checker->Reset();
2760
#endif
2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
    CHECK_LT(0u, profile_json.length());
    printf("Profile JSON: %s\n", profile_json.c_str());

    std::string profile_checker_code = R"(
        function checkProfile(json) {
          const profile_header = json[0];
          if (typeof profile_header['startTime'] !== 'number')
            return false;
          return json.some(event => (event.lines || []).some(line => line));
        }
        checkProfile()" + profile_json +
                                       ")";
    result = CompileRunChecked(CcTest::isolate(), profile_checker_code.c_str())
                 ->IsTrue();
2775 2776
  }

2777 2778 2779
  static_cast<v8::platform::tracing::TracingController*>(
      i::V8::GetCurrentPlatform()->GetTracingController())
      ->Initialize(nullptr);
2780
}
2781

2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809
TEST(Issue763073) {
  class AllowNativesSyntax {
   public:
    AllowNativesSyntax()
        : allow_natives_syntax_(i::FLAG_allow_natives_syntax),
          trace_deopt_(i::FLAG_trace_deopt) {
      i::FLAG_allow_natives_syntax = true;
      i::FLAG_trace_deopt = true;
    }

    ~AllowNativesSyntax() {
      i::FLAG_allow_natives_syntax = allow_natives_syntax_;
      i::FLAG_trace_deopt = trace_deopt_;
    }

   private:
    bool allow_natives_syntax_;
    bool trace_deopt_;
  };

  AllowNativesSyntax allow_natives_syntax_scope;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

  CompileRun(
      "function f() { return function g(x) { }; }"
      // Create first closure, optimize it, and deoptimize it.
      "var g = f();"
2810
      "%PrepareFunctionForOptimization(g);\n"
2811 2812 2813 2814 2815 2816 2817
      "g(1);"
      "%OptimizeFunctionOnNextCall(g);"
      "g(1);"
      "%DeoptimizeFunction(g);"
      // Create second closure, and optimize it. This will create another
      // optimized code object and put in the (shared) type feedback vector.
      "var h = f();"
2818
      "%PrepareFunctionForOptimization(h);\n"
2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
      "h(1);"
      "%OptimizeFunctionOnNextCall(h);"
      "h(1);");

  // Start profiling.
  v8::CpuProfiler* cpu_profiler = v8::CpuProfiler::New(env->GetIsolate());
  v8::Local<v8::String> profile_name = v8_str("test");

  // Here we test that the heap iteration upon profiling start is not
  // confused by having a deoptimized code object for a closure while
  // having a different optimized code object in the type feedback vector.
  cpu_profiler->StartProfiling(profile_name);
  v8::CpuProfile* p = cpu_profiler->StopProfiling(profile_name);
  p->Delete();
  cpu_profiler->Dispose();
}

2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
static const char* js_collect_sample_api_source =
    "%NeverOptimizeFunction(start);\n"
    "function start() {\n"
    "  CallStaticCollectSample();\n"
    "}";

static void CallStaticCollectSample(
    const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::CpuProfiler::CollectSample(info.GetIsolate());
}

TEST(StaticCollectSampleAPI) {
  i::FLAG_allow_natives_syntax = true;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(env->GetIsolate(), CallStaticCollectSample);
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  func->SetName(v8_str("CallStaticCollectSample"));
  env->Global()
      ->Set(env.local(), v8_str("CallStaticCollectSample"), func)
      .FromJust();

  CompileRun(js_collect_sample_api_source);
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");

  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 100);

  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* start_node = GetChild(env.local(), root, "start");
  GetChild(env.local(), start_node, "CallStaticCollectSample");

  profile->Delete();
}

2874 2875
TEST(CodeEntriesMemoryLeak) {
  v8::HandleScope scope(CcTest::isolate());
2876
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896
  v8::Context::Scope context_scope(env);

  std::string source = "function start() {}\n";
  for (int i = 0; i < 1000; ++i) {
    source += "function foo" + std::to_string(i) + "() { return " +
              std::to_string(i) +
              "; }\n"
              "foo" +
              std::to_string(i) + "();\n";
  }
  CompileRun(source.c_str());
  v8::Local<v8::Function> function = GetFunction(env, "start");

  ProfilerHelper helper(env);

  for (int j = 0; j < 100; ++j) {
    v8::CpuProfile* profile = helper.Run(function, nullptr, 0);
    profile->Delete();
  }

2897 2898 2899
  i::CpuProfiler* profiler =
      reinterpret_cast<i::CpuProfiler*>(helper.profiler());
  CHECK(!profiler->profiler_listener_for_test());
2900 2901
}

2902 2903 2904 2905 2906 2907 2908 2909
TEST(NativeFrameStackTrace) {
  // A test for issue https://crbug.com/768540
  // When a sample lands in a native function which has not EXIT frame
  // stack frame iterator used to bail out and produce an empty stack trace.
  // The source code below makes v8 call the
  // v8::internal::StringTable::LookupStringIfExists_NoAllocate native function
  // without producing an EXIT frame.
  v8::HandleScope scope(CcTest::isolate());
2910
  v8::Local<v8::Context> env = CcTest::NewContext({PROFILER_EXTENSION_ID});
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927
  v8::Context::Scope context_scope(env);

  const char* source = R"(
      function jsFunction() {
        var s = {};
        for (var i = 0; i < 1e4; ++i) {
          for (var j = 0; j < 100; j++) {
            s['item' + j] = 'alph';
          }
        }
      })";

  CompileRun(source);
  v8::Local<v8::Function> function = GetFunction(env, "jsFunction");

  ProfilerHelper helper(env);

2928
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 100, 0);
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948

  // Count the fraction of samples landing in 'jsFunction' (valid stack)
  // vs '(program)' (no stack captured).
  const v8::CpuProfileNode* root = profile->GetTopDownRoot();
  const v8::CpuProfileNode* js_function = FindChild(root, "jsFunction");
  const v8::CpuProfileNode* program = FindChild(root, "(program)");
  if (program) {
    unsigned js_function_samples = TotalHitCount(js_function);
    unsigned program_samples = TotalHitCount(program);
    double valid_samples_ratio =
        1. * js_function_samples / (js_function_samples + program_samples);
    i::PrintF("Ratio: %f\n", valid_samples_ratio);
    // TODO(alph): Investigate other causes of dropped frames. The ratio
    // should be close to 99%.
    CHECK_GE(valid_samples_ratio, 0.3);
  }

  profile->Delete();
}

2949
TEST(SourcePositionTable) {
2950
  i::SourcePositionTable info;
2951 2952 2953

  // Newly created tables should return NoLineNumberInfo for any lookup.
  int no_info = v8::CpuProfileNode::kNoLineNumberInfo;
2954 2955
  CHECK_EQ(no_info, info.GetSourceLineNumber(std::numeric_limits<int>::min()));
  CHECK_EQ(no_info, info.GetSourceLineNumber(0));
2956
  CHECK_EQ(SourcePosition::kNotInlined, info.GetInliningId(0));
2957 2958 2959 2960 2961 2962 2963 2964
  CHECK_EQ(no_info, info.GetSourceLineNumber(1));
  CHECK_EQ(no_info, info.GetSourceLineNumber(9));
  CHECK_EQ(no_info, info.GetSourceLineNumber(10));
  CHECK_EQ(no_info, info.GetSourceLineNumber(11));
  CHECK_EQ(no_info, info.GetSourceLineNumber(19));
  CHECK_EQ(no_info, info.GetSourceLineNumber(20));
  CHECK_EQ(no_info, info.GetSourceLineNumber(21));
  CHECK_EQ(no_info, info.GetSourceLineNumber(100));
2965
  CHECK_EQ(SourcePosition::kNotInlined, info.GetInliningId(100));
2966 2967
  CHECK_EQ(no_info, info.GetSourceLineNumber(std::numeric_limits<int>::max()));

2968 2969
  info.SetPosition(10, 1, SourcePosition::kNotInlined);
  info.SetPosition(20, 2, SourcePosition::kNotInlined);
2970

2971 2972
  // The only valid return values are 1 or 2 - every pc maps to a line
  // number.
2973 2974 2975 2976 2977 2978 2979
  CHECK_EQ(1, info.GetSourceLineNumber(std::numeric_limits<int>::min()));
  CHECK_EQ(1, info.GetSourceLineNumber(0));
  CHECK_EQ(1, info.GetSourceLineNumber(1));
  CHECK_EQ(1, info.GetSourceLineNumber(9));
  CHECK_EQ(1, info.GetSourceLineNumber(10));
  CHECK_EQ(1, info.GetSourceLineNumber(11));
  CHECK_EQ(1, info.GetSourceLineNumber(19));
2980
  CHECK_EQ(1, info.GetSourceLineNumber(20));
2981 2982 2983
  CHECK_EQ(2, info.GetSourceLineNumber(21));
  CHECK_EQ(2, info.GetSourceLineNumber(100));
  CHECK_EQ(2, info.GetSourceLineNumber(std::numeric_limits<int>::max()));
2984

2985 2986 2987
  CHECK_EQ(SourcePosition::kNotInlined, info.GetInliningId(0));
  CHECK_EQ(SourcePosition::kNotInlined, info.GetInliningId(100));

2988
  // Test SetPosition behavior.
2989
  info.SetPosition(25, 3, 0);
2990 2991 2992
  CHECK_EQ(2, info.GetSourceLineNumber(21));
  CHECK_EQ(3, info.GetSourceLineNumber(100));
  CHECK_EQ(3, info.GetSourceLineNumber(std::numeric_limits<int>::max()));
2993 2994 2995

  CHECK_EQ(SourcePosition::kNotInlined, info.GetInliningId(21));
  CHECK_EQ(0, info.GetInliningId(100));
2996 2997 2998 2999 3000 3001 3002 3003 3004

  // Test that subsequent SetPosition calls with the same pc_offset are ignored.
  info.SetPosition(25, 4, SourcePosition::kNotInlined);
  CHECK_EQ(2, info.GetSourceLineNumber(21));
  CHECK_EQ(3, info.GetSourceLineNumber(100));
  CHECK_EQ(3, info.GetSourceLineNumber(std::numeric_limits<int>::max()));

  CHECK_EQ(SourcePosition::kNotInlined, info.GetInliningId(21));
  CHECK_EQ(0, info.GetInliningId(100));
3005 3006
}

3007 3008 3009 3010 3011 3012 3013 3014 3015
TEST(MultipleProfilers) {
  std::unique_ptr<CpuProfiler> profiler1(new CpuProfiler(CcTest::i_isolate()));
  std::unique_ptr<CpuProfiler> profiler2(new CpuProfiler(CcTest::i_isolate()));
  profiler1->StartProfiling("1");
  profiler2->StartProfiling("2");
  profiler1->StopProfiling("1");
  profiler2->StopProfiling("2");
}

3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031
// Tests that logged CodeCreateEvent calls do not crash a reused CpuProfiler.
// crbug.com/929928
TEST(CrashReusedProfiler) {
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  i::HandleScope scope(isolate);

  std::unique_ptr<CpuProfiler> profiler(new CpuProfiler(isolate));
  profiler->StartProfiling("1");
  profiler->StopProfiling("1");

  profiler->StartProfiling("2");
  CreateCode(&env);
  profiler->StopProfiling("2");
}

3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
// Tests that samples from different profilers on the same isolate do not leak
// samples to each other. See crbug.com/v8/8835.
TEST(MultipleProfilersSampleIndependently) {
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  i::HandleScope scope(isolate);

  // Create two profilers- one slow ticking one, and one fast ticking one.
  // Ensure that the slow ticking profiler does not receive samples from the
  // fast ticking one.
  std::unique_ptr<CpuProfiler> slow_profiler(
      new CpuProfiler(CcTest::i_isolate()));
  slow_profiler->set_sampling_interval(base::TimeDelta::FromSeconds(1));
3045
  slow_profiler->StartProfiling("1", {kLeafNodeLineNumbers});
3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057

  CompileRun(R"(
    function start() {
      let val = 1;
      for (let i = 0; i < 10e3; i++) {
        val = (val * 2) % 3;
      }
      return val;
    }
  )");
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
  ProfilerHelper helper(env.local());
3058
  v8::CpuProfile* profile = helper.Run(function, nullptr, 0, 100, 0);
3059 3060 3061 3062 3063

  auto slow_profile = slow_profiler->StopProfiling("1");
  CHECK_GT(profile->GetSamplesCount(), slow_profile->samples_count());
}

3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074
void ProfileSomeCode(v8::Isolate* isolate) {
  v8::Isolate::Scope isolate_scope(isolate);
  v8::HandleScope scope(isolate);
  LocalContext context(isolate);

  v8::CpuProfiler* profiler = v8::CpuProfiler::New(isolate);

  v8::Local<v8::String> profile_name = v8_str("1");
  profiler->StartProfiling(profile_name);
  const char* source = R"(
      function foo() {
3075
        var x = 0;
3076
        for (var i = 0; i < 1e3; i++) {
3077
          for (var j = 0; j < 1e3; j++) {
3078
            x = i * j;
3079 3080
          }
        }
3081
        return x;
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108
      }
      foo();
    )";

  CompileRun(source);
  profiler->StopProfiling(profile_name);
  profiler->Dispose();
}

class IsolateThread : public v8::base::Thread {
 public:
  IsolateThread() : Thread(Options("IsolateThread")) {}

  void Run() override {
    v8::Isolate::CreateParams create_params;
    create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
    v8::Isolate* isolate = v8::Isolate::New(create_params);
    ProfileSomeCode(isolate);
    isolate->Dispose();
  }
};

// Checking for crashes and TSAN issues with multiple isolates profiling.
TEST(MultipleIsolates) {
  IsolateThread thread1;
  IsolateThread thread2;

3109 3110
  CHECK(thread1.Start());
  CHECK(thread2.Start());
3111 3112 3113 3114 3115

  thread1.Join();
  thread2.Join();
}

3116 3117 3118 3119 3120 3121 3122 3123
// Tests that StopProfiling doesn't wait for the next sample tick in order to
// stop, but rather exits early before a given wait threshold.
TEST(FastStopProfiling) {
  static const base::TimeDelta kLongInterval = base::TimeDelta::FromSeconds(10);
  static const base::TimeDelta kWaitThreshold = base::TimeDelta::FromSeconds(5);

  std::unique_ptr<CpuProfiler> profiler(new CpuProfiler(CcTest::i_isolate()));
  profiler->set_sampling_interval(kLongInterval);
3124
  profiler->StartProfiling("", {kLeafNodeLineNumbers});
3125 3126 3127 3128 3129 3130 3131 3132 3133

  v8::Platform* platform = v8::internal::V8::GetCurrentPlatform();
  double start = platform->CurrentClockTimeMillis();
  profiler->StopProfiling("");
  double duration = platform->CurrentClockTimeMillis() - start;

  CHECK_LT(duration, kWaitThreshold.InMillisecondsF());
}

3134 3135 3136
TEST(LowPrecisionSamplingStartStopInternal) {
  i::Isolate* isolate = CcTest::i_isolate();
  CpuProfilesCollection profiles(isolate);
3137 3138
  ProfilerCodeObserver code_observer(isolate);
  ProfileGenerator generator(&profiles, code_observer.code_map());
3139
  std::unique_ptr<ProfilerEventsProcessor> processor(
3140
      new SamplingEventsProcessor(isolate, &generator, &code_observer,
3141 3142
                                  v8::base::TimeDelta::FromMicroseconds(100),
                                  false));
3143
  CHECK(processor->Start());
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157
  processor->StopSynchronously();
}

TEST(LowPrecisionSamplingStartStopPublic) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::CpuProfiler* cpu_profiler = v8::CpuProfiler::New(env->GetIsolate());
  cpu_profiler->SetUsePreciseSampling(false);
  v8::Local<v8::String> profile_name = v8_str("");
  cpu_profiler->StartProfiling(profile_name, true);
  cpu_profiler->StopProfiling(profile_name);
  cpu_profiler->Dispose();
}

3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229
const char* naming_test_source = R"(
  (function testAssignmentPropertyNamedFunction() {
    let object = {};
    object.propNamed = function () {
      CallCollectSample();
    };
    object.propNamed();
  })();
  )";

TEST(StandardNaming) {
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  i::HandleScope scope(isolate);

  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(env->GetIsolate(), CallCollectSample);
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  func->SetName(v8_str("CallCollectSample"));
  env->Global()->Set(env.local(), v8_str("CallCollectSample"), func).FromJust();

  v8::CpuProfiler* profiler =
      v8::CpuProfiler::New(env->GetIsolate(), kStandardNaming);

  const auto profile_name = v8_str("");
  profiler->StartProfiling(profile_name);
  CompileRun(naming_test_source);
  auto* profile = profiler->StopProfiling(profile_name);

  auto* root = profile->GetTopDownRoot();
  auto* toplevel = FindChild(root, "");
  DCHECK(toplevel);

  auto* prop_assignment_named_test =
      GetChild(env.local(), toplevel, "testAssignmentPropertyNamedFunction");
  CHECK(FindChild(prop_assignment_named_test, ""));

  profiler->Dispose();
}

TEST(DebugNaming) {
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  i::HandleScope scope(isolate);

  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(env->GetIsolate(), CallCollectSample);
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  func->SetName(v8_str("CallCollectSample"));
  env->Global()->Set(env.local(), v8_str("CallCollectSample"), func).FromJust();

  v8::CpuProfiler* profiler =
      v8::CpuProfiler::New(env->GetIsolate(), kDebugNaming);

  const auto profile_name = v8_str("");
  profiler->StartProfiling(profile_name);
  CompileRun(naming_test_source);
  auto* profile = profiler->StopProfiling(profile_name);

  auto* root = profile->GetTopDownRoot();
  auto* toplevel = FindChild(root, "");
  DCHECK(toplevel);

  auto* prop_assignment_named_test =
      GetChild(env.local(), toplevel, "testAssignmentPropertyNamedFunction");
  CHECK(FindChild(prop_assignment_named_test, "object.propNamed"));

  profiler->Dispose();
}

3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248
TEST(SampleLimit) {
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  i::HandleScope scope(isolate);

  CompileRun(R"(
    function start() {
      let val = 1;
      for (let i = 0; i < 10e3; i++) {
        val = (val * 2) % 3;
      }
      return val;
    }
  )");

  // Take 100 samples of `start`, but set the max samples to 50.
  v8::Local<v8::Function> function = GetFunction(env.local(), "start");
  ProfilerHelper helper(env.local());
  v8::CpuProfile* profile =
3249
      helper.Run(function, nullptr, 0, 100, 0,
3250 3251 3252 3253 3254
                 v8::CpuProfilingMode::kLeafNodeLineNumbers, 50);

  CHECK_EQ(profile->GetSamplesCount(), 50);
}

3255 3256 3257 3258 3259 3260 3261 3262
// Tests that a CpuProfile instance subsamples from a stream of tick samples
// appropriately.
TEST(ProflilerSubsampling) {
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  i::HandleScope scope(isolate);

  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
3263 3264 3265 3266 3267 3268 3269 3270 3271
  ProfilerCodeObserver code_observer(isolate);
  ProfileGenerator* generator =
      new ProfileGenerator(profiles, code_observer.code_map());
  ProfilerEventsProcessor* processor =
      new SamplingEventsProcessor(isolate, generator, &code_observer,
                                  v8::base::TimeDelta::FromMicroseconds(1),
                                  /* use_precise_sampling */ true);
  CpuProfiler profiler(isolate, kDebugNaming, kLazyLogging, profiles, generator,
                       processor);
3272 3273 3274

  // Create a new CpuProfile that wants samples at 8us.
  CpuProfile profile(&profiler, "",
3275
                     {v8::CpuProfilingMode::kLeafNodeLineNumbers,
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307
                      v8::CpuProfilingOptions::kNoSampleLimit, 8});
  // Verify that the first sample is always included.
  CHECK(profile.CheckSubsample(base::TimeDelta::FromMicroseconds(10)));

  // 4 2us samples should result in one 8us sample.
  CHECK(!profile.CheckSubsample(base::TimeDelta::FromMicroseconds(2)));
  CHECK(!profile.CheckSubsample(base::TimeDelta::FromMicroseconds(2)));
  CHECK(!profile.CheckSubsample(base::TimeDelta::FromMicroseconds(2)));
  CHECK(profile.CheckSubsample(base::TimeDelta::FromMicroseconds(2)));

  // Profiles should expect the source sample interval to change, in which case
  // they should still take the first sample elapsed after their interval.
  CHECK(!profile.CheckSubsample(base::TimeDelta::FromMicroseconds(2)));
  CHECK(!profile.CheckSubsample(base::TimeDelta::FromMicroseconds(2)));
  CHECK(!profile.CheckSubsample(base::TimeDelta::FromMicroseconds(2)));
  CHECK(profile.CheckSubsample(base::TimeDelta::FromMicroseconds(4)));

  // Aligned samples (at 8us) are always included.
  CHECK(profile.CheckSubsample(base::TimeDelta::FromMicroseconds(8)));

  // Samples with a rate of 0 should always be included.
  CHECK(profile.CheckSubsample(base::TimeDelta::FromMicroseconds(0)));
}

// Tests that the base sampling rate of a CpuProfilesCollection is dynamically
// chosen based on the GCD of its child profiles.
TEST(DynamicResampling) {
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  i::HandleScope scope(isolate);

  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
3308 3309 3310 3311 3312 3313 3314 3315 3316
  ProfilerCodeObserver code_observer(isolate);
  ProfileGenerator* generator =
      new ProfileGenerator(profiles, code_observer.code_map());
  ProfilerEventsProcessor* processor =
      new SamplingEventsProcessor(isolate, generator, &code_observer,
                                  v8::base::TimeDelta::FromMicroseconds(1),
                                  /* use_precise_sampling */ true);
  CpuProfiler profiler(isolate, kDebugNaming, kLazyLogging, profiles, generator,
                       processor);
3317 3318 3319 3320 3321 3322 3323 3324 3325 3326

  // Set a 1us base sampling rate, dividing all possible intervals.
  profiler.set_sampling_interval(base::TimeDelta::FromMicroseconds(1));

  // Verify that the sampling interval with no started profilers is unset.
  CHECK_EQ(profiles->GetCommonSamplingInterval(), base::TimeDelta());

  // Add a 10us profiler, verify that the base sampling interval is as high as
  // possible (10us).
  profiles->StartProfiling("10us",
3327
                           {v8::CpuProfilingMode::kLeafNodeLineNumbers,
3328 3329 3330 3331 3332 3333
                            v8::CpuProfilingOptions::kNoSampleLimit, 10});
  CHECK_EQ(profiles->GetCommonSamplingInterval(),
           base::TimeDelta::FromMicroseconds(10));

  // Add a 5us profiler, verify that the base sampling interval is as high as
  // possible given a 10us and 5us profiler (5us).
3334 3335
  profiles->StartProfiling("5us", {v8::CpuProfilingMode::kLeafNodeLineNumbers,
                                   v8::CpuProfilingOptions::kNoSampleLimit, 5});
3336 3337 3338 3339 3340
  CHECK_EQ(profiles->GetCommonSamplingInterval(),
           base::TimeDelta::FromMicroseconds(5));

  // Add a 3us profiler, verify that the base sampling interval is 1us (due to
  // coprime intervals).
3341 3342
  profiles->StartProfiling("3us", {v8::CpuProfilingMode::kLeafNodeLineNumbers,
                                   v8::CpuProfilingOptions::kNoSampleLimit, 3});
3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369
  CHECK_EQ(profiles->GetCommonSamplingInterval(),
           base::TimeDelta::FromMicroseconds(1));

  // Remove the 5us profiler, verify that the sample interval stays at 1us.
  profiles->StopProfiling("5us");
  CHECK_EQ(profiles->GetCommonSamplingInterval(),
           base::TimeDelta::FromMicroseconds(1));

  // Remove the 10us profiler, verify that the sample interval becomes 3us.
  profiles->StopProfiling("10us");
  CHECK_EQ(profiles->GetCommonSamplingInterval(),
           base::TimeDelta::FromMicroseconds(3));

  // Remove the 3us profiler, verify that the sample interval becomes unset.
  profiles->StopProfiling("3us");
  CHECK_EQ(profiles->GetCommonSamplingInterval(), base::TimeDelta());
}

// Ensures that when a non-unit base sampling interval is set on the profiler,
// that the sampling rate gets snapped to the nearest multiple prior to GCD
// computation.
TEST(DynamicResamplingWithBaseInterval) {
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  i::HandleScope scope(isolate);

  CpuProfilesCollection* profiles = new CpuProfilesCollection(isolate);
3370 3371 3372 3373 3374 3375 3376 3377 3378
  ProfilerCodeObserver code_observer(isolate);
  ProfileGenerator* generator =
      new ProfileGenerator(profiles, code_observer.code_map());
  ProfilerEventsProcessor* processor =
      new SamplingEventsProcessor(isolate, generator, &code_observer,
                                  v8::base::TimeDelta::FromMicroseconds(1),
                                  /* use_precise_sampling */ true);
  CpuProfiler profiler(isolate, kDebugNaming, kLazyLogging, profiles, generator,
                       processor);
3379 3380 3381 3382 3383 3384 3385 3386

  profiler.set_sampling_interval(base::TimeDelta::FromMicroseconds(7));

  // Verify that the sampling interval with no started profilers is unset.
  CHECK_EQ(profiles->GetCommonSamplingInterval(), base::TimeDelta());

  // Add a profiler with an unset sampling interval, verify that the common
  // sampling interval is equal to the base.
3387 3388
  profiles->StartProfiling("unset", {v8::CpuProfilingMode::kLeafNodeLineNumbers,
                                     v8::CpuProfilingOptions::kNoSampleLimit});
3389 3390 3391 3392 3393
  CHECK_EQ(profiles->GetCommonSamplingInterval(),
           base::TimeDelta::FromMicroseconds(7));
  profiles->StopProfiling("unset");

  // Adding a 8us sampling interval rounds to a 14us base interval.
3394 3395
  profiles->StartProfiling("8us", {v8::CpuProfilingMode::kLeafNodeLineNumbers,
                                   v8::CpuProfilingOptions::kNoSampleLimit, 8});
3396 3397 3398 3399
  CHECK_EQ(profiles->GetCommonSamplingInterval(),
           base::TimeDelta::FromMicroseconds(14));

  // Adding a 4us sampling interval should cause a lowering to a 7us interval.
3400 3401
  profiles->StartProfiling("4us", {v8::CpuProfilingMode::kLeafNodeLineNumbers,
                                   v8::CpuProfilingOptions::kNoSampleLimit, 4});
3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
  CHECK_EQ(profiles->GetCommonSamplingInterval(),
           base::TimeDelta::FromMicroseconds(7));

  // Removing the 4us sampling interval should restore the 14us sampling
  // interval.
  profiles->StopProfiling("4us");
  CHECK_EQ(profiles->GetCommonSamplingInterval(),
           base::TimeDelta::FromMicroseconds(14));

  // Removing the 8us sampling interval should unset the common sampling
  // interval.
  profiles->StopProfiling("8us");
  CHECK_EQ(profiles->GetCommonSamplingInterval(), base::TimeDelta());

  // A sampling interval of 0us should enforce all profiles to have a sampling
  // interval of 0us (the only multiple of 0).
  profiler.set_sampling_interval(base::TimeDelta::FromMicroseconds(0));
3419 3420
  profiles->StartProfiling("5us", {v8::CpuProfilingMode::kLeafNodeLineNumbers,
                                   v8::CpuProfilingOptions::kNoSampleLimit, 5});
3421 3422 3423 3424 3425
  CHECK_EQ(profiles->GetCommonSamplingInterval(),
           base::TimeDelta::FromMicroseconds(0));
  profiles->StopProfiling("5us");
}

3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469
// Tests that functions compiled after a started profiler is stopped are still
// visible when the profiler is started again. (https://crbug.com/v8/9151)
TEST(Bug9151StaleCodeEntries) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

  v8::Local<v8::FunctionTemplate> func_template =
      v8::FunctionTemplate::New(env->GetIsolate(), CallCollectSample);
  v8::Local<v8::Function> func =
      func_template->GetFunction(env.local()).ToLocalChecked();
  func->SetName(v8_str("CallCollectSample"));
  env->Global()->Set(env.local(), v8_str("CallCollectSample"), func).FromJust();

  v8::CpuProfiler* profiler =
      v8::CpuProfiler::New(env->GetIsolate(), kDebugNaming, kEagerLogging);
  v8::Local<v8::String> profile_name = v8_str("");

  // Warm up the profiler to create the initial code map.
  profiler->StartProfiling(profile_name);
  profiler->StopProfiling(profile_name);

  // Log a function compilation (executed once to force a compilation).
  CompileRun(R"(
      function start() {
        CallCollectSample();
      }
      start();
  )");

  // Restart the profiler, and execute both the JS function and callback.
  profiler->StartProfiling(profile_name, true);
  CompileRun("start();");
  v8::CpuProfile* profile = profiler->StopProfiling(profile_name);

  auto* root = profile->GetTopDownRoot();
  auto* toplevel = GetChild(env.local(), root, "");

  auto* start = FindChild(env.local(), toplevel, "start");
  CHECK(start);

  auto* callback = FindChild(env.local(), start, "CallCollectSample");
  CHECK(callback);
}

3470 3471 3472 3473 3474 3475
enum class EntryCountMode { kAll, kOnlyInlined };

// Count the number of unique source positions.
int GetSourcePositionEntryCount(i::Isolate* isolate, const char* source,
                                EntryCountMode mode = EntryCountMode::kAll) {
  std::unordered_set<int64_t> raw_position_set;
3476 3477 3478 3479 3480 3481
  i::Handle<i::JSFunction> function = i::Handle<i::JSFunction>::cast(
      v8::Utils::OpenHandle(*CompileRun(source)));
  if (function->IsInterpreted()) return -1;
  i::Handle<i::Code> code(function->code(), isolate);
  i::SourcePositionTableIterator iterator(
      ByteArray::cast(code->source_position_table()));
3482

3483
  while (!iterator.done()) {
3484 3485 3486 3487
    if (mode == EntryCountMode::kAll ||
        iterator.source_position().isInlined()) {
      raw_position_set.insert(iterator.source_position().raw());
    }
3488 3489
    iterator.Advance();
  }
3490
  return static_cast<int>(raw_position_set.size());
3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505
}

UNINITIALIZED_TEST(DetailedSourcePositionAPI) {
  i::FLAG_detailed_line_info = false;
  i::FLAG_allow_natives_syntax = true;
  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
  v8::Isolate* isolate = v8::Isolate::New(create_params);

  const char* source =
      "function fib(i) {"
      "  if (i <= 1) return 1; "
      "  return fib(i - 1) +"
      "         fib(i - 2);"
      "}"
3506
      "%PrepareFunctionForOptimization(fib);\n"
3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
      "fib(5);"
      "%OptimizeFunctionOnNextCall(fib);"
      "fib(5);"
      "fib";
  {
    v8::Isolate::Scope isolate_scope(isolate);
    v8::HandleScope handle_scope(isolate);
    v8::Local<v8::Context> context = v8::Context::New(isolate);
    v8::Context::Scope context_scope(context);
    i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);

    CHECK(!i_isolate->NeedsDetailedOptimizedCodeLineInfo());

    int non_detailed_positions = GetSourcePositionEntryCount(i_isolate, source);

    v8::CpuProfiler::UseDetailedSourcePositionsForProfiling(isolate);
    CHECK(i_isolate->NeedsDetailedOptimizedCodeLineInfo());

    int detailed_positions = GetSourcePositionEntryCount(i_isolate, source);

    CHECK((non_detailed_positions == -1 && detailed_positions == -1) ||
          non_detailed_positions < detailed_positions);
  }

  isolate->Dispose();
}

3534 3535
UNINITIALIZED_TEST(DetailedSourcePositionAPI_Inlining) {
  i::FLAG_detailed_line_info = false;
3536
  i::FLAG_turbo_inlining = true;
3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556
  i::FLAG_stress_inline = true;
  i::FLAG_always_opt = false;
  i::FLAG_allow_natives_syntax = true;
  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
  v8::Isolate* isolate = v8::Isolate::New(create_params);

  const char* source = R"(
    function foo(x) {
      return bar(x) + 1;
    }

    function bar(x) {
      var y = 1;
      for (var i = 0; i < x; ++i) {
        y = y * x;
      }
      return x;
    }

3557
    %EnsureFeedbackVectorForFunction(bar);
3558
    %PrepareFunctionForOptimization(foo);
3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597
    foo(5);
    %OptimizeFunctionOnNextCall(foo);
    foo(5);
    foo;
  )";

  {
    v8::Isolate::Scope isolate_scope(isolate);
    v8::HandleScope handle_scope(isolate);
    v8::Local<v8::Context> context = v8::Context::New(isolate);
    v8::Context::Scope context_scope(context);
    i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);

    CHECK(!i_isolate->NeedsDetailedOptimizedCodeLineInfo());

    int non_detailed_positions =
        GetSourcePositionEntryCount(i_isolate, source, EntryCountMode::kAll);
    int non_detailed_inlined_positions = GetSourcePositionEntryCount(
        i_isolate, source, EntryCountMode::kOnlyInlined);

    v8::CpuProfiler::UseDetailedSourcePositionsForProfiling(isolate);
    CHECK(i_isolate->NeedsDetailedOptimizedCodeLineInfo());

    int detailed_positions =
        GetSourcePositionEntryCount(i_isolate, source, EntryCountMode::kAll);
    int detailed_inlined_positions = GetSourcePositionEntryCount(
        i_isolate, source, EntryCountMode::kOnlyInlined);

    if (non_detailed_positions == -1) {
      CHECK_EQ(non_detailed_positions, detailed_positions);
    } else {
      CHECK_LT(non_detailed_positions, detailed_positions);
      CHECK_LT(non_detailed_inlined_positions, detailed_inlined_positions);
    }
  }

  isolate->Dispose();
}

3598 3599 3600
}  // namespace test_cpu_profiler
}  // namespace internal
}  // namespace v8