test-compiler.cc 38.3 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 "src/v8.h"
32

33
#include "src/api/api-inl.h"
34 35
#include "src/codegen/compilation-cache.h"
#include "src/codegen/compiler.h"
36
#include "src/diagnostics/disasm.h"
37
#include "src/heap/factory.h"
38
#include "src/heap/spaces.h"
39
#include "src/interpreter/interpreter.h"
40
#include "src/objects-inl.h"
41
#include "src/objects/allocation-site-inl.h"
42
#include "test/cctest/cctest.h"
43

44 45
namespace v8 {
namespace internal {
46

47
static Handle<Object> GetGlobalProperty(const char* name) {
48
  Isolate* isolate = CcTest::i_isolate();
49 50
  return JSReceiver::GetProperty(isolate, isolate->global_object(), name)
      .ToHandleChecked();
51 52
}

53
static void SetGlobalProperty(const char* name, Object value) {
54
  Isolate* isolate = CcTest::i_isolate();
55
  Handle<Object> object(value, isolate);
56 57
  Handle<String> internalized_name =
      isolate->factory()->InternalizeUtf8String(name);
58
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
59
  Runtime::SetObjectProperty(isolate, global, internalized_name, object,
60
                             StoreOrigin::kMaybeKeyed, Just(kDontThrow))
61
      .Check();
62 63 64
}

static Handle<JSFunction> Compile(const char* source) {
65
  Isolate* isolate = CcTest::i_isolate();
66 67
  Handle<String> source_code = isolate->factory()->NewStringFromUtf8(
      CStrVector(source)).ToHandleChecked();
68 69
  Handle<SharedFunctionInfo> shared =
      Compiler::GetSharedFunctionInfoForScript(
70 71 72
          isolate, source_code, Compiler::ScriptDetails(),
          v8::ScriptOriginOptions(), nullptr, nullptr,
          v8::ScriptCompiler::kNoCompileOptions,
73
          ScriptCompiler::kNoCacheNoReason, NOT_NATIVES_CODE)
74
          .ToHandleChecked();
75
  return isolate->factory()->NewFunctionFromSharedFunctionInfo(
76
      shared, isolate->native_context());
77 78 79
}


80
static double Inc(Isolate* isolate, int x) {
81
  const char* source = "result = %d + 1;";
82
  EmbeddedVector<char, 512> buffer;
83
  SNPrintF(buffer, source, x);
84

85
  Handle<JSFunction> fun = Compile(buffer.begin());
86 87
  if (fun.is_null()) return -1;

88
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
89
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
90
  return GetGlobalProperty("result")->Number();
91 92 93 94
}


TEST(Inc) {
95 96
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
97
  CHECK_EQ(4.0, Inc(CcTest::i_isolate(), 3));
98 99 100
}


101
static double Add(Isolate* isolate, int x, int y) {
102 103 104 105 106
  Handle<JSFunction> fun = Compile("result = x + y;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("x", Smi::FromInt(x));
  SetGlobalProperty("y", Smi::FromInt(y));
107
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
108
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
109
  return GetGlobalProperty("result")->Number();
110 111 112 113
}


TEST(Add) {
114 115
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
116
  CHECK_EQ(5.0, Add(CcTest::i_isolate(), 2, 3));
117 118 119
}


120
static double Abs(Isolate* isolate, int x) {
121 122 123 124
  Handle<JSFunction> fun = Compile("if (x < 0) result = -x; else result = x;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("x", Smi::FromInt(x));
125
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
126
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
127
  return GetGlobalProperty("result")->Number();
128 129 130 131
}


TEST(Abs) {
132 133
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
134
  CHECK_EQ(3.0, Abs(CcTest::i_isolate(), -3));
135 136 137
}


138
static double Sum(Isolate* isolate, int n) {
139 140 141 142 143
  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));
144
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
145
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
146
  return GetGlobalProperty("result")->Number();
147 148 149 150
}


TEST(Sum) {
151 152
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
153
  CHECK_EQ(5050.0, Sum(CcTest::i_isolate(), 100));
154 155 156 157
}


TEST(Print) {
158
  v8::HandleScope scope(CcTest::isolate());
159
  v8::Local<v8::Context> context = CcTest::NewContext({PRINT_EXTENSION_ID});
160
  v8::Context::Scope context_scope(context);
161 162 163
  const char* source = "for (n = 0; n < 100; ++n) print(n, 1, 2);";
  Handle<JSFunction> fun = Compile(source);
  if (fun.is_null()) return;
164 165
  Handle<JSObject> global(CcTest::i_isolate()->context()->global_object(),
                          fun->GetIsolate());
166
  Execution::Call(CcTest::i_isolate(), fun, global, 0, nullptr).Check();
167 168 169 170 171 172
}


// The following test method stems from my coding efforts today. It
// tests all the functionality I have added to the compiler today
TEST(Stuff) {
173 174
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
  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());
196 197
  Handle<JSObject> global(CcTest::i_isolate()->context()->global_object(),
                          fun->GetIsolate());
198
  Execution::Call(CcTest::i_isolate(), fun, global, 0, nullptr).Check();
199
  CHECK_EQ(511.0, GetGlobalProperty("r")->Number());
200 201 202 203
}


TEST(UncaughtThrow) {
204 205
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
206 207 208 209

  const char* source = "throw 42;";
  Handle<JSFunction> fun = Compile(source);
  CHECK(!fun.is_null());
210
  Isolate* isolate = fun->GetIsolate();
211
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
212
  CHECK(Execution::Call(isolate, fun, global, 0, nullptr).is_null());
213
  CHECK_EQ(42.0, isolate->pending_exception()->Number());
214 215 216 217 218 219 220 221 222 223
}


// 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) {
224
  FLAG_expose_gc = true;
225
  v8::HandleScope scope(CcTest::isolate());
226
  v8::Local<v8::Context> context =
227
      CcTest::NewContext({PRINT_EXTENSION_ID, GC_EXTENSION_ID});
228
  v8::Context::Scope context_scope(context);
229 230 231 232 233

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

  Handle<JSFunction> fun0 = Compile(source);
  CHECK(!fun0.is_null());
234
  Isolate* isolate = fun0->GetIsolate();
235 236

  // Run the generated code to populate the global object with 'foo'.
237
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
238
  Execution::Call(isolate, fun0, global, 0, nullptr).Check();
239

240 241 242
  Handle<Object> fun1 =
      JSReceiver::GetProperty(isolate, isolate->global_object(), "foo")
          .ToHandleChecked();
243 244
  CHECK(fun1->IsJSFunction());

245 246
  Handle<Object> argv[] = {
      isolate->factory()->InternalizeOneByteString(StaticCharVector("hello"))};
247 248
  Execution::Call(isolate,
                  Handle<JSFunction>::cast(fun1),
249
                  global,
250
                  arraysize(argv),
251
                  argv).Check();
252
}
253 254 255 256 257


// Regression 236. Calling InitLineEnds on a Script with undefined
// source resulted in crash.
TEST(Regression236) {
258
  CcTest::InitializeVM();
259
  Isolate* isolate = CcTest::i_isolate();
260
  Factory* factory = isolate->factory();
261
  v8::HandleScope scope(CcTest::isolate());
262

263
  Handle<Script> script = factory->NewScript(factory->empty_string());
264
  script->set_source(ReadOnlyRoots(CcTest::heap()).undefined_value());
265 266 267
  CHECK_EQ(-1, Script::GetLineNumber(script, 0));
  CHECK_EQ(-1, Script::GetLineNumber(script, 100));
  CHECK_EQ(-1, Script::GetLineNumber(script, -1));
268
}
269 270 271


TEST(GetScriptLineNumber) {
272
  LocalContext context;
273
  v8::HandleScope scope(CcTest::isolate());
274
  v8::ScriptOrigin origin = v8::ScriptOrigin(v8_str("test"));
275 276 277 278
  const char function_f[] = "function f() {}";
  const int max_rows = 1000;
  const int buffer_size = max_rows + sizeof(function_f);
  ScopedVector<char> buffer(buffer_size);
279
  memset(buffer.begin(), '\n', buffer_size - 1);
280 281 282 283 284
  buffer[buffer_size - 1] = '\0';

  for (int i = 0; i < max_rows; ++i) {
    if (i > 0)
      buffer[i - 1] = '\n';
285
    MemCopy(&buffer[i], function_f, sizeof(function_f) - 1);
286
    v8::Local<v8::String> script_body = v8_str(buffer.begin());
287 288 289 290 291 292
    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());
293 294 295
    CHECK_EQ(i, f->GetScriptLineNumber());
  }
}
296 297


298
TEST(FeedbackVectorPreservedAcrossRecompiles) {
299
  if (i::FLAG_always_opt || !i::FLAG_opt) return;
300 301
  i::FLAG_allow_natives_syntax = true;
  CcTest::InitializeVM();
Mythri's avatar
Mythri committed
302
  if (!CcTest::i_isolate()->use_optimizer()) return;
303
  v8::HandleScope scope(CcTest::isolate());
304
  v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
305 306

  // Make sure function f has a call that uses a type feedback slot.
307 308 309 310 311
  CompileRun(
      "function fun() {};"
      "fun1 = fun;"
      "%PrepareFunctionForOptimization(f);"
      "function f(a) { a(); } f(fun1);");
312

313 314 315
  Handle<JSFunction> f = Handle<JSFunction>::cast(
      v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
          CcTest::global()->Get(context, v8_str("f")).ToLocalChecked())));
316 317

  // Verify that we gathered feedback.
318
  Handle<FeedbackVector> feedback_vector(f->feedback_vector(), f->GetIsolate());
319
  CHECK(!feedback_vector->is_empty());
320
  FeedbackSlot slot_for_a(0);
321
  MaybeObject object = feedback_vector->Get(slot_for_a);
322
  {
323
    HeapObject heap_object;
324
    CHECK(object->GetHeapObjectIfWeak(&heap_object));
325 326
    CHECK(heap_object->IsJSFunction());
  }
327 328 329 330 331 332

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

  // Verify that the feedback is still "gathered" despite a recompilation
  // of the full code.
  CHECK(f->IsOptimized());
333
  object = f->feedback_vector()->Get(slot_for_a);
334
  {
335
    HeapObject heap_object;
336
    CHECK(object->GetHeapObjectIfWeak(&heap_object));
337 338
    CHECK(heap_object->IsJSFunction());
  }
339 340 341 342
}


TEST(FeedbackVectorUnaffectedByScopeChanges) {
343
  if (i::FLAG_always_opt || !i::FLAG_lazy || i::FLAG_lite_mode) {
344 345
    return;
  }
346 347
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
348
  v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
349 350 351 352 353 354 355 356 357 358 359 360 361

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

362 363 364 365
  Handle<JSFunction> f = Handle<JSFunction>::cast(v8::Utils::OpenHandle(
      *v8::Local<v8::Function>::Cast(CcTest::global()
                                         ->Get(context, v8_str("morphing_call"))
                                         .ToLocalChecked())));
366

367 368
  // If we are compiling lazily then it should not be compiled, and so no
  // feedback vector allocated yet.
369 370 371 372
  CHECK(!f->shared()->is_compiled());

  CompileRun("morphing_call();");

373
  // Now a feedback vector / closure feedback cell array is allocated.
374
  CHECK(f->shared()->is_compiled());
375
  CHECK(f->has_feedback_vector() || f->has_closure_feedback_cell_array());
376 377
}

378
// Test that optimized code for different closures is actually shared.
379
TEST(OptimizedCodeSharing1) {
380
  FLAG_stress_compaction = false;
381
  FLAG_allow_natives_syntax = true;
382 383
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
384
  for (int i = 0; i < 3; i++) {
385
    LocalContext env;
386 387 388
    env->Global()
        ->Set(env.local(), v8_str("x"), v8::Integer::New(CcTest::isolate(), i))
        .FromJust();
389 390 391 392 393
    CompileRun(
        "function MakeClosure() {"
        "  return function() { return x; };"
        "}"
        "var closure0 = MakeClosure();"
394 395
        "var closure1 = MakeClosure();"  // We only share optimized code
                                         // if there are at least two closures.
396
        "%PrepareFunctionForOptimization(closure0);"
397 398 399
        "%DebugPrint(closure0());"
        "%OptimizeFunctionOnNextCall(closure0);"
        "%DebugPrint(closure0());"
400
        "closure1();"
401
        "var closure2 = MakeClosure(); closure2();");
402 403
    Handle<JSFunction> fun1 = Handle<JSFunction>::cast(
        v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
404 405 406
            env->Global()
                ->Get(env.local(), v8_str("closure1"))
                .ToLocalChecked())));
407 408
    Handle<JSFunction> fun2 = Handle<JSFunction>::cast(
        v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
409 410 411
            env->Global()
                ->Get(env.local(), v8_str("closure2"))
                .ToLocalChecked())));
Mythri's avatar
Mythri committed
412 413
    CHECK(fun1->IsOptimized() || !CcTest::i_isolate()->use_optimizer());
    CHECK(fun2->IsOptimized() || !CcTest::i_isolate()->use_optimizer());
414 415 416 417
    CHECK_EQ(fun1->code(), fun2->code());
  }
}

418
TEST(CompileFunctionInContext) {
419
  if (i::FLAG_always_opt) return;
420 421 422 423
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var r = 10;");
424 425
  v8::Local<v8::Object> math = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("Math")).ToLocalChecked());
426 427 428 429
  v8::ScriptCompiler::Source script_source(v8_str(
      "a = PI * r * r;"
      "x = r * cos(PI);"
      "y = r * sin(PI / 2);"));
430 431
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
432
                                                   0, nullptr, 1, &math)
433
          .ToLocalChecked();
434
  CHECK(!fun.IsEmpty());
435 436

  i::DisallowCompilation no_compile(CcTest::i_isolate());
437
  fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
438 439 440
  CHECK(env->Global()->Has(env.local(), v8_str("a")).FromJust());
  v8::Local<v8::Value> a =
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked();
441
  CHECK(a->IsNumber());
442 443 444
  CHECK(env->Global()->Has(env.local(), v8_str("x")).FromJust());
  v8::Local<v8::Value> x =
      env->Global()->Get(env.local(), v8_str("x")).ToLocalChecked();
445
  CHECK(x->IsNumber());
446 447 448
  CHECK(env->Global()->Has(env.local(), v8_str("y")).FromJust());
  v8::Local<v8::Value> y =
      env->Global()->Get(env.local(), v8_str("y")).ToLocalChecked();
449
  CHECK(y->IsNumber());
450 451 452
  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());
453 454 455 456 457 458 459 460 461 462 463 464 465 466
}


TEST(CompileFunctionInContextComplex) {
  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];
467 468 469 470
  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());
471
  v8::ScriptCompiler::Source script_source(v8_str("result = x + y + z"));
472 473
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
474
                                                   0, nullptr, 2, ext)
475
          .ToLocalChecked();
476
  CHECK(!fun.IsEmpty());
477
  fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
478 479 480
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
481
  CHECK(result->IsNumber());
482
  CHECK_EQ(52.0, result->NumberValue(env.local()).FromJust());
483 484 485
}


486 487 488 489 490 491
TEST(CompileFunctionInContextArgs) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var a = {x: 23};");
  v8::Local<v8::Object> ext[1];
492 493
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
494 495
  v8::ScriptCompiler::Source script_source(v8_str("result = x + abc"));
  v8::Local<v8::String> arg = v8_str("abc");
496 497 498 499
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
                                                   1, &arg, 1, ext)
          .ToLocalChecked();
500 501 502 503 504
  CHECK_EQ(1, fun->Get(env.local(), v8_str("length"))
                  .ToLocalChecked()
                  ->ToInt32(env.local())
                  .ToLocalChecked()
                  ->Value());
505 506
  v8::Local<v8::Value> arg_value = v8::Number::New(CcTest::isolate(), 42.0);
  fun->Call(env.local(), env->Global(), 1, &arg_value).ToLocalChecked();
