test-compiler.cc 35.7 KB
Newer Older
1
// Copyright 2012 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 27 28
// 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.

#include <stdlib.h>
29
#include <wchar.h>
30

31
#include <memory>
32

33 34
#include "include/v8-function.h"
#include "include/v8-local-handle.h"
35
#include "include/v8-profiler.h"
36
#include "include/v8-script.h"
37
#include "src/api/api-inl.h"
38 39
#include "src/codegen/compilation-cache.h"
#include "src/codegen/compiler.h"
40
#include "src/codegen/script-details.h"
41
#include "src/diagnostics/disasm.h"
42
#include "src/heap/factory.h"
43
#include "src/heap/spaces.h"
44
#include "src/init/v8.h"
45
#include "src/interpreter/interpreter.h"
46
#include "src/objects/allocation-site-inl.h"
47
#include "src/objects/objects-inl.h"
48
#include "src/objects/shared-function-info.h"
49
#include "test/cctest/cctest.h"
50

51 52
namespace v8 {
namespace internal {
53

54
static Handle<Object> GetGlobalProperty(const char* name) {
55
  Isolate* isolate = CcTest::i_isolate();
56 57
  return JSReceiver::GetProperty(isolate, isolate->global_object(), name)
      .ToHandleChecked();
58 59
}

60
static void SetGlobalProperty(const char* name, Object value) {
61
  Isolate* isolate = CcTest::i_isolate();
62
  Handle<Object> object(value, isolate);
63 64
  Handle<String> internalized_name =
      isolate->factory()->InternalizeUtf8String(name);
65
  Handle<JSObject> global(isolate->context().global_object(), isolate);
66
  Runtime::SetObjectProperty(isolate, global, internalized_name, object,
67
                             StoreOrigin::kMaybeKeyed, Just(kDontThrow))
68
      .Check();
69 70 71
}

static Handle<JSFunction> Compile(const char* source) {
72
  Isolate* isolate = CcTest::i_isolate();
73 74 75
  Handle<String> source_code = isolate->factory()
                                   ->NewStringFromUtf8(base::CStrVector(source))
                                   .ToHandleChecked();
76 77
  Handle<SharedFunctionInfo> shared =
      Compiler::GetSharedFunctionInfoForScript(
78
          isolate, source_code, ScriptDetails(),
79
          v8::ScriptCompiler::kNoCompileOptions,
80
          ScriptCompiler::kNoCacheNoReason, NOT_NATIVES_CODE)
81
          .ToHandleChecked();
82 83
  return Factory::JSFunctionBuilder{isolate, shared, isolate->native_context()}
      .Build();
84 85 86
}


87
static double Inc(Isolate* isolate, int x) {
88
  const char* source = "result = %d + 1;";
89
  base::EmbeddedVector<char, 512> buffer;
90
  SNPrintF(buffer, source, x);
91

92
  Handle<JSFunction> fun = Compile(buffer.begin());
93 94
  if (fun.is_null()) return -1;

95
  Handle<JSObject> global(isolate->context().global_object(), isolate);
96 97 98
  Execution::CallScript(isolate, fun, global,
                        isolate->factory()->empty_fixed_array())
      .Check();
99
  return GetGlobalProperty("result")->Number();
100 101 102 103
}


TEST(Inc) {
104 105
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
106
  CHECK_EQ(4.0, Inc(CcTest::i_isolate(), 3));
107 108 109
}


110
static double Add(Isolate* isolate, int x, int y) {
111 112 113 114 115
  Handle<JSFunction> fun = Compile("result = x + y;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("x", Smi::FromInt(x));
  SetGlobalProperty("y", Smi::FromInt(y));
116
  Handle<JSObject> global(isolate->context().global_object(), isolate);
117 118 119
  Execution::CallScript(isolate, fun, global,
                        isolate->factory()->empty_fixed_array())
      .Check();
120
  return GetGlobalProperty("result")->Number();
121 122 123 124
}


TEST(Add) {
125 126
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
127
  CHECK_EQ(5.0, Add(CcTest::i_isolate(), 2, 3));
128 129 130
}


131
static double Abs(Isolate* isolate, int x) {
132 133 134 135
  Handle<JSFunction> fun = Compile("if (x < 0) result = -x; else result = x;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("x", Smi::FromInt(x));
136
  Handle<JSObject> global(isolate->context().global_object(), isolate);
137 138 139
  Execution::CallScript(isolate, fun, global,
                        isolate->factory()->empty_fixed_array())
      .Check();
140
  return GetGlobalProperty("result")->Number();
141 142 143 144
}


TEST(Abs) {
145 146
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
147
  CHECK_EQ(3.0, Abs(CcTest::i_isolate(), -3));
148 149 150
}


151
static double Sum(Isolate* isolate, int n) {
152 153 154 155 156
  Handle<JSFunction> fun =
      Compile("s = 0; while (n > 0) { s += n; n -= 1; }; result = s;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("n", Smi::FromInt(n));
157
  Handle<JSObject> global(isolate->context().global_object(), isolate);
158 159 160
  Execution::CallScript(isolate, fun, global,
                        isolate->factory()->empty_fixed_array())
      .Check();
161
  return GetGlobalProperty("result")->Number();
162 163 164 165
}


TEST(Sum) {
166 167
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
168
  CHECK_EQ(5050.0, Sum(CcTest::i_isolate(), 100));
169 170 171 172
}


TEST(Print) {
173
  v8::HandleScope scope(CcTest::isolate());
174
  v8::Local<v8::Context> context = CcTest::NewContext({PRINT_EXTENSION_ID});
175
  v8::Context::Scope context_scope(context);
176 177 178
  const char* source = "for (n = 0; n < 100; ++n) print(n, 1, 2);";
  Handle<JSFunction> fun = Compile(source);
  if (fun.is_null()) return;
179 180 181 182 183
  auto isolate = CcTest::i_isolate();
  Handle<JSObject> global(isolate->context().global_object(), isolate);
  Execution::CallScript(isolate, fun, global,
                        isolate->factory()->empty_fixed_array())
      .Check();
184 185 186 187 188 189
}


// The following test method stems from my coding efforts today. It
// tests all the functionality I have added to the compiler today
TEST(Stuff) {
190 191
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  const char* source =
    "r = 0;\n"
    "a = new Object;\n"
    "if (a == a) r+=1;\n"  // 1
    "if (a != new Object()) r+=2;\n"  // 2
    "a.x = 42;\n"
    "if (a.x == 42) r+=4;\n"  // 4
    "function foo() { var x = 87; return x; }\n"
    "if (foo() == 87) r+=8;\n"  // 8
    "function bar() { var x; x = 99; return x; }\n"
    "if (bar() == 99) r+=16;\n"  // 16
    "function baz() { var x = 1, y, z = 2; y = 3; return x + y + z; }\n"
    "if (baz() == 6) r+=32;\n"  // 32
    "function Cons0() { this.x = 42; this.y = 87; }\n"
    "if (new Cons0().x == 42) r+=64;\n"  // 64
    "if (new Cons0().y == 87) r+=128;\n"  // 128
    "function Cons2(x, y) { this.sum = x + y; }\n"
    "if (new Cons2(3,4).sum == 7) r+=256;";  // 256

  Handle<JSFunction> fun = Compile(source);
  CHECK(!fun.is_null());
213 214 215 216 217
  auto isolate = CcTest::i_isolate();
  Handle<JSObject> global(isolate->context().global_object(), isolate);
  Execution::CallScript(isolate, fun, global,
                        isolate->factory()->empty_fixed_array())
      .Check();
218
  CHECK_EQ(511.0, GetGlobalProperty("r")->Number());
219 220 221 222
}


TEST(UncaughtThrow) {
223 224
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
225 226 227 228

  const char* source = "throw 42;";
  Handle<JSFunction> fun = Compile(source);
  CHECK(!fun.is_null());
229
  Isolate* isolate = fun->GetIsolate();
230
  Handle<JSObject> global(isolate->context().global_object(), isolate);
231 232 233
  CHECK(Execution::CallScript(isolate, fun, global,
                              isolate->factory()->empty_fixed_array())
            .is_null());
234
  CHECK_EQ(42.0, isolate->pending_exception().Number());
235 236 237 238 239 240 241 242 243 244
}


// Tests calling a builtin function from C/C++ code, and the builtin function
// performs GC. It creates a stack frame looks like following:
//   | C (PerformGC) |
//   |   JS-to-C     |
//   |      JS       |
//   |   C-to-JS     |
TEST(C2JSFrames) {
245
  FLAG_expose_gc = true;
246
  v8::HandleScope scope(CcTest::isolate());
247
  v8::Local<v8::Context> context =
248
      CcTest::NewContext({PRINT_EXTENSION_ID, GC_EXTENSION_ID});
249
  v8::Context::Scope context_scope(context);
250 251 252 253 254

  const char* source = "function foo(a) { gc(), print(a); }";

  Handle<JSFunction> fun0 = Compile(source);
  CHECK(!fun0.is_null());
255
  Isolate* isolate = fun0->GetIsolate();
256 257

  // Run the generated code to populate the global object with 'foo'.
258
  Handle<JSObject> global(isolate->context().global_object(), isolate);
259 260 261
  Execution::CallScript(isolate, fun0, global,
                        isolate->factory()->empty_fixed_array())
      .Check();
262

263 264 265
  Handle<Object> fun1 =
      JSReceiver::GetProperty(isolate, isolate->global_object(), "foo")
          .ToHandleChecked();
266 267
  CHECK(fun1->IsJSFunction());

268
  Handle<Object> argv[] = {
269
      isolate->factory()->InternalizeString(base::StaticCharVector("hello"))};
270 271
  Execution::Call(isolate,
                  Handle<JSFunction>::cast(fun1),
272
                  global,
273
                  arraysize(argv),
274
                  argv).Check();
275
}
276 277 278 279 280


// Regression 236. Calling InitLineEnds on a Script with undefined
// source resulted in crash.
TEST(Regression236) {
281
  CcTest::InitializeVM();
282
  Isolate* isolate = CcTest::i_isolate();
283
  Factory* factory = isolate->factory();
284
  v8::HandleScope scope(CcTest::isolate());
285

286
  Handle<Script> script = factory->NewScript(factory->empty_string());
287
  script->set_source(ReadOnlyRoots(CcTest::heap()).undefined_value());
288 289 290
  CHECK_EQ(-1, Script::GetLineNumber(script, 0));
  CHECK_EQ(-1, Script::GetLineNumber(script, 100));
  CHECK_EQ(-1, Script::GetLineNumber(script, -1));
291
}
292 293 294


TEST(GetScriptLineNumber) {
295
  LocalContext context;
296 297 298
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::ScriptOrigin origin = v8::ScriptOrigin(isolate, v8_str("test"));
299 300 301
  const char function_f[] = "function f() {}";
  const int max_rows = 1000;
  const int buffer_size = max_rows + sizeof(function_f);
302
  base::ScopedVector<char> buffer(buffer_size);
303
  memset(buffer.begin(), '\n', buffer_size - 1);
304 305 306 307 308
  buffer[buffer_size - 1] = '\0';

  for (int i = 0; i < max_rows; ++i) {
    if (i > 0)
      buffer[i - 1] = '\n';
309
    MemCopy(&buffer[i], function_f, sizeof(function_f) - 1);
310
    v8::Local<v8::String> script_body = v8_str(buffer.begin());
311 312 313 314 315 316
    v8::Script::Compile(context.local(), script_body, &origin)
        .ToLocalChecked()
        ->Run(context.local())
        .ToLocalChecked();
    v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
        context->Global()->Get(context.local(), v8_str("f")).ToLocalChecked());
317 318 319
    CHECK_EQ(i, f->GetScriptLineNumber());
  }
}
320 321


322
TEST(FeedbackVectorPreservedAcrossRecompiles) {
323
  if (i::FLAG_always_opt || !i::FLAG_opt) return;
324 325
  i::FLAG_allow_natives_syntax = true;
  CcTest::InitializeVM();
Mythri's avatar
Mythri committed
326
  if (!CcTest::i_isolate()->use_optimizer()) return;
327
  v8::HandleScope scope(CcTest::isolate());
328
  v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
329 330

  // Make sure function f has a call that uses a type feedback slot.
331 332 333 334 335
  CompileRun(
      "function fun() {};"
      "fun1 = fun;"
      "%PrepareFunctionForOptimization(f);"
      "function f(a) { a(); } f(fun1);");
336

337 338 339
  Handle<JSFunction> f = Handle<JSFunction>::cast(
      v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
          CcTest::global()->Get(context, v8_str("f")).ToLocalChecked())));
340 341

  // Verify that we gathered feedback.
342
  Handle<FeedbackVector> feedback_vector(f->feedback_vector(), f->GetIsolate());
343
  CHECK(!feedback_vector->is_empty());
344
  FeedbackSlot slot_for_a(0);
345
  MaybeObject object = feedback_vector->Get(slot_for_a);
346
  {
347
    HeapObject heap_object;
348
    CHECK(object->GetHeapObjectIfWeak(&heap_object));
349
    CHECK(heap_object.IsJSFunction());
350
  }
351 352 353 354 355

  CompileRun("%OptimizeFunctionOnNextCall(f); f(fun1);");

  // Verify that the feedback is still "gathered" despite a recompilation
  // of the full code.
356
  CHECK(f->HasAttachedOptimizedCode());
357
  object = f->feedback_vector().Get(slot_for_a);
358
  {
359
    HeapObject heap_object;
360
    CHECK(object->GetHeapObjectIfWeak(&heap_object));
361
    CHECK(heap_object.IsJSFunction());
362
  }
363 364 365 366
}


TEST(FeedbackVectorUnaffectedByScopeChanges) {
367
  if (i::FLAG_always_opt || !i::FLAG_lazy || i::FLAG_lite_mode) {
368 369
    return;
  }
370 371
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
372
  v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
373 374 375 376 377 378 379 380 381 382 383 384 385

  CompileRun("function builder() {"
             "  call_target = function() { return 3; };"
             "  return (function() {"
             "    eval('');"
             "    return function() {"
             "      'use strict';"
             "      call_target();"
             "    }"
             "  })();"
             "}"
             "morphing_call = builder();");

386 387 388 389
  Handle<JSFunction> f = Handle<JSFunction>::cast(v8::Utils::OpenHandle(
      *v8::Local<v8::Function>::Cast(CcTest::global()
                                         ->Get(context, v8_str("morphing_call"))
                                         .ToLocalChecked())));
390

391 392
  // If we are compiling lazily then it should not be compiled, and so no
  // feedback vector allocated yet.
393
  CHECK(!f->shared().is_compiled());
394 395 396

  CompileRun("morphing_call();");

397
  // Now a feedback vector / closure feedback cell array is allocated.
398
  CHECK(f->shared().is_compiled());
399
  CHECK(f->has_feedback_vector() || f->has_closure_feedback_cell_array());
400 401
}

402
// Test that optimized code for different closures is actually shared.
403
TEST(OptimizedCodeSharing1) {
404
  FLAG_stress_compaction = false;
405
  FLAG_allow_natives_syntax = true;
406 407
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
408
  for (int i = 0; i < 3; i++) {
409
    LocalContext env;
410 411 412
    env->Global()
        ->Set(env.local(), v8_str("x"), v8::Integer::New(CcTest::isolate(), i))
        .FromJust();
413 414 415 416 417
    CompileRun(
        "function MakeClosure() {"
        "  return function() { return x; };"
        "}"
        "var closure0 = MakeClosure();"
418 419
        "var closure1 = MakeClosure();"  // We only share optimized code
                                         // if there are at least two closures.
420
        "%PrepareFunctionForOptimization(closure0);"
421 422 423
        "%DebugPrint(closure0());"
        "%OptimizeFunctionOnNextCall(closure0);"
        "%DebugPrint(closure0());"
424
        "closure1();"
425
        "var closure2 = MakeClosure(); closure2();");
426 427
    Handle<JSFunction> fun1 = Handle<JSFunction>::cast(
        v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
428 429 430
            env->Global()
                ->Get(env.local(), v8_str("closure1"))
                .ToLocalChecked())));
431 432
    Handle<JSFunction> fun2 = Handle<JSFunction>::cast(
        v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
433 434 435
            env->Global()
                ->Get(env.local(), v8_str("closure2"))
                .ToLocalChecked())));
436 437 438 439
    CHECK(fun1->HasAttachedOptimizedCode() ||
          !CcTest::i_isolate()->use_optimizer());
    CHECK(fun2->HasAttachedOptimizedCode() ||
          !CcTest::i_isolate()->use_optimizer());
440 441 442 443
    CHECK_EQ(fun1->code(), fun2->code());
  }
}

444
TEST(CompileFunction) {
445
  if (i::FLAG_always_opt) return;
446 447 448 449
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var r = 10;");
450 451
  v8::Local<v8::Object> math = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("Math")).ToLocalChecked());
452 453 454 455
  v8::ScriptCompiler::Source script_source(v8_str(
      "a = PI * r * r;"
      "x = r * cos(PI);"
      "y = r * sin(PI / 2);"));
456
  v8::Local<v8::Function> fun =
457 458
      v8::ScriptCompiler::CompileFunction(env.local(), &script_source, 0,
                                          nullptr, 1, &math)
459
          .ToLocalChecked();
460
  CHECK(!fun.IsEmpty());
461 462

  i::DisallowCompilation no_compile(CcTest::i_isolate());
463
  fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
464 465 466
  CHECK(env->Global()->Has(env.local(), v8_str("a")).FromJust());
  v8::Local<v8::Value> a =
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked();
467
  CHECK(a->IsNumber());
468 469 470
  CHECK(env->Global()->Has(env.local(), v8_str("x")).FromJust());
  v8::Local<v8::Value> x =
      env->Global()->Get(env.local(), v8_str("x")).ToLocalChecked();
471
  CHECK(x->IsNumber());
472 473 474
  CHECK(env->Global()->Has(env.local(), v8_str("y")).FromJust());
  v8::Local<v8::Value> y =
      env->Global()->Get(env.local(), v8_str("y")).ToLocalChecked();
475
  CHECK(y->IsNumber());
476 477 478
  CHECK_EQ(314.1592653589793, a->NumberValue(env.local()).FromJust());
  CHECK_EQ(-10.0, x->NumberValue(env.local()).FromJust());
  CHECK_EQ(10.0, y->NumberValue(env.local()).FromJust());
479 480
}

481
TEST(CompileFunctionComplex) {
482 483 484 485 486 487 488 489 490 491
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun(
      "var x = 1;"
      "var y = 2;"
      "var z = 4;"
      "var a = {x: 8, y: 16};"
      "var b = {x: 32};");
  v8::Local<v8::Object> ext[2];
492 493 494 495
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
  ext[1] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("b")).ToLocalChecked());
496
  v8::ScriptCompiler::Source script_source(v8_str("result = x + y + z"));
