Commit b8a01ce0 authored by jameslahm's avatar jameslahm Committed by V8 LUCI CQ

[test] Move cctest/test-compiler to unittests

... /compiler/compiler-unittest.

- Add PrintExtension for adding print function.
- Add WithPrintExtensionMixin to register
PrintExtension.
- Add StreamerThread to run a ScriptStreamingTask
in a separate thread.

Bug: v8:12781
Change-Id: I9d3324f3a8dcf00b5b121db6007c9a3cb2972313
Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/3596442Reviewed-by: 's avatarLeszek Swirski <leszeks@chromium.org>
Commit-Queue: 王澳 <wangao.james@bytedance.com>
Cr-Commit-Position: refs/heads/main@{#80084}
parent f7cc70de
......@@ -200,7 +200,6 @@ v8_source_set("cctest_sources") {
"test-code-layout.cc",
"test-code-pages.cc",
"test-code-stub-assembler.cc",
"test-compiler.cc",
"test-concurrent-descriptor-array.cc",
"test-concurrent-feedback-vector.cc",
"test-concurrent-js-array.cc",
......
......@@ -257,6 +257,7 @@ v8_source_set("unittests_sources") {
"compiler/common-operator-reducer-unittest.cc",
"compiler/common-operator-unittest.cc",
"compiler/compiler-test-utils.h",
"compiler/compiler-unittest.cc",
"compiler/constant-folding-reducer-unittest.cc",
"compiler/control-equivalence-unittest.cc",
"compiler/control-flow-optimizer-unittest.cc",
......
// Copyright 2012 the V8 project authors. All rights reserved.
// 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.
// Copyright 2022 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/codegen/compiler.h"
#include <stdlib.h>
#include <wchar.h>
......@@ -36,7 +15,6 @@
#include "include/v8-script.h"
#include "src/api/api-inl.h"
#include "src/codegen/compilation-cache.h"
#include "src/codegen/compiler.h"
#include "src/codegen/script-details.h"
#include "src/diagnostics/disasm.h"
#include "src/heap/factory.h"
......@@ -46,19 +24,22 @@
#include "src/objects/allocation-site-inl.h"
#include "src/objects/objects-inl.h"
#include "src/objects/shared-function-info.h"
#include "test/cctest/cctest.h"
#include "test/unittests/test-utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace v8 {
using CompilerTest = TestWithContext;
namespace internal {
static Handle<Object> GetGlobalProperty(const char* name) {
Isolate* isolate = CcTest::i_isolate();
Isolate* isolate = reinterpret_cast<i::Isolate*>(v8::Isolate::GetCurrent());
return JSReceiver::GetProperty(isolate, isolate->global_object(), name)
.ToHandleChecked();
}
static void SetGlobalProperty(const char* name, Object value) {
Isolate* isolate = CcTest::i_isolate();
Isolate* isolate = reinterpret_cast<i::Isolate*>(v8::Isolate::GetCurrent());
Handle<Object> object(value, isolate);
Handle<String> internalized_name =
isolate->factory()->InternalizeUtf8String(name);
......@@ -69,7 +50,7 @@ static void SetGlobalProperty(const char* name, Object value) {
}
static Handle<JSFunction> Compile(const char* source) {
Isolate* isolate = CcTest::i_isolate();
Isolate* isolate = reinterpret_cast<i::Isolate*>(v8::Isolate::GetCurrent());
Handle<String> source_code = isolate->factory()
->NewStringFromUtf8(base::CStrVector(source))
.ToHandleChecked();
......@@ -83,7 +64,6 @@ static Handle<JSFunction> Compile(const char* source) {
.Build();
}
static double Inc(Isolate* isolate, int x) {
const char* source = "result = %d + 1;";
base::EmbeddedVector<char, 512> buffer;
......@@ -99,14 +79,11 @@ static double Inc(Isolate* isolate, int x) {
return GetGlobalProperty("result")->Number();
}
TEST(Inc) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
CHECK_EQ(4.0, Inc(CcTest::i_isolate(), 3));
TEST_F(CompilerTest, Inc) {
v8::HandleScope scope(isolate());
EXPECT_EQ(4.0, Inc(i_isolate(), 3));
}
static double Add(Isolate* isolate, int x, int y) {
Handle<JSFunction> fun = Compile("result = x + y;");
if (fun.is_null()) return -1;
......@@ -120,14 +97,11 @@ static double Add(Isolate* isolate, int x, int y) {
return GetGlobalProperty("result")->Number();
}
TEST(Add) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
CHECK_EQ(5.0, Add(CcTest::i_isolate(), 2, 3));
TEST_F(CompilerTest, Add) {
v8::HandleScope scope(isolate());
EXPECT_EQ(5.0, Add(i_isolate(), 2, 3));
}
static double Abs(Isolate* isolate, int x) {
Handle<JSFunction> fun = Compile("if (x < 0) result = -x; else result = x;");
if (fun.is_null()) return -1;
......@@ -140,14 +114,11 @@ static double Abs(Isolate* isolate, int x) {
return GetGlobalProperty("result")->Number();
}
TEST(Abs) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
CHECK_EQ(3.0, Abs(CcTest::i_isolate(), -3));
TEST_F(CompilerTest, Abs) {
v8::HandleScope scope(isolate());
EXPECT_EQ(3.0, Abs(i_isolate(), -3));
}
static double Sum(Isolate* isolate, int n) {
Handle<JSFunction> fun =
Compile("s = 0; while (n > 0) { s += n; n -= 1; }; result = s;");
......@@ -161,79 +132,76 @@ static double Sum(Isolate* isolate, int n) {
return GetGlobalProperty("result")->Number();
}
TEST(Sum) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
CHECK_EQ(5050.0, Sum(CcTest::i_isolate(), 100));
TEST_F(CompilerTest, Sum) {
v8::HandleScope scope(isolate());
EXPECT_EQ(5050.0, Sum(i_isolate(), 100));
}
using CompilerPrintTest = WithPrintExtensionMixin<v8::TestWithIsolate>;
TEST(Print) {
v8::HandleScope scope(CcTest::isolate());
v8::Local<v8::Context> context = CcTest::NewContext({PRINT_EXTENSION_ID});
TEST_F(CompilerPrintTest, Print) {
v8::HandleScope scope(isolate());
const char* extension_names[1] = {
WithPrintExtensionMixin::kPrintExtensionName};
v8::ExtensionConfiguration config(1, extension_names);
v8::Local<v8::Context> context = v8::Context::New(isolate(), &config);
v8::Context::Scope context_scope(context);
const char* source = "for (n = 0; n < 100; ++n) print(n, 1, 2);";
Handle<JSFunction> fun = Compile(source);
if (fun.is_null()) return;
auto isolate = CcTest::i_isolate();
Handle<JSObject> global(isolate->context().global_object(), isolate);
Execution::CallScript(isolate, fun, global,
isolate->factory()->empty_fixed_array())
Handle<JSObject> global(i_isolate()->context().global_object(), i_isolate());
Execution::CallScript(i_isolate(), fun, global,
i_isolate()->factory()->empty_fixed_array())
.Check();
}
// The following test method stems from my coding efforts today. It
// tests all the functionality I have added to the compiler today
TEST(Stuff) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
TEST_F(CompilerTest, Stuff) {
v8::HandleScope scope(isolate());
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
"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());
auto isolate = CcTest::i_isolate();
Handle<JSObject> global(isolate->context().global_object(), isolate);
Execution::CallScript(isolate, fun, global,
isolate->factory()->empty_fixed_array())
EXPECT_TRUE(!fun.is_null());
Handle<JSObject> global(i_isolate()->context().global_object(), i_isolate());
Execution::CallScript(i_isolate(), fun, global,
i_isolate()->factory()->empty_fixed_array())
.Check();
CHECK_EQ(511.0, GetGlobalProperty("r")->Number());
EXPECT_EQ(511.0, GetGlobalProperty("r")->Number());
}
TEST(UncaughtThrow) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
TEST_F(CompilerTest, UncaughtThrow) {
v8::HandleScope scope(isolate());
const char* source = "throw 42;";
Handle<JSFunction> fun = Compile(source);
CHECK(!fun.is_null());
EXPECT_TRUE(!fun.is_null());
Isolate* isolate = fun->GetIsolate();
Handle<JSObject> global(isolate->context().global_object(), isolate);
CHECK(Execution::CallScript(isolate, fun, global,
isolate->factory()->empty_fixed_array())
.is_null());
CHECK_EQ(42.0, isolate->pending_exception().Number());
EXPECT_TRUE(Execution::CallScript(isolate, fun, global,
isolate->factory()->empty_fixed_array())
.is_null());
EXPECT_EQ(42.0, isolate->pending_exception().Number());
}
using CompilerC2JSFramesTest = WithPrintExtensionMixin<v8::TestWithIsolate>;
// Tests calling a builtin function from C/C++ code, and the builtin function
// performs GC. It creates a stack frame looks like following:
......@@ -241,17 +209,19 @@ TEST(UncaughtThrow) {
// | JS-to-C |
// | JS |
// | C-to-JS |
TEST(C2JSFrames) {
TEST_F(CompilerC2JSFramesTest, C2JSFrames) {
FLAG_expose_gc = true;
v8::HandleScope scope(CcTest::isolate());
v8::Local<v8::Context> context =
CcTest::NewContext({PRINT_EXTENSION_ID, GC_EXTENSION_ID});
v8::HandleScope scope(isolate());
const char* extension_names[2] = {
"v8/gc", WithPrintExtensionMixin::kPrintExtensionName};
v8::ExtensionConfiguration config(2, extension_names);
v8::Local<v8::Context> context = v8::Context::New(isolate(), &config);
v8::Context::Scope context_scope(context);
const char* source = "function foo(a) { gc(), print(a); }";
Handle<JSFunction> fun0 = Compile(source);
CHECK(!fun0.is_null());
EXPECT_TRUE(!fun0.is_null());
Isolate* isolate = fun0->GetIsolate();
// Run the generated code to populate the global object with 'foo'.
......@@ -263,39 +233,31 @@ TEST(C2JSFrames) {
Handle<Object> fun1 =
JSReceiver::GetProperty(isolate, isolate->global_object(), "foo")
.ToHandleChecked();
CHECK(fun1->IsJSFunction());
EXPECT_TRUE(fun1->IsJSFunction());
Handle<Object> argv[] = {
isolate->factory()->InternalizeString(base::StaticCharVector("hello"))};
Execution::Call(isolate,
Handle<JSFunction>::cast(fun1),
global,
arraysize(argv),
argv).Check();
Execution::Call(isolate, Handle<JSFunction>::cast(fun1), global,
arraysize(argv), argv)
.Check();
}
// Regression 236. Calling InitLineEnds on a Script with undefined
// source resulted in crash.
TEST(Regression236) {
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Factory* factory = isolate->factory();
v8::HandleScope scope(CcTest::isolate());
TEST_F(CompilerTest, Regression236) {
Factory* factory = i_isolate()->factory();
v8::HandleScope scope(isolate());
Handle<Script> script = factory->NewScript(factory->empty_string());
script->set_source(ReadOnlyRoots(CcTest::heap()).undefined_value());
CHECK_EQ(-1, Script::GetLineNumber(script, 0));
CHECK_EQ(-1, Script::GetLineNumber(script, 100));
CHECK_EQ(-1, Script::GetLineNumber(script, -1));
script->set_source(ReadOnlyRoots(i_isolate()->heap()).undefined_value());
EXPECT_EQ(-1, Script::GetLineNumber(script, 0));
EXPECT_EQ(-1, Script::GetLineNumber(script, 100));
EXPECT_EQ(-1, Script::GetLineNumber(script, -1));
}
TEST(GetScriptLineNumber) {
LocalContext context;
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(isolate);
v8::ScriptOrigin origin = v8::ScriptOrigin(isolate, v8_str("test"));
TEST_F(CompilerTest, GetScriptLineNumber) {
v8::HandleScope scope(isolate());
v8::ScriptOrigin origin = v8::ScriptOrigin(isolate(), NewString("test"));
const char function_f[] = "function f() {}";
const int max_rows = 1000;
const int buffer_size = max_rows + sizeof(function_f);
......@@ -304,113 +266,110 @@ TEST(GetScriptLineNumber) {
buffer[buffer_size - 1] = '\0';
for (int i = 0; i < max_rows; ++i) {
if (i > 0)
buffer[i - 1] = '\n';
if (i > 0) buffer[i - 1] = '\n';
MemCopy(&buffer[i], function_f, sizeof(function_f) - 1);
v8::Local<v8::String> script_body = v8_str(buffer.begin());
v8::Script::Compile(context.local(), script_body, &origin)
v8::Local<v8::String> script_body = NewString(buffer.begin());
v8::Script::Compile(context(), script_body, &origin)
.ToLocalChecked()
->Run(context.local())
->Run(context())
.ToLocalChecked();
v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
context->Global()->Get(context.local(), v8_str("f")).ToLocalChecked());
CHECK_EQ(i, f->GetScriptLineNumber());
context()->Global()->Get(context(), NewString("f")).ToLocalChecked());
EXPECT_EQ(i, f->GetScriptLineNumber());
}
}
TEST(FeedbackVectorPreservedAcrossRecompiles) {
TEST_F(CompilerTest, FeedbackVectorPreservedAcrossRecompiles) {
if (i::FLAG_always_opt || !i::FLAG_opt) return;
i::FLAG_allow_natives_syntax = true;
CcTest::InitializeVM();
if (!CcTest::i_isolate()->use_optimizer()) return;
v8::HandleScope scope(CcTest::isolate());
v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
if (!i_isolate()->use_optimizer()) return;
v8::HandleScope scope(isolate());
// Make sure function f has a call that uses a type feedback slot.
CompileRun(
RunJS(
"function fun() {};"
"fun1 = fun;"
"%PrepareFunctionForOptimization(f);"
"function f(a) { a(); } f(fun1);");
Handle<JSFunction> f = Handle<JSFunction>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
CcTest::global()->Get(context, v8_str("f")).ToLocalChecked())));
Handle<JSFunction> f = Handle<JSFunction>::cast(v8::Utils::OpenHandle(
*v8::Local<v8::Function>::Cast(context()
->Global()
->Get(context(), NewString("f"))
.ToLocalChecked())));
// Verify that we gathered feedback.
Handle<FeedbackVector> feedback_vector(f->feedback_vector(), f->GetIsolate());
CHECK(!feedback_vector->is_empty());
EXPECT_TRUE(!feedback_vector->is_empty());
FeedbackSlot slot_for_a(0);
MaybeObject object = feedback_vector->Get(slot_for_a);
{
HeapObject heap_object;
CHECK(object->GetHeapObjectIfWeak(&heap_object));
CHECK(heap_object.IsJSFunction());
EXPECT_TRUE(object->GetHeapObjectIfWeak(&heap_object));
EXPECT_TRUE(heap_object.IsJSFunction());
}
CompileRun("%OptimizeFunctionOnNextCall(f); f(fun1);");
RunJS("%OptimizeFunctionOnNextCall(f); f(fun1);");
// Verify that the feedback is still "gathered" despite a recompilation
// of the full code.
CHECK(f->HasAttachedOptimizedCode());
EXPECT_TRUE(f->HasAttachedOptimizedCode());
object = f->feedback_vector().Get(slot_for_a);
{
HeapObject heap_object;
CHECK(object->GetHeapObjectIfWeak(&heap_object));
CHECK(heap_object.IsJSFunction());
EXPECT_TRUE(object->GetHeapObjectIfWeak(&heap_object));
EXPECT_TRUE(heap_object.IsJSFunction());
}
}
TEST(FeedbackVectorUnaffectedByScopeChanges) {
TEST_F(CompilerTest, FeedbackVectorUnaffectedByScopeChanges) {
if (i::FLAG_always_opt || !i::FLAG_lazy || i::FLAG_lite_mode) {
return;
}
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
CompileRun("function builder() {"
" call_target = function() { return 3; };"
" return (function() {"
" eval('');"
" return function() {"
" 'use strict';"
" call_target();"
" }"
" })();"
"}"
"morphing_call = builder();");
v8::HandleScope scope(isolate());
RunJS(
"function builder() {"
" call_target = function() { return 3; };"
" return (function() {"
" eval('');"
" return function() {"
" 'use strict';"
" call_target();"
" }"
" })();"
"}"
"morphing_call = builder();");
Handle<JSFunction> f = Handle<JSFunction>::cast(v8::Utils::OpenHandle(
*v8::Local<v8::Function>::Cast(CcTest::global()
->Get(context, v8_str("morphing_call"))
.ToLocalChecked())));
Handle<JSFunction> f = Handle<JSFunction>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
context()
->Global()
->Get(context(), NewString("morphing_call"))
.ToLocalChecked())));
// If we are compiling lazily then it should not be compiled, and so no
// feedback vector allocated yet.
CHECK(!f->shared().is_compiled());
EXPECT_TRUE(!f->shared().is_compiled());
CompileRun("morphing_call();");
RunJS("morphing_call();");
// Now a feedback vector / closure feedback cell array is allocated.
CHECK(f->shared().is_compiled());
CHECK(f->has_feedback_vector() || f->has_closure_feedback_cell_array());
EXPECT_TRUE(f->shared().is_compiled());
EXPECT_TRUE(f->has_feedback_vector() || f->has_closure_feedback_cell_array());
}
// Test that optimized code for different closures is actually shared.
TEST(OptimizedCodeSharing1) {
TEST_F(CompilerTest, OptimizedCodeSharing1) {
FLAG_stress_compaction = false;
FLAG_allow_natives_syntax = true;
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
v8::HandleScope scope(isolate());
for (int i = 0; i < 3; i++) {
LocalContext env;
env->Global()
->Set(env.local(), v8_str("x"), v8::Integer::New(CcTest::isolate(), i))
context()
->Global()
->Set(context(), NewString("x"), v8::Integer::New(isolate(), i))
.FromJust();
CompileRun(
RunJS(
"function MakeClosure() {"
" return function() { return x; };"
"}"
......@@ -425,64 +384,62 @@ TEST(OptimizedCodeSharing1) {
"var closure2 = MakeClosure(); closure2();");
Handle<JSFunction> fun1 = Handle<JSFunction>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
env->Global()
->Get(env.local(), v8_str("closure1"))
context()
->Global()
->Get(context(), NewString("closure1"))
.ToLocalChecked())));
Handle<JSFunction> fun2 = Handle<JSFunction>::cast(
v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
env->Global()
->Get(env.local(), v8_str("closure2"))
context()
->Global()
->Get(context(), NewString("closure2"))
.ToLocalChecked())));
CHECK(fun1->HasAttachedOptimizedCode() ||
!CcTest::i_isolate()->use_optimizer());
CHECK(fun2->HasAttachedOptimizedCode() ||
!CcTest::i_isolate()->use_optimizer());
CHECK_EQ(fun1->code(), fun2->code());
EXPECT_TRUE(fun1->HasAttachedOptimizedCode() ||
!i_isolate()->use_optimizer());
EXPECT_TRUE(fun2->HasAttachedOptimizedCode() ||
!i_isolate()->use_optimizer());
EXPECT_EQ(fun1->code(), fun2->code());
}
}
TEST(CompileFunction) {
TEST_F(CompilerTest, CompileFunction) {
if (i::FLAG_always_opt) return;
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
LocalContext env;
CompileRun("var r = 10;");
v8::HandleScope scope(isolate());
RunJS("var r = 10;");
v8::Local<v8::Object> math = v8::Local<v8::Object>::Cast(
env->Global()->Get(env.local(), v8_str("Math")).ToLocalChecked());
v8::ScriptCompiler::Source script_source(v8_str(
"a = PI * r * r;"
"x = r * cos(PI);"
"y = r * sin(PI / 2);"));
context()->Global()->Get(context(), NewString("Math")).ToLocalChecked());
v8::ScriptCompiler::Source script_source(
NewString("a = PI * r * r;"
"x = r * cos(PI);"
"y = r * sin(PI / 2);"));
v8::Local<v8::Function> fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source, 0,
nullptr, 1, &math)
v8::ScriptCompiler::CompileFunction(context(), &script_source, 0, nullptr,
1, &math)
.ToLocalChecked();
CHECK(!fun.IsEmpty());
EXPECT_TRUE(!fun.IsEmpty());
i::DisallowCompilation no_compile(CcTest::i_isolate());
fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
CHECK(env->Global()->Has(env.local(), v8_str("a")).FromJust());
i::DisallowCompilation no_compile(i_isolate());
fun->Call(context(), context()->Global(), 0, nullptr).ToLocalChecked();
EXPECT_TRUE(context()->Global()->Has(context(), NewString("a")).FromJust());
v8::Local<v8::Value> a =
env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked();
CHECK(a->IsNumber());
CHECK(env->Global()->Has(env.local(), v8_str("x")).FromJust());
context()->Global()->Get(context(), NewString("a")).ToLocalChecked();
EXPECT_TRUE(a->IsNumber());
EXPECT_TRUE(context()->Global()->Has(context(), NewString("x")).FromJust());
v8::Local<v8::Value> x =
env->Global()->Get(env.local(), v8_str("x")).ToLocalChecked();
CHECK(x->IsNumber());
CHECK(env->Global()->Has(env.local(), v8_str("y")).FromJust());
context()->Global()->Get(context(), NewString("x")).ToLocalChecked();
EXPECT_TRUE(x->IsNumber());
EXPECT_TRUE(context()->Global()->Has(context(), NewString("y")).FromJust());
v8::Local<v8::Value> y =
env->Global()->Get(env.local(), v8_str("y")).ToLocalChecked();
CHECK(y->IsNumber());
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());
}
TEST(CompileFunctionComplex) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
LocalContext env;
CompileRun(
context()->Global()->Get(context(), NewString("y")).ToLocalChecked();
EXPECT_TRUE(y->IsNumber());
EXPECT_EQ(314.1592653589793, a->NumberValue(context()).FromJust());
EXPECT_EQ(-10.0, x->NumberValue(context()).FromJust());
EXPECT_EQ(10.0, y->NumberValue(context()).FromJust());
}
TEST_F(CompilerTest, CompileFunctionComplex) {
v8::HandleScope scope(isolate());
RunJS(
"var x = 1;"
"var y = 2;"
"var z = 4;"
......@@ -490,92 +447,85 @@ TEST(CompileFunctionComplex) {
"var b = {x: 32};");
v8::Local<v8::Object> ext[2];
ext[0] = v8::Local<v8::Object>::Cast(
env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
context()->Global()->Get(context(), NewString("a")).ToLocalChecked());
ext[1] = v8::Local<v8::Object>::Cast(
env->Global()->Get(env.local(), v8_str("b")).ToLocalChecked());
v8::ScriptCompiler::Source script_source(v8_str("result = x + y + z"));
context()->Global()->Get(context(), NewString("b")).ToLocalChecked());
v8::ScriptCompiler::Source script_source(NewString("result = x + y + z"));
v8::Local<v8::Function> fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source, 0,
nullptr, 2, ext)
v8::ScriptCompiler::CompileFunction(context(), &script_source, 0, nullptr,
2, ext)
.ToLocalChecked();
CHECK(!fun.IsEmpty());
fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
EXPECT_TRUE(!fun.IsEmpty());
fun->Call(context(), context()->Global(), 0, nullptr).ToLocalChecked();
EXPECT_TRUE(
context()->Global()->Has(context(), NewString("result")).FromJust());
v8::Local<v8::Value> result =
env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
CHECK(result->IsNumber());
CHECK_EQ(52.0, result->NumberValue(env.local()).FromJust());
context()->Global()->Get(context(), NewString("result")).ToLocalChecked();
EXPECT_TRUE(result->IsNumber());
EXPECT_EQ(52.0, result->NumberValue(context()).FromJust());
}
TEST(CompileFunctionArgs) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
LocalContext env;
CompileRun("var a = {x: 23};");
TEST_F(CompilerTest, CompileFunctionArgs) {
v8::HandleScope scope(isolate());
RunJS("var a = {x: 23};");
v8::Local<v8::Object> ext[1];
ext[0] = v8::Local<v8::Object>::Cast(
env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
v8::ScriptCompiler::Source script_source(v8_str("result = x + abc"));
v8::Local<v8::String> arg = v8_str("abc");
v8::Local<v8::Function> fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source, 1, &arg,
1, ext)
.ToLocalChecked();
CHECK_EQ(1, fun->Get(env.local(), v8_str("length"))
.ToLocalChecked()
->ToInt32(env.local())
.ToLocalChecked()
->Value());
v8::Local<v8::Value> arg_value = v8::Number::New(CcTest::isolate(), 42.0);
fun->Call(env.local(), env->Global(), 1, &arg_value).ToLocalChecked();
CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
context()->Global()->Get(context(), NewString("a")).ToLocalChecked());
v8::ScriptCompiler::Source script_source(NewString("result = x + abc"));
v8::Local<v8::String> arg = NewString("abc");
v8::Local<v8::Function> fun = v8::ScriptCompiler::CompileFunction(
context(), &script_source, 1, &arg, 1, ext)
.ToLocalChecked();
EXPECT_EQ(1, fun->Get(context(), NewString("length"))
.ToLocalChecked()
->ToInt32(context())
.ToLocalChecked()
->Value());
v8::Local<v8::Value> arg_value = v8::Number::New(isolate(), 42.0);
fun->Call(context(), context()->Global(), 1, &arg_value).ToLocalChecked();
EXPECT_TRUE(
context()->Global()->Has(context(), NewString("result")).FromJust());
v8::Local<v8::Value> result =
env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
CHECK(result->IsNumber());
CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
context()->Global()->Get(context(), NewString("result")).ToLocalChecked();
EXPECT_TRUE(result->IsNumber());
EXPECT_EQ(65.0, result->NumberValue(context()).FromJust());
}
TEST(CompileFunctionComments) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
LocalContext env;
CompileRun("var a = {x: 23, y: 1, z: 2};");
TEST_F(CompilerTest, CompileFunctionComments) {
v8::HandleScope scope(isolate());
RunJS("var a = {x: 23, y: 1, z: 2};");
v8::Local<v8::Object> ext[1];
ext[0] = v8::Local<v8::Object>::Cast(
env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
context()->Global()->Get(context(), NewString("a")).ToLocalChecked());
v8::Local<v8::String> source =
CompileRun("'result = /* y + */ x + a\\u4e00 // + z'").As<v8::String>();
RunJS("'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>();
v8::Local<v8::Function> fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source, 1, &arg,
1, ext)
.ToLocalChecked();
CHECK(!fun.IsEmpty());
v8::Local<v8::Value> arg_value = v8::Number::New(CcTest::isolate(), 42.0);
fun->Call(env.local(), env->Global(), 1, &arg_value).ToLocalChecked();
CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
v8::Local<v8::String> arg = RunJS("'a\\u4e00'").As<v8::String>();
v8::Local<v8::Function> fun = v8::ScriptCompiler::CompileFunction(
context(), &script_source, 1, &arg, 1, ext)
.ToLocalChecked();
EXPECT_TRUE(!fun.IsEmpty());
v8::Local<v8::Value> arg_value = v8::Number::New(isolate(), 42.0);
fun->Call(context(), context()->Global(), 1, &arg_value).ToLocalChecked();
EXPECT_TRUE(
context()->Global()->Has(context(), NewString("result")).FromJust());
v8::Local<v8::Value> result =
env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
CHECK(result->IsNumber());
CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
}
TEST(CompileFunctionNonIdentifierArgs) {
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 }");
CHECK(
v8::ScriptCompiler::CompileFunction(env.local(), &script_source, 1, &arg)
context()->Global()->Get(context(), NewString("result")).ToLocalChecked();
EXPECT_TRUE(result->IsNumber());
EXPECT_EQ(65.0, result->NumberValue(context()).FromJust());
}
TEST_F(CompilerTest, CompileFunctionNonIdentifierArgs) {
v8::HandleScope scope(isolate());
v8::ScriptCompiler::Source script_source(NewString("result = 1"));
v8::Local<v8::String> arg = NewString("b }");
EXPECT_TRUE(
v8::ScriptCompiler::CompileFunction(context(), &script_source, 1, &arg)
.IsEmpty());
}
TEST(CompileFunctionRenderCallSite) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
LocalContext env;
TEST_F(CompilerTest, CompileFunctionRenderCallSite) {
v8::HandleScope scope(isolate());
static const char* source1 =
"try {"
" var a = [];"
......@@ -595,253 +545,234 @@ TEST(CompileFunctionRenderCallSite) {
"}";
static const char* expect2 = "TypeError: a[0] is not a function";
{
v8::ScriptCompiler::Source script_source(v8_str(source1));
v8::ScriptCompiler::Source script_source(NewString(source1));
v8::Local<v8::Function> fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source)
v8::ScriptCompiler::CompileFunction(context(), &script_source)
.ToLocalChecked();
CHECK(!fun.IsEmpty());
EXPECT_TRUE(!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());
fun->Call(context(), context()->Global(), 0, nullptr).ToLocalChecked();
EXPECT_TRUE(result->IsString());
EXPECT_TRUE(v8::Local<v8::String>::Cast(result)
->Equals(context(), NewString(expect1))
.FromJust());
}
{
v8::ScriptCompiler::Source script_source(v8_str(source2));
v8::ScriptCompiler::Source script_source(NewString(source2));
v8::Local<v8::Function> fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source)
v8::ScriptCompiler::CompileFunction(context(), &script_source)
.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());
fun->Call(context(), context()->Global(), 0, nullptr).ToLocalChecked();
EXPECT_TRUE(result->IsString());
EXPECT_TRUE(v8::Local<v8::String>::Cast(result)
->Equals(context(), NewString(expect2))
.FromJust());
}
}
TEST(CompileFunctionQuirks) {
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
LocalContext env;
TEST_F(CompilerTest, CompileFunctionQuirks) {
v8::HandleScope scope(isolate());
{
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::ScriptCompiler::Source script_source(NewString(source));
v8::Local<v8::Function> fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source)
v8::ScriptCompiler::CompileFunction(context(), &script_source)
.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());
fun->Call(context(), context()->Global(), 0, nullptr).ToLocalChecked();
EXPECT_TRUE(result->IsString());
EXPECT_TRUE(v8::Local<v8::String>::Cast(result)
->Equals(context(), NewString(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::CompileFunction(env.local(), &script_source)
.IsEmpty());
CHECK(try_catch.HasCaught());
v8::ScriptCompiler::Source script_source(NewString(source));
v8::TryCatch try_catch(isolate());
EXPECT_TRUE(v8::ScriptCompiler::CompileFunction(context(), &script_source)
.IsEmpty());
EXPECT_TRUE(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::CompileFunction(env.local(), &script_source)
.IsEmpty());
CHECK(try_catch.HasCaught());
v8::ScriptCompiler::Source script_source(NewString(source));
v8::TryCatch try_catch(isolate());
EXPECT_TRUE(v8::ScriptCompiler::CompileFunction(context(), &script_source)
.IsEmpty());
EXPECT_TRUE(try_catch.HasCaught());
}
}
TEST(CompileFunctionScriptOrigin) {
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(isolate);
LocalContext env;
v8::ScriptOrigin origin(isolate, v8_str("test"), 22, 41);
v8::ScriptCompiler::Source script_source(v8_str("throw new Error()"), origin);
TEST_F(CompilerTest, CompileFunctionScriptOrigin) {
v8::HandleScope scope(isolate());
v8::ScriptOrigin origin(isolate(), NewString("test"), 22, 41);
v8::ScriptCompiler::Source script_source(NewString("throw new Error()"),
origin);
v8::Local<v8::Function> fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source)
v8::ScriptCompiler::CompileFunction(context(), &script_source)
.ToLocalChecked();
CHECK(!fun.IsEmpty());
EXPECT_TRUE(!fun.IsEmpty());
v8::Local<v8::UnboundScript> script =
fun->GetUnboundScript().ToLocalChecked();
CHECK(!script.IsEmpty());
CHECK(script->GetScriptName()->StrictEquals(v8_str("test")));
v8::TryCatch try_catch(CcTest::isolate());
CcTest::isolate()->SetCaptureStackTraceForUncaughtExceptions(true);
CHECK(fun->Call(env.local(), env->Global(), 0, nullptr).IsEmpty());
CHECK(try_catch.HasCaught());
CHECK(!try_catch.Exception().IsEmpty());
EXPECT_TRUE(!script.IsEmpty());
EXPECT_TRUE(script->GetScriptName()->StrictEquals(NewString("test")));
v8::TryCatch try_catch(isolate());
isolate()->SetCaptureStackTraceForUncaughtExceptions(true);
EXPECT_TRUE(fun->Call(context(), context()->Global(), 0, nullptr).IsEmpty());
EXPECT_TRUE(try_catch.HasCaught());
EXPECT_TRUE(!try_catch.Exception().IsEmpty());
v8::Local<v8::StackTrace> stack =
v8::Exception::GetStackTrace(try_catch.Exception());
CHECK(!stack.IsEmpty());
CHECK_GT(stack->GetFrameCount(), 0);
v8::Local<v8::StackFrame> frame = stack->GetFrame(CcTest::isolate(), 0);
CHECK_EQ(23, frame->GetLineNumber());
CHECK_EQ(42 + strlen("throw "), static_cast<unsigned>(frame->GetColumn()));
}
void TestCompileFunctionToStringImpl() {
#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); \
} \
EXPECT_TRUE(!stack.IsEmpty());
EXPECT_GT(stack->GetFrameCount(), 0);
v8::Local<v8::StackFrame> frame = stack->GetFrame(isolate(), 0);
EXPECT_EQ(23, frame->GetLineNumber());
EXPECT_EQ(42 + strlen("throw "), static_cast<unsigned>(frame->GetColumn()));
}
TEST_F(CompilerTest, CompileFunctionFunctionToString) {
#define CHECK_NOT_CAUGHT(__local_context__, try_catch, __op__) \
do { \
const char* op = (__op__); \
if (try_catch.HasCaught()) { \
v8::String::Utf8Value error(isolate(), try_catch.Exception() \
->ToString(__local_context__) \
.ToLocalChecked()); \
FATAL("Unexpected exception thrown during %s:\n\t%s\n", op, *error); \
} \
} while (false)
{
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(isolate);
LocalContext env;
v8::HandleScope scope(isolate());
// Regression test for v8:6190
{
v8::ScriptOrigin origin(isolate, v8_str("test"), 22, 41);
v8::ScriptCompiler::Source script_source(v8_str("return event"), origin);
v8::ScriptOrigin origin(isolate(), NewString("test"), 22, 41);
v8::ScriptCompiler::Source script_source(NewString("return event"),
origin);
v8::Local<v8::String> params[] = {v8_str("event")};
v8::TryCatch try_catch(CcTest::isolate());
v8::Local<v8::String> params[] = {NewString("event")};
v8::TryCatch try_catch(isolate());
v8::MaybeLocal<v8::Function> maybe_fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source,
v8::ScriptCompiler::CompileFunction(context(), &script_source,
arraysize(params), params);
CHECK_NOT_CAUGHT(env.local(), try_catch,
CHECK_NOT_CAUGHT(context(), try_catch,
"v8::ScriptCompiler::CompileFunction");
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(
EXPECT_TRUE(!fun.IsEmpty());
EXPECT_TRUE(!try_catch.HasCaught());
v8::Local<v8::String> result = fun->ToString(context()).ToLocalChecked();
v8::Local<v8::String> expected = NewString(
"function (event) {\n"
"return event\n"
"}");
CHECK(expected->Equals(env.local(), result).FromJust());
EXPECT_TRUE(expected->Equals(context(), result).FromJust());
}
// With no parameters:
{
v8::ScriptOrigin origin(isolate, v8_str("test"), 17, 31);
v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);
v8::ScriptOrigin origin(isolate(), NewString("test"), 17, 31);
v8::ScriptCompiler::Source script_source(NewString("return 0"), origin);
v8::TryCatch try_catch(CcTest::isolate());
v8::TryCatch try_catch(isolate());
v8::MaybeLocal<v8::Function> maybe_fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source);
v8::ScriptCompiler::CompileFunction(context(), &script_source);
CHECK_NOT_CAUGHT(env.local(), try_catch,
CHECK_NOT_CAUGHT(context(), try_catch,
"v8::ScriptCompiler::CompileFunction");
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(
EXPECT_TRUE(!fun.IsEmpty());
EXPECT_TRUE(!try_catch.HasCaught());
v8::Local<v8::String> result = fun->ToString(context()).ToLocalChecked();
v8::Local<v8::String> expected = NewString(
"function () {\n"
"return 0\n"
"}");
CHECK(expected->Equals(env.local(), result).FromJust());
EXPECT_TRUE(expected->Equals(context(), result).FromJust());
}
// With a name:
{
v8::ScriptOrigin origin(isolate, v8_str("test"), 17, 31);
v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);
v8::ScriptOrigin origin(isolate(), NewString("test"), 17, 31);
v8::ScriptCompiler::Source script_source(NewString("return 0"), origin);
v8::TryCatch try_catch(CcTest::isolate());
v8::TryCatch try_catch(isolate());
v8::MaybeLocal<v8::Function> maybe_fun =
v8::ScriptCompiler::CompileFunction(env.local(), &script_source);
v8::ScriptCompiler::CompileFunction(context(), &script_source);
CHECK_NOT_CAUGHT(env.local(), try_catch,
CHECK_NOT_CAUGHT(context(), try_catch,
"v8::ScriptCompiler::CompileFunction");
v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
CHECK(!fun.IsEmpty());
CHECK(!try_catch.HasCaught());
EXPECT_TRUE(!fun.IsEmpty());
EXPECT_TRUE(!try_catch.HasCaught());
fun->SetName(v8_str("onclick"));
fun->SetName(NewString("onclick"));
v8::Local<v8::String> result =
fun->ToString(env.local()).ToLocalChecked();
v8::Local<v8::String> expected = v8_str(
v8::Local<v8::String> result = fun->ToString(context()).ToLocalChecked();
v8::Local<v8::String> expected = NewString(
"function onclick() {\n"
"return 0\n"
"}");
CHECK(expected->Equals(env.local(), result).FromJust());
EXPECT_TRUE(expected->Equals(context(), result).FromJust());
}
}
#undef CHECK_NOT_CAUGHT
}
TEST(CompileFunctionFunctionToString) { TestCompileFunctionToStringImpl(); }
TEST(InvocationCount) {
TEST_F(CompilerTest, InvocationCount) {
if (FLAG_lite_mode) return;
FLAG_allow_natives_syntax = true;
FLAG_always_opt = false;
CcTest::InitializeVM();
v8::HandleScope scope(CcTest::isolate());
v8::HandleScope scope(isolate());
CompileRun(
RunJS(
"function bar() {};"
"%EnsureFeedbackVectorForFunction(bar);"
"function foo() { return bar(); };"
"%EnsureFeedbackVectorForFunction(foo);"
"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());
EXPECT_EQ(1, foo->feedback_vector().invocation_count());
RunJS("foo()");
EXPECT_EQ(2, foo->feedback_vector().invocation_count());
RunJS("bar()");
EXPECT_EQ(2, foo->feedback_vector().invocation_count());
RunJS("foo(); foo()");
EXPECT_EQ(4, foo->feedback_vector().invocation_count());
}
TEST(ShallowEagerCompilation) {
TEST_F(CompilerTest, 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(
v8::HandleScope scope(isolate());
v8::Local<v8::String> source = NewString(
"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::Compile(context(), &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());
v8::internal::DisallowCompilation no_compile_expected(i_isolate());
v8::Local<v8::Value> result = script->Run(context()).ToLocalChecked();
EXPECT_EQ(4, result->Int32Value(context()).FromJust());
}
}
TEST(DeepEagerCompilation) {
TEST_F(CompilerTest, 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(
v8::HandleScope scope(isolate());
v8::Local<v8::String> source = NewString(
"function f(x) {"
" function g(x) {"
" function h(x) {"
......@@ -854,22 +785,20 @@ TEST(DeepEagerCompilation) {
"f(2)");
v8::ScriptCompiler::Source script_source(source);
v8::Local<v8::Script> script =
v8::ScriptCompiler::Compile(env.local(), &script_source,
v8::ScriptCompiler::Compile(context(), &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());
v8::internal::DisallowCompilation no_compile_expected(i_isolate());
v8::Local<v8::Value> result = script->Run(context()).ToLocalChecked();
EXPECT_EQ(32, result->Int32Value(context()).FromJust());
}
}
TEST(DeepEagerCompilationPeakMemory) {
TEST_F(CompilerTest, DeepEagerCompilationPeakMemory) {
i::FLAG_always_opt = false;
CcTest::InitializeVM();
LocalContext env;
v8::HandleScope scope(CcTest::isolate());
v8::Local<v8::String> source = v8_str(
v8::HandleScope scope(isolate());
v8::Local<v8::String> source = NewString(
"function f() {"
" function g1() {"
" function h1() {"
......@@ -893,43 +822,43 @@ TEST(DeepEagerCompilationPeakMemory) {
" }"
"}");
v8::ScriptCompiler::Source script_source(source);
CcTest::i_isolate()->compilation_cache()->DisableScriptAndEval();
i_isolate()->compilation_cache()->DisableScriptAndEval();
v8::HeapStatistics heap_statistics;
CcTest::isolate()->GetHeapStatistics(&heap_statistics);
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::Compile(context(), &script_source,
v8::ScriptCompiler::kNoCompileOptions)
.ToLocalChecked();
CcTest::isolate()->GetHeapStatistics(&heap_statistics);
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::Compile(context(), &script_source,
v8::ScriptCompiler::kNoCompileOptions)
.ToLocalChecked();
CcTest::isolate()->GetHeapStatistics(&heap_statistics);
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::Compile(context(), &script_source,
v8::ScriptCompiler::kEagerCompile)
.ToLocalChecked();
CcTest::isolate()->GetHeapStatistics(&heap_statistics);
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);
EXPECT_LE(peak_mem_1, peak_mem_2);
EXPECT_EQ(peak_mem_2, peak_mem_3);
EXPECT_LE(peak_mem_3, peak_mem_4);
// Check that eager compilation does not cause significantly higher (+100%)
// peak memory than lazy compilation.
CHECK_LE(peak_mem_4 - peak_mem_3, peak_mem_3);
EXPECT_LE(peak_mem_4 - peak_mem_3, peak_mem_3);
}
namespace {
......@@ -964,38 +893,36 @@ class DummySourceStream : public v8::ScriptCompiler::ExternalSourceStream {
// 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);
TEST_F(CompilerTest, ProfilerEnabledDuringBackgroundCompile) {
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(
v8::ScriptCompiler::StartStreaming(isolate, &streamed_source));
v8::ScriptCompiler::StartStreaming(isolate(), &streamed_source));
// Run the background compilation task. DummySourceStream::GetMoreData won't
// block, so it's OK to just join the background task.
StreamerThread::StartThreadForTaskAndJoin(task.get());
// Enable the CPU profiler.
auto* cpu_profiler = v8::CpuProfiler::New(isolate, v8::kStandardNaming);
v8::Local<v8::String> profile = v8_str("profile");
auto* cpu_profiler = v8::CpuProfiler::New(isolate(), v8::kStandardNaming);
v8::Local<v8::String> profile = NewString("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),
v8::ScriptOrigin(isolate, v8_str("foo")))
v8::ScriptCompiler::Compile(isolate()->GetCurrentContext(),
&streamed_source, NewString(source),
v8::ScriptOrigin(isolate(), NewString("foo")))
.ToLocalChecked();
i::Handle<i::Object> obj = Utils::OpenHandle(*script);
CHECK(i::JSFunction::cast(*obj).shared().AreSourcePositionsAvailable(
CcTest::i_isolate()));
EXPECT_TRUE(i::JSFunction::cast(*obj).shared().AreSourcePositionsAvailable(
i_isolate()));
cpu_profiler->StopProfiling(profile);
}
......
......@@ -11,8 +11,10 @@
#include "include/libplatform/libplatform.h"
#include "include/v8-array-buffer.h"
#include "include/v8-context.h"
#include "include/v8-extension.h"
#include "include/v8-local-handle.h"
#include "include/v8-primitive.h"
#include "include/v8-template.h"
#include "src/api/api-inl.h"
#include "src/base/macros.h"
#include "src/base/utils/random-number-generator.h"
......@@ -205,6 +207,62 @@ using TestWithContext = //
WithDefaultPlatformMixin< //
::testing::Test>>>>;
class PrintExtension : public v8::Extension {
public:
PrintExtension() : v8::Extension("v8/print", "native function print();") {}
v8::Local<v8::FunctionTemplate> GetNativeFunctionTemplate(
v8::Isolate* isolate, v8::Local<v8::String> name) override {
return v8::FunctionTemplate::New(isolate, PrintExtension::Print);
}
static void Print(const v8::FunctionCallbackInfo<v8::Value>& args) {
for (int i = 0; i < args.Length(); i++) {
if (i != 0) printf(" ");
v8::HandleScope scope(args.GetIsolate());
v8::String::Utf8Value str(args.GetIsolate(), args[i]);
if (*str == nullptr) return;
printf("%s", *str);
}
printf("\n");
}
};
template <typename TMixin>
class WithPrintExtensionMixin : public TMixin {
public:
WithPrintExtensionMixin() = default;
~WithPrintExtensionMixin() override = default;
WithPrintExtensionMixin(const WithPrintExtensionMixin&) = delete;
WithPrintExtensionMixin& operator=(const WithPrintExtensionMixin&) = delete;
static void SetUpTestSuite() {
v8::RegisterExtension(std::make_unique<PrintExtension>());
TMixin::SetUpTestSuite();
}
static void TearDownTestSuite() { TMixin::TearDownTestSuite(); }
static constexpr const char* kPrintExtensionName = "v8/print";
};
// Run a ScriptStreamingTask in a separate thread.
class StreamerThread : public v8::base::Thread {
public:
static void StartThreadForTaskAndJoin(
v8::ScriptCompiler::ScriptStreamingTask* task) {
StreamerThread thread(task);
CHECK(thread.Start());
thread.Join();
}
explicit StreamerThread(v8::ScriptCompiler::ScriptStreamingTask* task)
: Thread(Thread::Options()), task_(task) {}
void Run() override { task_->Run(); }
private:
v8::ScriptCompiler::ScriptStreamingTask* task_;
};
namespace internal {
// Forward declarations.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment