LCOV - code coverage report
Current view: top level - test/cctest - test-compiler.cc (source / functions) Hit Total Coverage
Test: app.info Lines: 439 439 100.0 %
Date: 2019-04-17 Functions: 39 39 100.0 %

          Line data    Source code
       1             : // Copyright 2012 the V8 project authors. All rights reserved.
       2             : // Redistribution and use in source and binary forms, with or without
       3             : // modification, are permitted provided that the following conditions are
       4             : // met:
       5             : //
       6             : //     * Redistributions of source code must retain the above copyright
       7             : //       notice, this list of conditions and the following disclaimer.
       8             : //     * Redistributions in binary form must reproduce the above
       9             : //       copyright notice, this list of conditions and the following
      10             : //       disclaimer in the documentation and/or other materials provided
      11             : //       with the distribution.
      12             : //     * Neither the name of Google Inc. nor the names of its
      13             : //       contributors may be used to endorse or promote products derived
      14             : //       from this software without specific prior written permission.
      15             : //
      16             : // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
      17             : // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
      18             : // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      19             : // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
      20             : // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
      21             : // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
      22             : // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
      23             : // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
      24             : // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      25             : // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
      26             : // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      27             : 
      28             : #include <stdlib.h>
      29             : #include <wchar.h>
      30             : 
      31             : #include "src/v8.h"
      32             : 
      33             : #include "src/api-inl.h"
      34             : #include "src/compilation-cache.h"
      35             : #include "src/compiler.h"
      36             : #include "src/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             : namespace v8 {
      45             : namespace internal {
      46             : 
      47          60 : static Handle<Object> GetGlobalProperty(const char* name) {
      48             :   Isolate* isolate = CcTest::i_isolate();
      49         180 :   return JSReceiver::GetProperty(isolate, isolate->global_object(), name)
      50          60 :       .ToHandleChecked();
      51             : }
      52             : 
      53          20 : static void SetGlobalProperty(const char* name, Object value) {
      54             :   Isolate* isolate = CcTest::i_isolate();
      55             :   Handle<Object> object(value, isolate);
      56             :   Handle<String> internalized_name =
      57          20 :       isolate->factory()->InternalizeUtf8String(name);
      58          40 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
      59          40 :   Runtime::SetObjectProperty(isolate, global, internalized_name, object,
      60          20 :                              StoreOrigin::kMaybeKeyed, Just(kDontThrow))
      61             :       .Check();
      62          20 : }
      63             : 
      64          40 : static Handle<JSFunction> Compile(const char* source) {
      65             :   Isolate* isolate = CcTest::i_isolate();
      66          80 :   Handle<String> source_code = isolate->factory()->NewStringFromUtf8(
      67          40 :       CStrVector(source)).ToHandleChecked();
      68             :   Handle<SharedFunctionInfo> shared =
      69          80 :       Compiler::GetSharedFunctionInfoForScript(
      70             :           isolate, source_code, Compiler::ScriptDetails(),
      71             :           v8::ScriptOriginOptions(), nullptr, nullptr,
      72             :           v8::ScriptCompiler::kNoCompileOptions,
      73          40 :           ScriptCompiler::kNoCacheNoReason, NOT_NATIVES_CODE)
      74          40 :           .ToHandleChecked();
      75             :   return isolate->factory()->NewFunctionFromSharedFunctionInfo(
      76          80 :       shared, isolate->native_context());
      77             : }
      78             : 
      79             : 
      80           5 : static double Inc(Isolate* isolate, int x) {
      81             :   const char* source = "result = %d + 1;";
      82             :   EmbeddedVector<char, 512> buffer;
      83           5 :   SNPrintF(buffer, source, x);
      84             : 
      85           5 :   Handle<JSFunction> fun = Compile(buffer.start());
      86           5 :   if (fun.is_null()) return -1;
      87             : 
      88          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
      89          10 :   Execution::Call(isolate, fun, global, 0, nullptr).Check();
      90          10 :   return GetGlobalProperty("result")->Number();
      91             : }
      92             : 
      93             : 
      94       26644 : TEST(Inc) {
      95           5 :   CcTest::InitializeVM();
      96          10 :   v8::HandleScope scope(CcTest::isolate());
      97           5 :   CHECK_EQ(4.0, Inc(CcTest::i_isolate(), 3));
      98           5 : }
      99             : 
     100             : 
     101           5 : static double Add(Isolate* isolate, int x, int y) {
     102           5 :   Handle<JSFunction> fun = Compile("result = x + y;");
     103           5 :   if (fun.is_null()) return -1;
     104             : 
     105           5 :   SetGlobalProperty("x", Smi::FromInt(x));
     106           5 :   SetGlobalProperty("y", Smi::FromInt(y));
     107          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
     108          10 :   Execution::Call(isolate, fun, global, 0, nullptr).Check();
     109          10 :   return GetGlobalProperty("result")->Number();
     110             : }
     111             : 
     112             : 
     113       26644 : TEST(Add) {
     114           5 :   CcTest::InitializeVM();
     115          10 :   v8::HandleScope scope(CcTest::isolate());
     116           5 :   CHECK_EQ(5.0, Add(CcTest::i_isolate(), 2, 3));
     117           5 : }
     118             : 
     119             : 
     120           5 : static double Abs(Isolate* isolate, int x) {
     121           5 :   Handle<JSFunction> fun = Compile("if (x < 0) result = -x; else result = x;");
     122           5 :   if (fun.is_null()) return -1;
     123             : 
     124           5 :   SetGlobalProperty("x", Smi::FromInt(x));
     125          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
     126          10 :   Execution::Call(isolate, fun, global, 0, nullptr).Check();
     127          10 :   return GetGlobalProperty("result")->Number();
     128             : }
     129             : 
     130             : 
     131       26644 : TEST(Abs) {
     132           5 :   CcTest::InitializeVM();
     133          10 :   v8::HandleScope scope(CcTest::isolate());
     134           5 :   CHECK_EQ(3.0, Abs(CcTest::i_isolate(), -3));
     135           5 : }
     136             : 
     137             : 
     138           5 : static double Sum(Isolate* isolate, int n) {
     139             :   Handle<JSFunction> fun =
     140           5 :       Compile("s = 0; while (n > 0) { s += n; n -= 1; }; result = s;");
     141           5 :   if (fun.is_null()) return -1;
     142             : 
     143           5 :   SetGlobalProperty("n", Smi::FromInt(n));
     144          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
     145          10 :   Execution::Call(isolate, fun, global, 0, nullptr).Check();
     146          10 :   return GetGlobalProperty("result")->Number();
     147             : }
     148             : 
     149             : 
     150       26644 : TEST(Sum) {
     151           5 :   CcTest::InitializeVM();
     152          10 :   v8::HandleScope scope(CcTest::isolate());
     153           5 :   CHECK_EQ(5050.0, Sum(CcTest::i_isolate(), 100));
     154           5 : }
     155             : 
     156             : 
     157       26644 : TEST(Print) {
     158          10 :   v8::HandleScope scope(CcTest::isolate());
     159          10 :   v8::Local<v8::Context> context = CcTest::NewContext({PRINT_EXTENSION_ID});
     160             :   v8::Context::Scope context_scope(context);
     161             :   const char* source = "for (n = 0; n < 100; ++n) print(n, 1, 2);";
     162           5 :   Handle<JSFunction> fun = Compile(source);
     163           5 :   if (fun.is_null()) return;
     164          10 :   Handle<JSObject> global(CcTest::i_isolate()->context()->global_object(),
     165             :                           fun->GetIsolate());
     166          10 :   Execution::Call(CcTest::i_isolate(), fun, global, 0, nullptr).Check();
     167             : }
     168             : 
     169             : 
     170             : // The following test method stems from my coding efforts today. It
     171             : // tests all the functionality I have added to the compiler today
     172       26644 : TEST(Stuff) {
     173           5 :   CcTest::InitializeVM();
     174          10 :   v8::HandleScope scope(CcTest::isolate());
     175             :   const char* source =
     176             :     "r = 0;\n"
     177             :     "a = new Object;\n"
     178             :     "if (a == a) r+=1;\n"  // 1
     179             :     "if (a != new Object()) r+=2;\n"  // 2
     180             :     "a.x = 42;\n"
     181             :     "if (a.x == 42) r+=4;\n"  // 4
     182             :     "function foo() { var x = 87; return x; }\n"
     183             :     "if (foo() == 87) r+=8;\n"  // 8
     184             :     "function bar() { var x; x = 99; return x; }\n"
     185             :     "if (bar() == 99) r+=16;\n"  // 16
     186             :     "function baz() { var x = 1, y, z = 2; y = 3; return x + y + z; }\n"
     187             :     "if (baz() == 6) r+=32;\n"  // 32
     188             :     "function Cons0() { this.x = 42; this.y = 87; }\n"
     189             :     "if (new Cons0().x == 42) r+=64;\n"  // 64
     190             :     "if (new Cons0().y == 87) r+=128;\n"  // 128
     191             :     "function Cons2(x, y) { this.sum = x + y; }\n"
     192             :     "if (new Cons2(3,4).sum == 7) r+=256;";  // 256
     193             : 
     194           5 :   Handle<JSFunction> fun = Compile(source);
     195           5 :   CHECK(!fun.is_null());
     196          10 :   Handle<JSObject> global(CcTest::i_isolate()->context()->global_object(),
     197             :                           fun->GetIsolate());
     198          10 :   Execution::Call(CcTest::i_isolate(), fun, global, 0, nullptr).Check();
     199          10 :   CHECK_EQ(511.0, GetGlobalProperty("r")->Number());
     200           5 : }
     201             : 
     202             : 
     203       26644 : TEST(UncaughtThrow) {
     204           5 :   CcTest::InitializeVM();
     205          10 :   v8::HandleScope scope(CcTest::isolate());
     206             : 
     207             :   const char* source = "throw 42;";
     208           5 :   Handle<JSFunction> fun = Compile(source);
     209           5 :   CHECK(!fun.is_null());
     210             :   Isolate* isolate = fun->GetIsolate();
     211          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
     212          10 :   CHECK(Execution::Call(isolate, fun, global, 0, nullptr).is_null());
     213           5 :   CHECK_EQ(42.0, isolate->pending_exception()->Number());
     214           5 : }
     215             : 
     216             : 
     217             : // Tests calling a builtin function from C/C++ code, and the builtin function
     218             : // performs GC. It creates a stack frame looks like following:
     219             : //   | C (PerformGC) |
     220             : //   |   JS-to-C     |
     221             : //   |      JS       |
     222             : //   |   C-to-JS     |
     223       26644 : TEST(C2JSFrames) {
     224           5 :   FLAG_expose_gc = true;
     225          10 :   v8::HandleScope scope(CcTest::isolate());
     226             :   v8::Local<v8::Context> context =
     227          10 :       CcTest::NewContext({PRINT_EXTENSION_ID, GC_EXTENSION_ID});
     228             :   v8::Context::Scope context_scope(context);
     229             : 
     230             :   const char* source = "function foo(a) { gc(), print(a); }";
     231             : 
     232           5 :   Handle<JSFunction> fun0 = Compile(source);
     233           5 :   CHECK(!fun0.is_null());
     234             :   Isolate* isolate = fun0->GetIsolate();
     235             : 
     236             :   // Run the generated code to populate the global object with 'foo'.
     237          10 :   Handle<JSObject> global(isolate->context()->global_object(), isolate);
     238          10 :   Execution::Call(isolate, fun0, global, 0, nullptr).Check();
     239             : 
     240             :   Handle<Object> fun1 =
     241          15 :       JSReceiver::GetProperty(isolate, isolate->global_object(), "foo")
     242             :           .ToHandleChecked();
     243           5 :   CHECK(fun1->IsJSFunction());
     244             : 
     245             :   Handle<Object> argv[] = {
     246           5 :       isolate->factory()->InternalizeOneByteString(StaticCharVector("hello"))};
     247          10 :   Execution::Call(isolate,
     248             :                   Handle<JSFunction>::cast(fun1),
     249             :                   global,
     250             :                   arraysize(argv),
     251           5 :                   argv).Check();
     252           5 : }
     253             : 
     254             : 
     255             : // Regression 236. Calling InitLineEnds on a Script with undefined
     256             : // source resulted in crash.
     257       26644 : TEST(Regression236) {
     258           5 :   CcTest::InitializeVM();
     259             :   Isolate* isolate = CcTest::i_isolate();
     260             :   Factory* factory = isolate->factory();
     261          10 :   v8::HandleScope scope(CcTest::isolate());
     262             : 
     263           5 :   Handle<Script> script = factory->NewScript(factory->empty_string());
     264          15 :   script->set_source(ReadOnlyRoots(CcTest::heap()).undefined_value());
     265           5 :   CHECK_EQ(-1, Script::GetLineNumber(script, 0));
     266           5 :   CHECK_EQ(-1, Script::GetLineNumber(script, 100));
     267           5 :   CHECK_EQ(-1, Script::GetLineNumber(script, -1));
     268           5 : }
     269             : 
     270             : 
     271       26644 : TEST(GetScriptLineNumber) {
     272           5 :   LocalContext context;
     273          10 :   v8::HandleScope scope(CcTest::isolate());
     274           5 :   v8::ScriptOrigin origin = v8::ScriptOrigin(v8_str("test"));
     275           5 :   const char function_f[] = "function f() {}";
     276             :   const int max_rows = 1000;
     277             :   const int buffer_size = max_rows + sizeof(function_f);
     278             :   ScopedVector<char> buffer(buffer_size);
     279             :   memset(buffer.start(), '\n', buffer_size - 1);
     280           5 :   buffer[buffer_size - 1] = '\0';
     281             : 
     282       10005 :   for (int i = 0; i < max_rows; ++i) {
     283        5000 :     if (i > 0)
     284        9990 :       buffer[i - 1] = '\n';
     285        5000 :     MemCopy(&buffer[i], function_f, sizeof(function_f) - 1);
     286        5000 :     v8::Local<v8::String> script_body = v8_str(buffer.start());
     287        5000 :     v8::Script::Compile(context.local(), script_body, &origin)
     288             :         .ToLocalChecked()
     289        5000 :         ->Run(context.local())
     290             :         .ToLocalChecked();
     291             :     v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
     292       20000 :         context->Global()->Get(context.local(), v8_str("f")).ToLocalChecked());
     293        5000 :     CHECK_EQ(i, f->GetScriptLineNumber());
     294             :   }
     295           5 : }
     296             : 
     297             : 
     298       26644 : TEST(FeedbackVectorPreservedAcrossRecompiles) {
     299           7 :   if (i::FLAG_always_opt || !i::FLAG_opt) return;
     300           3 :   i::FLAG_allow_natives_syntax = true;
     301           3 :   CcTest::InitializeVM();
     302           3 :   if (!CcTest::i_isolate()->use_optimizer()) return;
     303           6 :   v8::HandleScope scope(CcTest::isolate());
     304           3 :   v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
     305             : 
     306             :   // Make sure function f has a call that uses a type feedback slot.
     307             :   CompileRun("function fun() {};"
     308             :              "fun1 = fun;"
     309             :              "function f(a) { a(); } f(fun1);");
     310             : 
     311             :   Handle<JSFunction> f = Handle<JSFunction>::cast(
     312             :       v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
     313          12 :           CcTest::global()->Get(context, v8_str("f")).ToLocalChecked())));
     314             : 
     315             :   // Verify that we gathered feedback.
     316             :   Handle<FeedbackVector> feedback_vector(f->feedback_vector(), f->GetIsolate());
     317           3 :   CHECK(!feedback_vector->is_empty());
     318             :   FeedbackSlot slot_for_a(0);
     319             :   MaybeObject object = feedback_vector->Get(slot_for_a);
     320             :   {
     321             :     HeapObject heap_object;
     322           3 :     CHECK(object->GetHeapObjectIfWeak(&heap_object));
     323           3 :     CHECK(heap_object->IsJSFunction());
     324             :   }
     325             : 
     326             :   CompileRun("%OptimizeFunctionOnNextCall(f); f(fun1);");
     327             : 
     328             :   // Verify that the feedback is still "gathered" despite a recompilation
     329             :   // of the full code.
     330           3 :   CHECK(f->IsOptimized());
     331             :   object = f->feedback_vector()->Get(slot_for_a);
     332             :   {
     333             :     HeapObject heap_object;
     334           3 :     CHECK(object->GetHeapObjectIfWeak(&heap_object));
     335           3 :     CHECK(heap_object->IsJSFunction());
     336             :   }
     337             : }
     338             : 
     339             : 
     340       26644 : TEST(FeedbackVectorUnaffectedByScopeChanges) {
     341           5 :   if (i::FLAG_always_opt || !i::FLAG_lazy || i::FLAG_lite_mode) {
     342           1 :     return;
     343             :   }
     344           4 :   CcTest::InitializeVM();
     345           8 :   v8::HandleScope scope(CcTest::isolate());
     346           4 :   v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
     347             : 
     348             :   CompileRun("function builder() {"
     349             :              "  call_target = function() { return 3; };"
     350             :              "  return (function() {"
     351             :              "    eval('');"
     352             :              "    return function() {"
     353             :              "      'use strict';"
     354             :              "      call_target();"
     355             :              "    }"
     356             :              "  })();"
     357             :              "}"
     358             :              "morphing_call = builder();");
     359             : 
     360             :   Handle<JSFunction> f = Handle<JSFunction>::cast(v8::Utils::OpenHandle(
     361           8 :       *v8::Local<v8::Function>::Cast(CcTest::global()
     362          12 :                                          ->Get(context, v8_str("morphing_call"))
     363             :                                          .ToLocalChecked())));
     364             : 
     365             :   // If we are compiling lazily then it should not be compiled, and so no
     366             :   // feedback vector allocated yet.
     367           4 :   CHECK(!f->shared()->is_compiled());
     368             : 
     369             :   CompileRun("morphing_call();");
     370             : 
     371             :   // Now a feedback vector is allocated.
     372           4 :   CHECK(f->shared()->is_compiled());
     373           4 :   CHECK(!f->feedback_vector()->is_empty());
     374             : }
     375             : 
     376             : // Test that optimized code for different closures is actually shared.
     377       26644 : TEST(OptimizedCodeSharing1) {
     378           5 :   FLAG_stress_compaction = false;
     379           5 :   FLAG_allow_natives_syntax = true;
     380           5 :   CcTest::InitializeVM();
     381          10 :   v8::HandleScope scope(CcTest::isolate());
     382          35 :   for (int i = 0; i < 3; i++) {
     383          15 :     LocalContext env;
     384          30 :     env->Global()
     385          75 :         ->Set(env.local(), v8_str("x"), v8::Integer::New(CcTest::isolate(), i))
     386             :         .FromJust();
     387             :     CompileRun(
     388             :         "function MakeClosure() {"
     389             :         "  return function() { return x; };"
     390             :         "}"
     391             :         "var closure0 = MakeClosure();"
     392             :         "var closure1 = MakeClosure();"  // We only share optimized code
     393             :                                          // if there are at least two closures.
     394             :         "%DebugPrint(closure0());"
     395             :         "%OptimizeFunctionOnNextCall(closure0);"
     396             :         "%DebugPrint(closure0());"
     397             :         "closure1();"
     398             :         "var closure2 = MakeClosure(); closure2();");
     399             :     Handle<JSFunction> fun1 = Handle<JSFunction>::cast(
     400             :         v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
     401          30 :             env->Global()
     402          45 :                 ->Get(env.local(), v8_str("closure1"))
     403             :                 .ToLocalChecked())));
     404             :     Handle<JSFunction> fun2 = Handle<JSFunction>::cast(
     405             :         v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
     406          30 :             env->Global()
     407          45 :                 ->Get(env.local(), v8_str("closure2"))
     408             :                 .ToLocalChecked())));
     409          18 :     CHECK(fun1->IsOptimized() || !CcTest::i_isolate()->use_optimizer());
     410          18 :     CHECK(fun2->IsOptimized() || !CcTest::i_isolate()->use_optimizer());
     411          15 :     CHECK_EQ(fun1->code(), fun2->code());
     412             :   }
     413           5 : }
     414             : 
     415       26644 : TEST(CompileFunctionInContext) {
     416           6 :   if (i::FLAG_always_opt) return;
     417           4 :   CcTest::InitializeVM();
     418           8 :   v8::HandleScope scope(CcTest::isolate());
     419           4 :   LocalContext env;
     420             :   CompileRun("var r = 10;");
     421             :   v8::Local<v8::Object> math = v8::Local<v8::Object>::Cast(
     422          16 :       env->Global()->Get(env.local(), v8_str("Math")).ToLocalChecked());
     423             :   v8::ScriptCompiler::Source script_source(v8_str(
     424             :       "a = PI * r * r;"
     425             :       "x = r * cos(PI);"
     426           4 :       "y = r * sin(PI / 2);"));
     427             :   v8::Local<v8::Function> fun =
     428           4 :       v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
     429             :                                                    0, nullptr, 1, &math)
     430             :           .ToLocalChecked();
     431           4 :   CHECK(!fun.IsEmpty());
     432             : 
     433             :   i::DisallowCompilation no_compile(CcTest::i_isolate());
     434          12 :   fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
     435          16 :   CHECK(env->Global()->Has(env.local(), v8_str("a")).FromJust());
     436             :   v8::Local<v8::Value> a =
     437          16 :       env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked();
     438           4 :   CHECK(a->IsNumber());
     439          16 :   CHECK(env->Global()->Has(env.local(), v8_str("x")).FromJust());
     440             :   v8::Local<v8::Value> x =
     441          16 :       env->Global()->Get(env.local(), v8_str("x")).ToLocalChecked();
     442           4 :   CHECK(x->IsNumber());
     443          16 :   CHECK(env->Global()->Has(env.local(), v8_str("y")).FromJust());
     444             :   v8::Local<v8::Value> y =
     445          16 :       env->Global()->Get(env.local(), v8_str("y")).ToLocalChecked();
     446           4 :   CHECK(y->IsNumber());
     447           8 :   CHECK_EQ(314.1592653589793, a->NumberValue(env.local()).FromJust());
     448           8 :   CHECK_EQ(-10.0, x->NumberValue(env.local()).FromJust());
     449           8 :   CHECK_EQ(10.0, y->NumberValue(env.local()).FromJust());
     450             : }
     451             : 
     452             : 
     453       26644 : TEST(CompileFunctionInContextComplex) {
     454           5 :   CcTest::InitializeVM();
     455          10 :   v8::HandleScope scope(CcTest::isolate());
     456           5 :   LocalContext env;
     457             :   CompileRun(
     458             :       "var x = 1;"
     459             :       "var y = 2;"
     460             :       "var z = 4;"
     461             :       "var a = {x: 8, y: 16};"
     462             :       "var b = {x: 32};");
     463          25 :   v8::Local<v8::Object> ext[2];
     464             :   ext[0] = v8::Local<v8::Object>::Cast(
     465          20 :       env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
     466             :   ext[1] = v8::Local<v8::Object>::Cast(
     467          20 :       env->Global()->Get(env.local(), v8_str("b")).ToLocalChecked());
     468           5 :   v8::ScriptCompiler::Source script_source(v8_str("result = x + y + z"));
     469             :   v8::Local<v8::Function> fun =
     470           5 :       v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
     471             :                                                    0, nullptr, 2, ext)
     472             :           .ToLocalChecked();
     473           5 :   CHECK(!fun.IsEmpty());
     474          15 :   fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
     475          20 :   CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
     476             :   v8::Local<v8::Value> result =
     477          20 :       env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
     478           5 :   CHECK(result->IsNumber());
     479          10 :   CHECK_EQ(52.0, result->NumberValue(env.local()).FromJust());
     480           5 : }
     481             : 
     482             : 
     483       26644 : TEST(CompileFunctionInContextArgs) {
     484           5 :   CcTest::InitializeVM();
     485          10 :   v8::HandleScope scope(CcTest::isolate());
     486           5 :   LocalContext env;
     487             :   CompileRun("var a = {x: 23};");
     488          15 :   v8::Local<v8::Object> ext[1];
     489             :   ext[0] = v8::Local<v8::Object>::Cast(
     490          20 :       env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
     491           5 :   v8::ScriptCompiler::Source script_source(v8_str("result = x + abc"));
     492           5 :   v8::Local<v8::String> arg = v8_str("abc");
     493             :   v8::Local<v8::Function> fun =
     494           5 :       v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
     495             :                                                    1, &arg, 1, ext)
     496             :           .ToLocalChecked();
     497          20 :   CHECK_EQ(1, fun->Get(env.local(), v8_str("length"))
     498             :                   .ToLocalChecked()
     499             :                   ->ToInt32(env.local())
     500             :                   .ToLocalChecked()
     501             :                   ->Value());
     502           5 :   v8::Local<v8::Value> arg_value = v8::Number::New(CcTest::isolate(), 42.0);
     503          15 :   fun->Call(env.local(), env->Global(), 1, &arg_value).ToLocalChecked();
     504          20 :   CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
     505             :   v8::Local<v8::Value> result =
     506          20 :       env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
     507           5 :   CHECK(result->IsNumber());
     508          10 :   CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
     509           5 : }
     510             : 
     511             : 
     512       26644 : TEST(CompileFunctionInContextComments) {
     513           5 :   CcTest::InitializeVM();
     514          10 :   v8::HandleScope scope(CcTest::isolate());
     515           5 :   LocalContext env;
     516             :   CompileRun("var a = {x: 23, y: 1, z: 2};");
     517          15 :   v8::Local<v8::Object> ext[1];
     518             :   ext[0] = v8::Local<v8::Object>::Cast(
     519          20 :       env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
     520             :   v8::Local<v8::String> source =
     521             :       CompileRun("'result = /* y + */ x + a\\u4e00 // + z'").As<v8::String>();
     522             :   v8::ScriptCompiler::Source script_source(source);
     523           5 :   v8::Local<v8::String> arg = CompileRun("'a\\u4e00'").As<v8::String>();
     524             :   v8::Local<v8::Function> fun =
     525           5 :       v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
     526             :                                                    1, &arg, 1, ext)
     527             :           .ToLocalChecked();
     528           5 :   CHECK(!fun.IsEmpty());
     529           5 :   v8::Local<v8::Value> arg_value = v8::Number::New(CcTest::isolate(), 42.0);
     530          15 :   fun->Call(env.local(), env->Global(), 1, &arg_value).ToLocalChecked();
     531          20 :   CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
     532             :   v8::Local<v8::Value> result =
     533          20 :       env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
     534           5 :   CHECK(result->IsNumber());
     535          10 :   CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
     536           5 : }
     537             : 
     538             : 
     539       26644 : TEST(CompileFunctionInContextNonIdentifierArgs) {
     540           5 :   CcTest::InitializeVM();
     541          10 :   v8::HandleScope scope(CcTest::isolate());
     542           5 :   LocalContext env;
     543           5 :   v8::ScriptCompiler::Source script_source(v8_str("result = 1"));
     544           5 :   v8::Local<v8::String> arg = v8_str("b }");
     545          10 :   CHECK(v8::ScriptCompiler::CompileFunctionInContext(
     546             :             env.local(), &script_source, 1, &arg, 0, nullptr)
     547             :             .IsEmpty());
     548           5 : }
     549             : 
     550       26644 : TEST(CompileFunctionInContextRenderCallSite) {
     551           5 :   CcTest::InitializeVM();
     552          10 :   v8::HandleScope scope(CcTest::isolate());
     553           5 :   LocalContext env;
     554             :   static const char* source1 =
     555             :       "try {"
     556             :       "  var a = [];"
     557             :       "  a[0]();"
     558             :       "} catch (e) {"
     559             :       "  return e.toString();"
     560             :       "}";
     561             :   static const char* expect1 = "TypeError: a[0] is not a function";
     562             :   static const char* source2 =
     563             :       "try {"
     564             :       "  (function() {"
     565             :       "    var a = [];"
     566             :       "    a[0]();"
     567             :       "  })()"
     568             :       "} catch (e) {"
     569             :       "  return e.toString();"
     570             :       "}";
     571             :   static const char* expect2 = "TypeError: a[0] is not a function";
     572             :   {
     573           5 :     v8::ScriptCompiler::Source script_source(v8_str(source1));
     574             :     v8::Local<v8::Function> fun =
     575           5 :         v8::ScriptCompiler::CompileFunctionInContext(
     576             :             env.local(), &script_source, 0, nullptr, 0, nullptr)
     577             :             .ToLocalChecked();
     578           5 :     CHECK(!fun.IsEmpty());
     579             :     v8::Local<v8::Value> result =
     580          15 :         fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
     581           5 :     CHECK(result->IsString());
     582          15 :     CHECK(v8::Local<v8::String>::Cast(result)
     583             :               ->Equals(env.local(), v8_str(expect1))
     584             :               .FromJust());
     585             :   }
     586             :   {
     587           5 :     v8::ScriptCompiler::Source script_source(v8_str(source2));
     588             :     v8::Local<v8::Function> fun =
     589           5 :         v8::ScriptCompiler::CompileFunctionInContext(
     590             :             env.local(), &script_source, 0, nullptr, 0, nullptr)
     591             :             .ToLocalChecked();
     592             :     v8::Local<v8::Value> result =
     593          15 :         fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
     594           5 :     CHECK(result->IsString());
     595          15 :     CHECK(v8::Local<v8::String>::Cast(result)
     596             :               ->Equals(env.local(), v8_str(expect2))
     597             :               .FromJust());
     598             :   }
     599           5 : }
     600             : 
     601       26644 : TEST(CompileFunctionInContextQuirks) {
     602           5 :   CcTest::InitializeVM();
     603          10 :   v8::HandleScope scope(CcTest::isolate());
     604           5 :   LocalContext env;
     605             :   {
     606             :     static const char* source =
     607             :         "[x, y] = ['ab', 'cd'];"
     608             :         "return x + y";
     609             :     static const char* expect = "abcd";
     610           5 :     v8::ScriptCompiler::Source script_source(v8_str(source));
     611             :     v8::Local<v8::Function> fun =
     612           5 :         v8::ScriptCompiler::CompileFunctionInContext(
     613             :             env.local(), &script_source, 0, nullptr, 0, nullptr)
     614             :             .ToLocalChecked();
     615             :     v8::Local<v8::Value> result =
     616          15 :         fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
     617           5 :     CHECK(result->IsString());
     618          15 :     CHECK(v8::Local<v8::String>::Cast(result)
     619             :               ->Equals(env.local(), v8_str(expect))
     620             :               .FromJust());
     621             :   }
     622             :   {
     623             :     static const char* source = "'use strict'; var a = 077";
     624           5 :     v8::ScriptCompiler::Source script_source(v8_str(source));
     625          10 :     v8::TryCatch try_catch(CcTest::isolate());
     626          10 :     CHECK(v8::ScriptCompiler::CompileFunctionInContext(
     627             :               env.local(), &script_source, 0, nullptr, 0, nullptr)
     628             :               .IsEmpty());
     629           5 :     CHECK(try_catch.HasCaught());
     630             :   }
     631             :   {
     632             :     static const char* source = "{ let x; { var x } }";
     633           5 :     v8::ScriptCompiler::Source script_source(v8_str(source));
     634          10 :     v8::TryCatch try_catch(CcTest::isolate());
     635          10 :     CHECK(v8::ScriptCompiler::CompileFunctionInContext(
     636             :               env.local(), &script_source, 0, nullptr, 0, nullptr)
     637             :               .IsEmpty());
     638           5 :     CHECK(try_catch.HasCaught());
     639             :   }
     640           5 : }
     641             : 
     642       26644 : TEST(CompileFunctionInContextScriptOrigin) {
     643           5 :   CcTest::InitializeVM();
     644          10 :   v8::HandleScope scope(CcTest::isolate());
     645           5 :   LocalContext env;
     646             :   v8::ScriptOrigin origin(v8_str("test"),
     647             :                           v8::Integer::New(CcTest::isolate(), 22),
     648           5 :                           v8::Integer::New(CcTest::isolate(), 41));
     649           5 :   v8::ScriptCompiler::Source script_source(v8_str("throw new Error()"), origin);
     650             :   v8::Local<v8::Function> fun =
     651           5 :       v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
     652             :                                                    0, nullptr, 0, nullptr)
     653             :           .ToLocalChecked();
     654           5 :   CHECK(!fun.IsEmpty());
     655          10 :   v8::TryCatch try_catch(CcTest::isolate());
     656           5 :   CcTest::isolate()->SetCaptureStackTraceForUncaughtExceptions(true);
     657          15 :   CHECK(fun->Call(env.local(), env->Global(), 0, nullptr).IsEmpty());
     658           5 :   CHECK(try_catch.HasCaught());
     659          10 :   CHECK(!try_catch.Exception().IsEmpty());
     660             :   v8::Local<v8::StackTrace> stack =
     661           5 :       v8::Exception::GetStackTrace(try_catch.Exception());
     662           5 :   CHECK(!stack.IsEmpty());
     663           5 :   CHECK_GT(stack->GetFrameCount(), 0);
     664           5 :   v8::Local<v8::StackFrame> frame = stack->GetFrame(CcTest::isolate(), 0);
     665           5 :   CHECK_EQ(23, frame->GetLineNumber());
     666           5 :   CHECK_EQ(42 + strlen("throw "), static_cast<unsigned>(frame->GetColumn()));
     667           5 : }
     668             : 
     669           5 : void TestCompileFunctionInContextToStringImpl() {
     670             : #define CHECK_NOT_CAUGHT(__local_context__, try_catch, __op__)                \
     671             :   do {                                                                        \
     672             :     const char* op = (__op__);                                                \
     673             :     v8::Local<v8::Context> context = (__local_context__);                     \
     674             :     if (try_catch.HasCaught()) {                                              \
     675             :       v8::String::Utf8Value error(                                            \
     676             :           CcTest::isolate(),                                                  \
     677             :           try_catch.Exception()->ToString(context).ToLocalChecked());         \
     678             :       V8_Fatal(__FILE__, __LINE__,                                            \
     679             :                "Unexpected exception thrown during %s:\n\t%s\n", op, *error); \
     680             :     }                                                                         \
     681             :   } while (false)
     682             : 
     683             :   {  // NOLINT
     684           5 :     CcTest::InitializeVM();
     685          10 :     v8::HandleScope scope(CcTest::isolate());
     686           5 :     LocalContext env;
     687             : 
     688             :     // Regression test for v8:6190
     689             :     {
     690           5 :       v8::ScriptOrigin origin(v8_str("test"), v8_int(22), v8_int(41));
     691           5 :       v8::ScriptCompiler::Source script_source(v8_str("return event"), origin);
     692             : 
     693           5 :       v8::Local<v8::String> params[] = {v8_str("event")};
     694          10 :       v8::TryCatch try_catch(CcTest::isolate());
     695             :       v8::MaybeLocal<v8::Function> maybe_fun =
     696             :           v8::ScriptCompiler::CompileFunctionInContext(
     697             :               env.local(), &script_source, arraysize(params), params, 0,
     698           5 :               nullptr);
     699             : 
     700           5 :       CHECK_NOT_CAUGHT(env.local(), try_catch,
     701             :                        "v8::ScriptCompiler::CompileFunctionInContext");
     702             : 
     703             :       v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
     704           5 :       CHECK(!fun.IsEmpty());
     705           5 :       CHECK(!try_catch.HasCaught());
     706             :       v8::Local<v8::String> result =
     707           5 :           fun->ToString(env.local()).ToLocalChecked();
     708             :       v8::Local<v8::String> expected = v8_str(
     709             :           "function (event) {\n"
     710             :           "return event\n"
     711           5 :           "}");
     712          10 :       CHECK(expected->Equals(env.local(), result).FromJust());
     713             :     }
     714             : 
     715             :     // With no parameters:
     716             :     {
     717           5 :       v8::ScriptOrigin origin(v8_str("test"), v8_int(17), v8_int(31));
     718           5 :       v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);
     719             : 
     720          10 :       v8::TryCatch try_catch(CcTest::isolate());
     721             :       v8::MaybeLocal<v8::Function> maybe_fun =
     722             :           v8::ScriptCompiler::CompileFunctionInContext(
     723           5 :               env.local(), &script_source, 0, nullptr, 0, nullptr);
     724             : 
     725           5 :       CHECK_NOT_CAUGHT(env.local(), try_catch,
     726             :                        "v8::ScriptCompiler::CompileFunctionInContext");
     727             : 
     728             :       v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
     729           5 :       CHECK(!fun.IsEmpty());
     730           5 :       CHECK(!try_catch.HasCaught());
     731             :       v8::Local<v8::String> result =
     732           5 :           fun->ToString(env.local()).ToLocalChecked();
     733             :       v8::Local<v8::String> expected = v8_str(
     734             :           "function () {\n"
     735             :           "return 0\n"
     736           5 :           "}");
     737          10 :       CHECK(expected->Equals(env.local(), result).FromJust());
     738             :     }
     739             : 
     740             :     // With a name:
     741             :     {
     742           5 :       v8::ScriptOrigin origin(v8_str("test"), v8_int(17), v8_int(31));
     743           5 :       v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);
     744             : 
     745          10 :       v8::TryCatch try_catch(CcTest::isolate());
     746             :       v8::MaybeLocal<v8::Function> maybe_fun =
     747             :           v8::ScriptCompiler::CompileFunctionInContext(
     748           5 :               env.local(), &script_source, 0, nullptr, 0, nullptr);
     749             : 
     750           5 :       CHECK_NOT_CAUGHT(env.local(), try_catch,
     751             :                        "v8::ScriptCompiler::CompileFunctionInContext");
     752             : 
     753             :       v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
     754           5 :       CHECK(!fun.IsEmpty());
     755           5 :       CHECK(!try_catch.HasCaught());
     756             : 
     757           5 :       fun->SetName(v8_str("onclick"));
     758             : 
     759             :       v8::Local<v8::String> result =
     760           5 :           fun->ToString(env.local()).ToLocalChecked();
     761             :       v8::Local<v8::String> expected = v8_str(
     762             :           "function onclick() {\n"
     763             :           "return 0\n"
     764           5 :           "}");
     765          10 :       CHECK(expected->Equals(env.local(), result).FromJust());
     766             :     }
     767             :   }
     768             : #undef CHECK_NOT_CAUGHT
     769           5 : }
     770             : 
     771       26644 : TEST(CompileFunctionInContextFunctionToString) {
     772           5 :   TestCompileFunctionInContextToStringImpl();
     773           5 : }
     774             : 
     775       26644 : TEST(InvocationCount) {
     776             :   if (FLAG_lite_mode) return;
     777           5 :   FLAG_allow_natives_syntax = true;
     778           5 :   FLAG_always_opt = false;
     779           5 :   CcTest::InitializeVM();
     780          10 :   v8::HandleScope scope(CcTest::isolate());
     781             : 
     782             :   CompileRun(
     783             :       "function bar() {};"
     784             :       "function foo() { return bar(); };"
     785             :       "foo();");
     786           5 :   Handle<JSFunction> foo = Handle<JSFunction>::cast(GetGlobalProperty("foo"));
     787           5 :   CHECK_EQ(1, foo->feedback_vector()->invocation_count());
     788             :   CompileRun("foo()");
     789           5 :   CHECK_EQ(2, foo->feedback_vector()->invocation_count());
     790             :   CompileRun("bar()");
     791           5 :   CHECK_EQ(2, foo->feedback_vector()->invocation_count());
     792             :   CompileRun("foo(); foo()");
     793           5 :   CHECK_EQ(4, foo->feedback_vector()->invocation_count());
     794             : }
     795             : 
     796       26644 : TEST(SafeToSkipArgumentsAdaptor) {
     797           5 :   CcTest::InitializeVM();
     798          10 :   v8::HandleScope scope(CcTest::isolate());
     799             :   CompileRun(
     800             :       "function a() { \"use strict\"; }; a();"
     801             :       "function b() { }; b();"
     802             :       "function c() { \"use strict\"; return arguments; }; c();"
     803             :       "function d(...args) { return args; }; d();"
     804             :       "function e() { \"use strict\"; return eval(\"\"); }; e();"
     805             :       "function f(x, y) { \"use strict\"; return x + y; }; f(1, 2);");
     806           5 :   Handle<JSFunction> a = Handle<JSFunction>::cast(GetGlobalProperty("a"));
     807           5 :   CHECK(a->shared()->is_safe_to_skip_arguments_adaptor());
     808           5 :   Handle<JSFunction> b = Handle<JSFunction>::cast(GetGlobalProperty("b"));
     809           5 :   CHECK(!b->shared()->is_safe_to_skip_arguments_adaptor());
     810           5 :   Handle<JSFunction> c = Handle<JSFunction>::cast(GetGlobalProperty("c"));
     811           5 :   CHECK(!c->shared()->is_safe_to_skip_arguments_adaptor());
     812           5 :   Handle<JSFunction> d = Handle<JSFunction>::cast(GetGlobalProperty("d"));
     813           5 :   CHECK(!d->shared()->is_safe_to_skip_arguments_adaptor());
     814           5 :   Handle<JSFunction> e = Handle<JSFunction>::cast(GetGlobalProperty("e"));
     815           5 :   CHECK(!e->shared()->is_safe_to_skip_arguments_adaptor());
     816           5 :   Handle<JSFunction> f = Handle<JSFunction>::cast(GetGlobalProperty("f"));
     817           5 :   CHECK(f->shared()->is_safe_to_skip_arguments_adaptor());
     818           5 : }
     819             : 
     820       26644 : TEST(ShallowEagerCompilation) {
     821           5 :   i::FLAG_always_opt = false;
     822           5 :   CcTest::InitializeVM();
     823           5 :   LocalContext env;
     824             :   i::Isolate* isolate = CcTest::i_isolate();
     825          10 :   v8::HandleScope scope(CcTest::isolate());
     826             :   v8::Local<v8::String> source = v8_str(
     827             :       "function f(x) {"
     828             :       "  return x + x;"
     829             :       "}"
     830           5 :       "f(2)");
     831             :   v8::ScriptCompiler::Source script_source(source);
     832             :   v8::Local<v8::Script> script =
     833           5 :       v8::ScriptCompiler::Compile(env.local(), &script_source,
     834             :                                   v8::ScriptCompiler::kEagerCompile)
     835             :           .ToLocalChecked();
     836             :   {
     837             :     v8::internal::DisallowCompilation no_compile_expected(isolate);
     838           5 :     v8::Local<v8::Value> result = script->Run(env.local()).ToLocalChecked();
     839          10 :     CHECK_EQ(4, result->Int32Value(env.local()).FromJust());
     840             :   }
     841           5 : }
     842             : 
     843       26644 : TEST(DeepEagerCompilation) {
     844           5 :   i::FLAG_always_opt = false;
     845           5 :   CcTest::InitializeVM();
     846           5 :   LocalContext env;
     847             :   i::Isolate* isolate = CcTest::i_isolate();
     848          10 :   v8::HandleScope scope(CcTest::isolate());
     849             :   v8::Local<v8::String> source = v8_str(
     850             :       "function f(x) {"
     851             :       "  function g(x) {"
     852             :       "    function h(x) {"
     853             :       "      return x ** x;"
     854             :       "    }"
     855             :       "    return h(x) * h(x);"
     856             :       "  }"
     857             :       "  return g(x) + g(x);"
     858             :       "}"
     859           5 :       "f(2)");
     860             :   v8::ScriptCompiler::Source script_source(source);
     861             :   v8::Local<v8::Script> script =
     862           5 :       v8::ScriptCompiler::Compile(env.local(), &script_source,
     863             :                                   v8::ScriptCompiler::kEagerCompile)
     864             :           .ToLocalChecked();
     865             :   {
     866             :     v8::internal::DisallowCompilation no_compile_expected(isolate);
     867           5 :     v8::Local<v8::Value> result = script->Run(env.local()).ToLocalChecked();
     868          10 :     CHECK_EQ(32, result->Int32Value(env.local()).FromJust());
     869             :   }
     870           5 : }
     871             : 
     872       26644 : TEST(DeepEagerCompilationPeakMemory) {
     873           5 :   i::FLAG_always_opt = false;
     874           5 :   CcTest::InitializeVM();
     875           5 :   LocalContext env;
     876          10 :   v8::HandleScope scope(CcTest::isolate());
     877             :   v8::Local<v8::String> source = v8_str(
     878             :       "function f() {"
     879             :       "  function g1() {"
     880             :       "    function h1() {"
     881             :       "      function i1() {}"
     882             :       "      function i2() {}"
     883             :       "    }"
     884             :       "    function h2() {"
     885             :       "      function i1() {}"
     886             :       "      function i2() {}"
     887             :       "    }"
     888             :       "  }"
     889             :       "  function g2() {"
     890             :       "    function h1() {"
     891             :       "      function i1() {}"
     892             :       "      function i2() {}"
     893             :       "    }"
     894             :       "    function h2() {"
     895             :       "      function i1() {}"
     896             :       "      function i2() {}"
     897             :       "    }"
     898             :       "  }"
     899           5 :       "}");
     900             :   v8::ScriptCompiler::Source script_source(source);
     901           5 :   CcTest::i_isolate()->compilation_cache()->Disable();
     902             : 
     903           5 :   v8::HeapStatistics heap_statistics;
     904           5 :   CcTest::isolate()->GetHeapStatistics(&heap_statistics);
     905             :   size_t peak_mem_1 = heap_statistics.peak_malloced_memory();
     906             :   printf("peak memory after init:          %8zu\n", peak_mem_1);
     907             : 
     908           5 :   v8::ScriptCompiler::Compile(env.local(), &script_source,
     909             :                               v8::ScriptCompiler::kNoCompileOptions)
     910             :       .ToLocalChecked();
     911             : 
     912           5 :   CcTest::isolate()->GetHeapStatistics(&heap_statistics);
     913             :   size_t peak_mem_2 = heap_statistics.peak_malloced_memory();
     914             :   printf("peak memory after lazy compile:  %8zu\n", peak_mem_2);
     915             : 
     916           5 :   v8::ScriptCompiler::Compile(env.local(), &script_source,
     917             :                               v8::ScriptCompiler::kNoCompileOptions)
     918             :       .ToLocalChecked();
     919             : 
     920           5 :   CcTest::isolate()->GetHeapStatistics(&heap_statistics);
     921             :   size_t peak_mem_3 = heap_statistics.peak_malloced_memory();
     922             :   printf("peak memory after lazy compile:  %8zu\n", peak_mem_3);
     923             : 
     924           5 :   v8::ScriptCompiler::Compile(env.local(), &script_source,
     925             :                               v8::ScriptCompiler::kEagerCompile)
     926             :       .ToLocalChecked();
     927             : 
     928           5 :   CcTest::isolate()->GetHeapStatistics(&heap_statistics);
     929             :   size_t peak_mem_4 = heap_statistics.peak_malloced_memory();
     930             :   printf("peak memory after eager compile: %8zu\n", peak_mem_4);
     931             : 
     932           5 :   CHECK_LE(peak_mem_1, peak_mem_2);
     933           5 :   CHECK_EQ(peak_mem_2, peak_mem_3);
     934           5 :   CHECK_LE(peak_mem_3, peak_mem_4);
     935             :   // Check that eager compilation does not cause significantly higher (+100%)
     936             :   // peak memory than lazy compilation.
     937           5 :   CHECK_LE(peak_mem_4 - peak_mem_3, peak_mem_3);
     938           5 : }
     939             : 
     940             : // TODO(mslekova): Remove the duplication with test-heap.cc
     941           2 : static int AllocationSitesCount(Heap* heap) {
     942             :   int count = 0;
     943           4 :   for (Object site = heap->allocation_sites_list(); site->IsAllocationSite();) {
     944           1 :     AllocationSite cur = AllocationSite::cast(site);
     945           1 :     CHECK(cur->HasWeakNext());
     946             :     site = cur->weak_next();
     947           1 :     count++;
     948             :   }
     949           2 :   return count;
     950             : }
     951             : 
     952             : // This test simulates a specific race-condition if GC is triggered just
     953             : // before CompilationDependencies::Commit is finished, and this changes
     954             : // the pretenuring decision, thus causing a deoptimization.
     955       26643 : TEST(DecideToPretenureDuringCompilation) {
     956             :   // The test makes use of optimization and relies on deterministic
     957             :   // compilation.
     958           4 :   if (!i::FLAG_opt || i::FLAG_always_opt ||
     959           1 :       i::FLAG_stress_incremental_marking || i::FLAG_optimize_for_size
     960             : #ifdef ENABLE_MINOR_MC
     961           1 :       || i::FLAG_minor_mc
     962             : #endif
     963             :   )
     964           3 :     return;
     965             : 
     966           1 :   FLAG_stress_gc_during_compilation = true;
     967           1 :   FLAG_allow_natives_syntax = true;
     968           1 :   FLAG_allocation_site_pretenuring = true;
     969           1 :   FLAG_flush_bytecode = false;
     970             : 
     971             :   // We want to trigger exactly 1 optimization.
     972           1 :   FLAG_use_osr = false;
     973             : 
     974             :   // We'll do manual initialization.
     975             :   ManualGCScope manual_gc_scope;
     976             :   v8::Isolate::CreateParams create_params;
     977             : 
     978             :   // This setting ensures Heap::MaximumSizeScavenge will return `true`.
     979             :   // We need to initialize the heap with at least 1 page, while keeping the
     980             :   // limit low, to ensure the new space fills even on 32-bit architectures.
     981             :   create_params.constraints.set_max_semi_space_size_in_kb(Page::kPageSize /
     982             :                                                           1024);
     983           1 :   create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
     984           1 :   v8::Isolate* isolate = v8::Isolate::New(create_params);
     985             : 
     986           1 :   isolate->Enter();
     987             :   {
     988             :     i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
     989             :     Heap* heap = i_isolate->heap();
     990             :     GlobalHandles* global_handles = i_isolate->global_handles();
     991             :     HandleScope handle_scope(i_isolate);
     992             : 
     993             :     // The allocation site at the head of the list is ours.
     994             :     Handle<AllocationSite> site;
     995             :     {
     996           1 :       LocalContext context(isolate);
     997           2 :       v8::HandleScope scope(context->GetIsolate());
     998             : 
     999           1 :       int count = AllocationSitesCount(heap);
    1000             :       CompileRun(
    1001             :           "let arr = [];"
    1002             :           "function foo(shouldKeep) {"
    1003             :           "  let local_array = new Array();"
    1004             :           "  if (shouldKeep) arr.push(local_array);"
    1005             :           "}"
    1006             :           "function bar(shouldKeep) {"
    1007             :           "  for (let i = 0; i < 10000; i++) {"
    1008             :           "    foo(shouldKeep);"
    1009             :           "  }"
    1010             :           "}"
    1011             :           "bar();");
    1012             : 
    1013             :       // This number should be >= kPretenureRatio * 10000,
    1014             :       // where 10000 is the number of iterations in `bar`,
    1015             :       // in order to make the ratio in DigestPretenuringFeedback close to 1.
    1016             :       const int memento_found_bump = 8500;
    1017             : 
    1018             :       // One allocation site should have been created.
    1019           1 :       int new_count = AllocationSitesCount(heap);
    1020           1 :       CHECK_EQ(new_count, (count + 1));
    1021             :       site = Handle<AllocationSite>::cast(global_handles->Create(
    1022             :           AllocationSite::cast(heap->allocation_sites_list())));
    1023             :       site->set_memento_found_count(memento_found_bump);
    1024             : 
    1025             :       CompileRun("%OptimizeFunctionOnNextCall(bar);");
    1026             :       CompileRun("bar(true);");
    1027             : 
    1028             :       // The last call should have caused `foo` to bail out of compilation
    1029             :       // due to dependency change (the pretenuring decision in this case).
    1030             :       // This will cause recompilation.
    1031             : 
    1032             :       // Check `bar` can get optimized again, meaning the compiler state is
    1033             :       // recoverable from this point.
    1034             :       CompileRun("%OptimizeFunctionOnNextCall(bar);");
    1035             :       CompileRun("bar();");
    1036             : 
    1037             :       Handle<Object> foo_obj =
    1038           3 :           JSReceiver::GetProperty(i_isolate, i_isolate->global_object(), "bar")
    1039             :               .ToHandleChecked();
    1040             :       Handle<JSFunction> bar = Handle<JSFunction>::cast(foo_obj);
    1041             : 
    1042           1 :       CHECK(bar->IsOptimized());
    1043             :     }
    1044             :   }
    1045           1 :   isolate->Exit();
    1046           1 :   isolate->Dispose();
    1047             : }
    1048             : 
    1049             : }  // namespace internal
    1050       79917 : }  // namespace v8

Generated by: LCOV version 1.10