497
  v8::Local<v8::Function> fun =
498 499
      v8::ScriptCompiler::CompileFunction(env.local(), &script_source, 0,
                                          nullptr, 2, ext)
500
          .ToLocalChecked();
501
  CHECK(!fun.IsEmpty());
502
  fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
503 504 505
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
506
  CHECK(result->IsNumber());
507
  CHECK_EQ(52.0, result->NumberValue(env.local()).FromJust());
508 509
}

510
TEST(CompileFunctionArgs) {
511 512 513 514 515
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var a = {x: 23};");
  v8::Local<v8::Object> ext[1];
516 517
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
518 519
  v8::ScriptCompiler::Source script_source(v8_str("result = x + abc"));
  v8::Local<v8::String> arg = v8_str("abc");
520
  v8::Local<v8::Function> fun =
521 522
      v8::ScriptCompiler::CompileFunction(env.local(), &script_source, 1, &arg,
                                          1, ext)
523
          .ToLocalChecked();
524 525 526 527 528
  CHECK_EQ(1, fun->Get(env.local(), v8_str("length"))
                  .ToLocalChecked()
                  ->ToInt32(env.local())
                  .ToLocalChecked()
                  ->Value());
529 530
  v8::Local<v8::Value> arg_value = v8::Number::New(CcTest::isolate(), 42.0);
  fun->Call(env.local(), env->Global(), 1, &arg_value).ToLocalChecked();
531 532 533
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
534
  CHECK(result->IsNumber());
535
  CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
536 537
}

538
TEST(CompileFunctionComments) {
539 540 541 542 543
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var a = {x: 23, y: 1, z: 2};");
  v8::Local<v8::Object> ext[1];
544 545
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
546 547 548 549
  v8::Local<v8::String> source =
      CompileRun("'result = /* y + */ x + a\\u4e00 // + z'").As<v8::String>();
  v8::ScriptCompiler::Source script_source(source);
  v8::Local<v8::String> arg = CompileRun("'a\\u4e00'").As<v8::String>();
550
  v8::Local<v8::Function> fun =
551 552
      v8::ScriptCompiler::CompileFunction(env.local(), &script_source, 1, &arg,
                                          1, ext)
553
          .ToLocalChecked();
554
  CHECK(!fun.IsEmpty());
555 556
  v8::Local<v8::Value> arg_value = v8::Number::New(CcTest::isolate(), 42.0);
  fun->Call(env.local(), env->Global(), 1, &arg_value).ToLocalChecked();
557 558 559
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
560
  CHECK(result->IsNumber());
561
  CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
562 563
}

564
TEST(CompileFunctionNonIdentifierArgs) {
565 566 567 568 569
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  v8::ScriptCompiler::Source script_source(v8_str("result = 1"));
  v8::Local<v8::String> arg = v8_str("b }");
570 571 572
  CHECK(
      v8::ScriptCompiler::CompileFunction(env.local(), &script_source, 1, &arg)
          .IsEmpty());
573 574
}

575
TEST(CompileFunctionRenderCallSite) {
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  static const char* source1 =
      "try {"
      "  var a = [];"
      "  a[0]();"
      "} catch (e) {"
      "  return e.toString();"
      "}";
  static const char* expect1 = "TypeError: a[0] is not a function";
  static const char* source2 =
      "try {"
      "  (function() {"
      "    var a = [];"
      "    a[0]();"
      "  })()"
      "} catch (e) {"
      "  return e.toString();"
      "}";
  static const char* expect2 = "TypeError: a[0] is not a function";
  {
    v8::ScriptCompiler::Source script_source(v8_str(source1));
    v8::Local<v8::Function> fun =
600
        v8::ScriptCompiler::CompileFunction(env.local(), &script_source)
601 602 603 604 605 606 607 608 609 610 611 612
            .ToLocalChecked();
    CHECK(!fun.IsEmpty());
    v8::Local<v8::Value> result =
        fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
    CHECK(result->IsString());
    CHECK(v8::Local<v8::String>::Cast(result)
              ->Equals(env.local(), v8_str(expect1))
              .FromJust());
  }
  {
    v8::ScriptCompiler::Source script_source(v8_str(source2));
    v8::Local<v8::Function> fun =
613
        v8::ScriptCompiler::CompileFunction(env.local(), &script_source)
614 615 616 617 618 619 620 621 622 623
            .ToLocalChecked();
    v8::Local<v8::Value> result =
        fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
    CHECK(result->IsString());
    CHECK(v8::Local<v8::String>::Cast(result)
              ->Equals(env.local(), v8_str(expect2))
              .FromJust());
  }
}

624
TEST(CompileFunctionQuirks) {
625 626 627 628 629 630 631 632 633 634
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  {
    static const char* source =
        "[x, y] = ['ab', 'cd'];"
        "return x + y";
    static const char* expect = "abcd";
    v8::ScriptCompiler::Source script_source(v8_str(source));
    v8::Local<v8::Function> fun =
635
        v8::ScriptCompiler::CompileFunction(env.local(), &script_source)
636 637 638 639 640 641 642 643 644 645 646 647
            .ToLocalChecked();
    v8::Local<v8::Value> result =
        fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
    CHECK(result->IsString());
    CHECK(v8::Local<v8::String>::Cast(result)
              ->Equals(env.local(), v8_str(expect))
              .FromJust());
  }
  {
    static const char* source = "'use strict'; var a = 077";
    v8::ScriptCompiler::Source script_source(v8_str(source));
    v8::TryCatch try_catch(CcTest::isolate());
648
    CHECK(v8::ScriptCompiler::CompileFunction(env.local(), &script_source)
649 650 651 652 653 654 655
              .IsEmpty());
    CHECK(try_catch.HasCaught());
  }
  {
    static const char* source = "{ let x; { var x } }";
    v8::ScriptCompiler::Source script_source(v8_str(source));
    v8::TryCatch try_catch(CcTest::isolate());
656
    CHECK(v8::ScriptCompiler::CompileFunction(env.local(), &script_source)
657 658 659 660
              .IsEmpty());
    CHECK(try_catch.HasCaught());
  }
}
661

662
TEST(CompileFunctionScriptOrigin) {
663
  CcTest::InitializeVM();
664 665
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
666
  LocalContext env;
667
  v8::ScriptOrigin origin(isolate, v8_str("test"), 22, 41);
668
  v8::ScriptCompiler::Source script_source(v8_str("throw new Error()"), origin);
669
  v8::Local<v8::Function> fun =
670
      v8::ScriptCompiler::CompileFunction(env.local(), &script_source)
671
          .ToLocalChecked();
672
  CHECK(!fun.IsEmpty());
673 674
  v8::Local<v8::UnboundScript> script =
      fun->GetUnboundScript().ToLocalChecked();
675
  CHECK(!script.IsEmpty());
676
  CHECK(script->GetScriptName()->StrictEquals(v8_str("test")));
677
  v8::TryCatch try_catch(CcTest::isolate());
678
  CcTest::isolate()->SetCaptureStackTraceForUncaughtExceptions(true);
679
  CHECK(fun->Call(env.local(), env->Global(), 0, nullptr).IsEmpty());
680 681 682 683 684
  CHECK(try_catch.HasCaught());
  CHECK(!try_catch.Exception().IsEmpty());
  v8::Local<v8::StackTrace> stack =
      v8::Exception::GetStackTrace(try_catch.Exception());
  CHECK(!stack.IsEmpty());
685
  CHECK_GT(stack->GetFrameCount(), 0);
686
  v8::Local<v8::StackFrame> frame = stack->GetFrame(CcTest::isolate(), 0);
687 688 689 690
  CHECK_EQ(23, frame->GetLineNumber());
  CHECK_EQ(42 + strlen("throw "), static_cast<unsigned>(frame->GetColumn()));
}