507 508 509
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
510
  CHECK(result->IsNumber());
511
  CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
512 513 514 515 516 517 518 519 520
}


TEST(CompileFunctionInContextComments) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var a = {x: 23, y: 1, z: 2};");
  v8::Local<v8::Object> ext[1];
521 522
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
523 524 525 526
  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>();
527 528 529 530
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
                                                   1, &arg, 1, ext)
          .ToLocalChecked();
531
  CHECK(!fun.IsEmpty());
532 533
  v8::Local<v8::Value> arg_value = v8::Number::New(CcTest::isolate(), 42.0);
  fun->Call(env.local(), env->Global(), 1, &arg_value).ToLocalChecked();
534 535 536
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
537
  CHECK(result->IsNumber());
538
  CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
539 540 541 542 543 544 545 546 547
}


TEST(CompileFunctionInContextNonIdentifierArgs) {
  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 }");
548
  CHECK(v8::ScriptCompiler::CompileFunctionInContext(
549
            env.local(), &script_source, 1, &arg, 0, nullptr)
550
            .IsEmpty());
551 552
}

553 554 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 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 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
TEST(CompileFunctionInContextRenderCallSite) {
  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 =
        v8::ScriptCompiler::CompileFunctionInContext(
            env.local(), &script_source, 0, nullptr, 0, nullptr)
            .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 =
        v8::ScriptCompiler::CompileFunctionInContext(
            env.local(), &script_source, 0, nullptr, 0, nullptr)
            .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());
  }
}

TEST(CompileFunctionInContextQuirks) {
  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 =
        v8::ScriptCompiler::CompileFunctionInContext(
            env.local(), &script_source, 0, nullptr, 0, nullptr)
            .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());
    CHECK(v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr)
              .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());
    CHECK(v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr)
              .IsEmpty());
    CHECK(try_catch.HasCaught());
  }
}
644

645 646 647 648 649 650 651 652
TEST(CompileFunctionInContextScriptOrigin) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  v8::ScriptOrigin origin(v8_str("test"),
                          v8::Integer::New(CcTest::isolate(), 22),
                          v8::Integer::New(CcTest::isolate(), 41));
  v8::ScriptCompiler::Source script_source(v8_str("throw new Error()"), origin);
653 654
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
655
                                                   0, nullptr, 0, nullptr)
656
          .ToLocalChecked();
657
  CHECK(!fun.IsEmpty());
658
  v8::TryCatch try_catch(CcTest::isolate());
659
  CcTest::isolate()->SetCaptureStackTraceForUncaughtExceptions(true);
660
  CHECK(fun->Call(env.local(), env->Global(), 0, nullptr).IsEmpty());
661 662 663 664 665
  CHECK(try_catch.HasCaught());
  CHECK(!try_catch.Exception().IsEmpty());
  v8::Local<v8::StackTrace> stack =
      v8::Exception::GetStackTrace(try_catch.Exception());
  CHECK(!stack.IsEmpty());
666
  CHECK_GT(stack->GetFrameCount(), 0);
667
  v8::Local<v8::StackFrame> frame = stack->GetFrame(CcTest::isolate(), 0);
668 669 670 671
  CHECK_EQ(23, frame->GetLineNumber());
  CHECK_EQ(42 + strlen("throw "), static_cast<unsigned>(frame->GetColumn()));
}

672
void TestCompileFunctionInContextToStringImpl() {
673 674 675 676 677 678 679 680 681 682
#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); \
    }                                                                      \
683
  } while (false)
684

685
  {  // NOLINT
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
    CcTest::InitializeVM();
    v8::HandleScope scope(CcTest::isolate());
    LocalContext env;

    // Regression test for v8:6190
    {
      v8::ScriptOrigin origin(v8_str("test"), v8_int(22), v8_int(41));
      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 =
          v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, arraysize(params), params, 0,
              nullptr);

      CHECK_NOT_CAUGHT(env.local(), try_catch,
                       "v8::ScriptCompiler::CompileFunctionInContext");

      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(
711 712
          "function (event) {\n"
          "return event\n"
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
    }

    // With no parameters:
    {
      v8::ScriptOrigin origin(v8_str("test"), v8_int(17), v8_int(31));
      v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);

      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
          v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr);

      CHECK_NOT_CAUGHT(env.local(), try_catch,
                       "v8::ScriptCompiler::CompileFunctionInContext");

      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(
736 737
          "function () {\n"
          "return 0\n"
738 739
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
    }

    // With a name:
    {
      v8::ScriptOrigin origin(v8_str("test"), v8_int(17), v8_int(31));
      v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);

      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
          v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr);

      CHECK_NOT_CAUGHT(env.local(), try_catch,
                       "v8::ScriptCompiler::CompileFunctionInContext");

      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());
768 769 770 771
    }
  }
#undef CHECK_NOT_CAUGHT
}
772

773 774 775 776
TEST(CompileFunctionInContextFunctionToString) {
  TestCompileFunctionInContextToStringImpl();
}

777
TEST(InvocationCount) {
778
  if (FLAG_lite_mode) return;
779 780 781 782 783 784 785
  FLAG_allow_natives_syntax = true;
  FLAG_always_opt = false;
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());

  CompileRun(
      "function bar() {};"
786
      "%EnsureFeedbackVectorForFunction(bar);"
787
      "function foo() { return bar(); };"
788
      "%EnsureFeedbackVectorForFunction(foo);"
789 790 791 792 793 794 795 796 797 798
      "foo();");
  Handle<JSFunction> foo = Handle<JSFunction>::cast(GetGlobalProperty("foo"));
  CHECK_EQ(1, foo->feedback_vector()->invocation_count());
  CompileRun("foo()");
  CHECK_EQ(2, foo->feedback_vector()->invocation_count());
  CompileRun("bar()");
  CHECK_EQ(2, foo->feedback_vector()->invocation_count());
  CompileRun("foo(); foo()");
  CHECK_EQ(4, foo->feedback_vector()->invocation_count());
}
799

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
TEST(SafeToSkipArgumentsAdaptor) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  CompileRun(
      "function a() { \"use strict\"; }; a();"
      "function b() { }; b();"
      "function c() { \"use strict\"; return arguments; }; c();"
      "function d(...args) { return args; }; d();"
      "function e() { \"use strict\"; return eval(\"\"); }; e();"
      "function f(x, y) { \"use strict\"; return x + y; }; f(1, 2);");
  Handle<JSFunction> a = Handle<JSFunction>::cast(GetGlobalProperty("a"));
  CHECK(a->shared()->is_safe_to_skip_arguments_adaptor());
  Handle<JSFunction> b = Handle<JSFunction>::cast(GetGlobalProperty("b"));
  CHECK(!b->shared()->is_safe_to_skip_arguments_adaptor());
  Handle<JSFunction> c = Handle<JSFunction>::cast(GetGlobalProperty("c"));
  CHECK(!c->shared()->is_safe_to_skip_arguments_adaptor());
  Handle<JSFunction> d = Handle<JSFunction>::cast(GetGlobalProperty("d"));
  CHECK(!d->shared()->is_safe_to_skip_arguments_adaptor());
  Handle<JSFunction> e = Handle<JSFunction>::cast(GetGlobalProperty("e"));
  CHECK(!e->shared()->is_safe_to_skip_arguments_adaptor());
  Handle<JSFunction> f = Handle<JSFunction>::cast(GetGlobalProperty("f"));
  CHECK(f->shared()->is_safe_to_skip_arguments_adaptor());
}

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 867 868 869 870 871 872 873 874 875
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());
  }
}

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 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 930 931 932 933 934 935 936 937 938
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);
  CcTest::i_isolate()->compilation_cache()->Disable();

  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);
939
  // Check that eager compilation does not cause significantly higher (+100%)
940
  // peak memory than lazy compilation.
941
  CHECK_LE(peak_mem_4 - peak_mem_3, peak_mem_3);
942 943
}