691
void TestCompileFunctionToStringImpl() {
692 693 694 695 696 697 698 699 700 701
#define CHECK_NOT_CAUGHT(__local_context__, try_catch, __op__)             \
  do {                                                                     \
    const char* op = (__op__);                                             \
    v8::Local<v8::Context> context = (__local_context__);                  \
    if (try_catch.HasCaught()) {                                           \
      v8::String::Utf8Value error(                                         \
          CcTest::isolate(),                                               \
          try_catch.Exception()->ToString(context).ToLocalChecked());      \
      FATAL("Unexpected exception thrown during %s:\n\t%s\n", op, *error); \
    }                                                                      \
702
  } while (false)
703

704
  {
705
    CcTest::InitializeVM();
706 707
    v8::Isolate* isolate = CcTest::isolate();
    v8::HandleScope scope(isolate);
708 709 710 711
    LocalContext env;

    // Regression test for v8:6190
    {
712
      v8::ScriptOrigin origin(isolate, v8_str("test"), 22, 41);
713 714 715 716 717
      v8::ScriptCompiler::Source script_source(v8_str("return event"), origin);

      v8::Local<v8::String> params[] = {v8_str("event")};
      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
718 719
          v8::ScriptCompiler::CompileFunction(env.local(), &script_source,
                                              arraysize(params), params);
720 721

      CHECK_NOT_CAUGHT(env.local(), try_catch,
722
                       "v8::ScriptCompiler::CompileFunction");
723 724 725 726 727 728 729

      v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
      CHECK(!fun.IsEmpty());
      CHECK(!try_catch.HasCaught());
      v8::Local<v8::String> result =
          fun->ToString(env.local()).ToLocalChecked();
      v8::Local<v8::String> expected = v8_str(
730 731
          "function (event) {\n"
          "return event\n"
732 733 734 735 736 737
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
    }

    // With no parameters:
    {
738
      v8::ScriptOrigin origin(isolate, v8_str("test"), 17, 31);
739 740 741 742
      v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);

      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
743
          v8::ScriptCompiler::CompileFunction(env.local(), &script_source);
744 745

      CHECK_NOT_CAUGHT(env.local(), try_catch,
746
                       "v8::ScriptCompiler::CompileFunction");
747 748 749 750 751 752 753

      v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
      CHECK(!fun.IsEmpty());
      CHECK(!try_catch.HasCaught());
      v8::Local<v8::String> result =
          fun->ToString(env.local()).ToLocalChecked();
      v8::Local<v8::String> expected = v8_str(
754 755
          "function () {\n"
          "return 0\n"
756 757
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
758 759 760 761
    }

    // With a name:
    {
762
      v8::ScriptOrigin origin(isolate, v8_str("test"), 17, 31);
763 764 765 766
      v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);

      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
767
          v8::ScriptCompiler::CompileFunction(env.local(), &script_source);
768 769

      CHECK_NOT_CAUGHT(env.local(), try_catch,
770
                       "v8::ScriptCompiler::CompileFunction");
771 772 773 774 775 776 777 778 779 780 781 782 783 784

      v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
      CHECK(!fun.IsEmpty());
      CHECK(!try_catch.HasCaught());

      fun->SetName(v8_str("onclick"));

      v8::Local<v8::String> result =
          fun->ToString(env.local()).ToLocalChecked();
      v8::Local<v8::String> expected = v8_str(
          "function onclick() {\n"
          "return 0\n"
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
785 786 787 788
    }
  }
#undef CHECK_NOT_CAUGHT
}
789

790
TEST(CompileFunctionFunctionToString) { TestCompileFunctionToStringImpl(); }
791

792
TEST(InvocationCount) {
793
  if (FLAG_lite_mode) return;
794 795 796 797 798 799 800
  FLAG_allow_natives_syntax = true;
  FLAG_always_opt = false;
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());

  CompileRun(
      "function bar() {};"
801
      "%EnsureFeedbackVectorForFunction(bar);"
802
      "function foo() { return bar(); };"
803
      "%EnsureFeedbackVectorForFunction(foo);"
804 805
      "foo();");
  Handle<JSFunction> foo = Handle<JSFunction>::cast(GetGlobalProperty("foo"));
806
  CHECK_EQ(1, foo->feedback_vector().invocation_count());
807
  CompileRun("foo()");
808
  CHECK_EQ(2, foo->feedback_vector().invocation_count());
809
  CompileRun("bar()");
810
  CHECK_EQ(2, foo->feedback_vector().invocation_count());
811
  CompileRun("foo(); foo()");
812
  CHECK_EQ(4, foo->feedback_vector().invocation_count());
813
}
814

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
TEST(ShallowEagerCompilation) {
  i::FLAG_always_opt = false;
  CcTest::InitializeVM();
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::String> source = v8_str(
      "function f(x) {"
      "  return x + x;"
      "}"
      "f(2)");
  v8::ScriptCompiler::Source script_source(source);
  v8::Local<v8::Script> script =
      v8::ScriptCompiler::Compile(env.local(), &script_source,
                                  v8::ScriptCompiler::kEagerCompile)
          .ToLocalChecked();
  {
    v8::internal::DisallowCompilation no_compile_expected(isolate);
    v8::Local<v8::Value> result = script->Run(env.local()).ToLocalChecked();
    CHECK_EQ(4, result->Int32Value(env.local()).FromJust());
  }
}

TEST(DeepEagerCompilation) {
  i::FLAG_always_opt = false;
  CcTest::InitializeVM();
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::String> source = v8_str(
      "function f(x) {"
      "  function g(x) {"
      "    function h(x) {"
      "      return x ** x;"
      "    }"
      "    return h(x) * h(x);"
      "  }"
      "  return g(x) + g(x);"
      "}"
      "f(2)");
  v8::ScriptCompiler::Source script_source(source);
  v8::Local<v8::Script> script =
      v8::ScriptCompiler::Compile(env.local(), &script_source,
                                  v8::ScriptCompiler::kEagerCompile)
          .ToLocalChecked();
  {
    v8::internal::DisallowCompilation no_compile_expected(isolate);
    v8::Local<v8::Value> result = script->Run(env.local()).ToLocalChecked();
    CHECK_EQ(32, result->Int32Value(env.local()).FromJust());
  }
}