944 945 946
// TODO(mslekova): Remove the duplication with test-heap.cc
static int AllocationSitesCount(Heap* heap) {
  int count = 0;
947
  for (Object site = heap->allocation_sites_list(); site->IsAllocationSite();) {
948
    AllocationSite cur = AllocationSite::cast(site);
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
    CHECK(cur->HasWeakNext());
    site = cur->weak_next();
    count++;
  }
  return count;
}

// This test simulates a specific race-condition if GC is triggered just
// before CompilationDependencies::Commit is finished, and this changes
// the pretenuring decision, thus causing a deoptimization.
TEST(DecideToPretenureDuringCompilation) {
  // The test makes use of optimization and relies on deterministic
  // compilation.
  if (!i::FLAG_opt || i::FLAG_always_opt ||
      i::FLAG_stress_incremental_marking || i::FLAG_optimize_for_size
#ifdef ENABLE_MINOR_MC
      || i::FLAG_minor_mc
#endif
  )
    return;

  FLAG_stress_gc_during_compilation = true;
  FLAG_allow_natives_syntax = true;
  FLAG_allocation_site_pretenuring = true;
973
  FLAG_flush_bytecode = false;
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

  // We want to trigger exactly 1 optimization.
  FLAG_use_osr = false;

  // We'll do manual initialization.
  ManualGCScope manual_gc_scope;
  v8::Isolate::CreateParams create_params;

  // This setting ensures Heap::MaximumSizeScavenge will return `true`.
  // We need to initialize the heap with at least 1 page, while keeping the
  // limit low, to ensure the new space fills even on 32-bit architectures.
  create_params.constraints.set_max_semi_space_size_in_kb(Page::kPageSize /
                                                          1024);
  create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
  v8::Isolate* isolate = v8::Isolate::New(create_params);

  isolate->Enter();
  {
    i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
    Heap* heap = i_isolate->heap();
    GlobalHandles* global_handles = i_isolate->global_handles();
    HandleScope handle_scope(i_isolate);

    // The allocation site at the head of the list is ours.
    Handle<AllocationSite> site;
    {
      LocalContext context(isolate);
      v8::HandleScope scope(context->GetIsolate());

      int count = AllocationSitesCount(heap);
      CompileRun(
          "let arr = [];"
          "function foo(shouldKeep) {"
          "  let local_array = new Array();"
          "  if (shouldKeep) arr.push(local_array);"
          "}"
          "function bar(shouldKeep) {"
          "  for (let i = 0; i < 10000; i++) {"
          "    foo(shouldKeep);"
          "  }"
          "}"
1015
          "%PrepareFunctionForOptimization(bar);"
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
          "bar();");

      // This number should be >= kPretenureRatio * 10000,
      // where 10000 is the number of iterations in `bar`,
      // in order to make the ratio in DigestPretenuringFeedback close to 1.
      const int memento_found_bump = 8500;

      // One allocation site should have been created.
      int new_count = AllocationSitesCount(heap);
      CHECK_EQ(new_count, (count + 1));
      site = Handle<AllocationSite>::cast(global_handles->Create(
          AllocationSite::cast(heap->allocation_sites_list())));
      site->set_memento_found_count(memento_found_bump);

      CompileRun("%OptimizeFunctionOnNextCall(bar);");
      CompileRun("bar(true);");

      // The last call should have caused `foo` to bail out of compilation
      // due to dependency change (the pretenuring decision in this case).
      // This will cause recompilation.

      // Check `bar` can get optimized again, meaning the compiler state is
      // recoverable from this point.
1039 1040 1041
      CompileRun(
          "%PrepareFunctionForOptimization(bar);"
          "%OptimizeFunctionOnNextCall(bar);");
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
      CompileRun("bar();");

      Handle<Object> foo_obj =
          JSReceiver::GetProperty(i_isolate, i_isolate->global_object(), "bar")
              .ToHandleChecked();
      Handle<JSFunction> bar = Handle<JSFunction>::cast(foo_obj);

      CHECK(bar->IsOptimized());
    }
  }
  isolate->Exit();
  isolate->Dispose();
}

1056 1057
}  // namespace internal
}  // namespace v8