867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
TEST(DeepEagerCompilationPeakMemory) {
  i::FLAG_always_opt = false;
  CcTest::InitializeVM();
  LocalContext env;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::String> source = v8_str(
      "function f() {"
      "  function g1() {"
      "    function h1() {"
      "      function i1() {}"
      "      function i2() {}"
      "    }"
      "    function h2() {"
      "      function i1() {}"
      "      function i2() {}"
      "    }"
      "  }"
      "  function g2() {"
      "    function h1() {"
      "      function i1() {}"
      "      function i2() {}"
      "    }"
      "    function h2() {"
      "      function i1() {}"
      "      function i2() {}"
      "    }"
      "  }"
      "}");
  v8::ScriptCompiler::Source script_source(source);
896
  CcTest::i_isolate()->compilation_cache()->DisableScriptAndEval();
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929

  v8::HeapStatistics heap_statistics;
  CcTest::isolate()->GetHeapStatistics(&heap_statistics);
  size_t peak_mem_1 = heap_statistics.peak_malloced_memory();
  printf("peak memory after init:          %8zu\n", peak_mem_1);

  v8::ScriptCompiler::Compile(env.local(), &script_source,
                              v8::ScriptCompiler::kNoCompileOptions)
      .ToLocalChecked();

  CcTest::isolate()->GetHeapStatistics(&heap_statistics);
  size_t peak_mem_2 = heap_statistics.peak_malloced_memory();
  printf("peak memory after lazy compile:  %8zu\n", peak_mem_2);

  v8::ScriptCompiler::Compile(env.local(), &script_source,
                              v8::ScriptCompiler::kNoCompileOptions)
      .ToLocalChecked();

  CcTest::isolate()->GetHeapStatistics(&heap_statistics);
  size_t peak_mem_3 = heap_statistics.peak_malloced_memory();
  printf("peak memory after lazy compile:  %8zu\n", peak_mem_3);

  v8::ScriptCompiler::Compile(env.local(), &script_source,
                              v8::ScriptCompiler::kEagerCompile)
      .ToLocalChecked();

  CcTest::isolate()->GetHeapStatistics(&heap_statistics);
  size_t peak_mem_4 = heap_statistics.peak_malloced_memory();
  printf("peak memory after eager compile: %8zu\n", peak_mem_4);

  CHECK_LE(peak_mem_1, peak_mem_2);
  CHECK_EQ(peak_mem_2, peak_mem_3);
  CHECK_LE(peak_mem_3, peak_mem_4);
930
  // Check that eager compilation does not cause significantly higher (+100%)
931
  // peak memory than lazy compilation.
932
  CHECK_LE(peak_mem_4 - peak_mem_3, peak_mem_3);
933 934
}

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
namespace {

// Dummy external source stream which returns the whole source in one go.
class DummySourceStream : public v8::ScriptCompiler::ExternalSourceStream {
 public:
  explicit DummySourceStream(const char* source) : done_(false) {
    source_length_ = static_cast<int>(strlen(source));
    source_buffer_ = source;
  }

  size_t GetMoreData(const uint8_t** dest) override {
    if (done_) {
      return 0;
    }
    uint8_t* buf = new uint8_t[source_length_ + 1];
    memcpy(buf, source_buffer_, source_length_ + 1);
    *dest = buf;
    done_ = true;
    return source_length_;
  }

 private:
  int source_length_;
  const char* source_buffer_;
  bool done_;
};

}  // namespace

// Tests that doing something that causes source positions to need to be
// collected after a background compilation task has started does result in
// source positions being collected.
TEST(ProfilerEnabledDuringBackgroundCompile) {
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  const char* source = "var a = 0;";

  v8::ScriptCompiler::StreamedSource streamed_source(
      std::make_unique<DummySourceStream>(source),
      v8::ScriptCompiler::StreamedSource::UTF8);
  std::unique_ptr<v8::ScriptCompiler::ScriptStreamingTask> task(
977
      v8::ScriptCompiler::StartStreaming(isolate, &streamed_source));
978

979 980 981
  // Run the background compilation task. DummySourceStream::GetMoreData won't
  // block, so it's OK to just join the background task.
  StreamerThread::StartThreadForTaskAndJoin(task.get());
982 983 984 985 986 987 988 989 990 991 992

  // Enable the CPU profiler.
  auto* cpu_profiler = v8::CpuProfiler::New(isolate, v8::kStandardNaming);
  v8::Local<v8::String> profile = v8_str("profile");
  cpu_profiler->StartProfiling(profile);

  // Finalize the background compilation task ensuring it completed
  // successfully.
  v8::Local<v8::Script> script =
      v8::ScriptCompiler::Compile(isolate->GetCurrentContext(),
                                  &streamed_source, v8_str(source),
993
                                  v8::ScriptOrigin(isolate, v8_str("foo")))
994 995 996
          .ToLocalChecked();

  i::Handle<i::Object> obj = Utils::OpenHandle(*script);
997 998
  CHECK(i::JSFunction::cast(*obj).shared().AreSourcePositionsAvailable(
      CcTest::i_isolate()));
999 1000 1001 1002

  cpu_profiler->StopProfiling(profile);
}

1003 1004
}  // namespace internal
}  // namespace v8