// Copyright 2011 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.
#include "v8.h"
#include "codegen.h"
#include "deoptimizer.h"
#include "disasm.h"
#include "full-codegen.h"
#include "global-handles.h"
#include "macro-assembler.h"
#include "prettyprinter.h"
namespace v8 {
namespace internal {
DeoptimizerData::DeoptimizerData() {
eager_deoptimization_entry_code_ = NULL;
lazy_deoptimization_entry_code_ = NULL;
current_ = NULL;
deoptimizing_code_list_ = NULL;
#ifdef ENABLE_DEBUGGER_SUPPORT
deoptimized_frame_info_ = NULL;
#endif
}
DeoptimizerData::~DeoptimizerData() {
if (eager_deoptimization_entry_code_ != NULL) {
eager_deoptimization_entry_code_->Free(EXECUTABLE);
eager_deoptimization_entry_code_ = NULL;
}
if (lazy_deoptimization_entry_code_ != NULL) {
lazy_deoptimization_entry_code_->Free(EXECUTABLE);
lazy_deoptimization_entry_code_ = NULL;
}
}
#ifdef ENABLE_DEBUGGER_SUPPORT
void DeoptimizerData::Iterate(ObjectVisitor* v) {
if (deoptimized_frame_info_ != NULL) {
deoptimized_frame_info_->Iterate(v);
}
}
#endif
Deoptimizer* Deoptimizer::New(JSFunction* function,
BailoutType type,
unsigned bailout_id,
Address from,
int fp_to_sp_delta,
Isolate* isolate) {
ASSERT(isolate == Isolate::Current());
Deoptimizer* deoptimizer = new Deoptimizer(isolate,
function,
type,
bailout_id,
from,
fp_to_sp_delta,
NULL);
ASSERT(isolate->deoptimizer_data()->current_ == NULL);
isolate->deoptimizer_data()->current_ = deoptimizer;
return deoptimizer;
}
Deoptimizer* Deoptimizer::Grab(Isolate* isolate) {
ASSERT(isolate == Isolate::Current());
Deoptimizer* result = isolate->deoptimizer_data()->current_;
ASSERT(result != NULL);
result->DeleteFrameDescriptions();
isolate->deoptimizer_data()->current_ = NULL;
return result;
}
#ifdef ENABLE_DEBUGGER_SUPPORT
DeoptimizedFrameInfo* Deoptimizer::DebuggerInspectableFrame(
JavaScriptFrame* frame,
int frame_index,
Isolate* isolate) {
ASSERT(isolate == Isolate::Current());
ASSERT(frame->is_optimized());
ASSERT(isolate->deoptimizer_data()->deoptimized_frame_info_ == NULL);
// Get the function and code from the frame.
JSFunction* function = JSFunction::cast(frame->function());
Code* code = frame->LookupCode();
Address code_start_address = code->instruction_start();
// Locate the deoptimization point in the code. As we are at a call the
// return address must be at a place in the code with deoptimization support.
int deoptimization_index = Safepoint::kNoDeoptimizationIndex;
// Scope this as the safe point constructor will disallow allocation.
{
SafepointTable table(code);
for (unsigned i = 0; i < table.length(); ++i) {
Address address = code_start_address + table.GetPcOffset(i);
if (address == frame->pc()) {
SafepointEntry safepoint_entry = table.GetEntry(i);
ASSERT(safepoint_entry.deoptimization_index() !=
Safepoint::kNoDeoptimizationIndex);
deoptimization_index = safepoint_entry.deoptimization_index();
break;
}
}
}
ASSERT(deoptimization_index != Safepoint::kNoDeoptimizationIndex);
// Always use the actual stack slots when calculating the fp to sp
// delta adding two for the function and context.
unsigned stack_slots = code->stack_slots();
unsigned fp_to_sp_delta = ((stack_slots + 2) * kPointerSize);
Deoptimizer* deoptimizer = new Deoptimizer(isolate,
function,
Deoptimizer::DEBUGGER,
deoptimization_index,
frame->pc(),
fp_to_sp_delta,
code);
Address tos = frame->fp() - fp_to_sp_delta;
deoptimizer->FillInputFrame(tos, frame);
// Calculate the output frames.
Deoptimizer::ComputeOutputFrames(deoptimizer);
// Create the GC safe output frame information and register it for GC
// handling.
ASSERT_LT(frame_index, deoptimizer->output_count());
DeoptimizedFrameInfo* info =
new DeoptimizedFrameInfo(deoptimizer, frame_index);
isolate->deoptimizer_data()->deoptimized_frame_info_ = info;
// Get the "simulated" top and size for the requested frame.
Address top =
reinterpret_cast
(deoptimizer->output_[frame_index]->GetTop());
unsigned size =
deoptimizer->output_[frame_index]->GetFrameSize() / kPointerSize;
// Done with the GC-unsafe frame descriptions. This re-enables allocation.
deoptimizer->DeleteFrameDescriptions();
// Allocate a heap number for the doubles belonging to this frame.
deoptimizer->MaterializeHeapNumbersForDebuggerInspectableFrame(
top, size, info);
// Finished using the deoptimizer instance.
delete deoptimizer;
return info;
}
void Deoptimizer::DeleteDebuggerInspectableFrame(DeoptimizedFrameInfo* info,
Isolate* isolate) {
ASSERT(isolate == Isolate::Current());
ASSERT(isolate->deoptimizer_data()->deoptimized_frame_info_ == info);
delete info;
isolate->deoptimizer_data()->deoptimized_frame_info_ = NULL;
}
#endif
void Deoptimizer::GenerateDeoptimizationEntries(MacroAssembler* masm,
int count,
BailoutType type) {
TableEntryGenerator generator(masm, type, count);
generator.Generate();
}
class DeoptimizingVisitor : public OptimizedFunctionVisitor {
public:
virtual void EnterContext(Context* context) {
if (FLAG_trace_deopt) {
PrintF("[deoptimize context: %" V8PRIxPTR "]\n",
reinterpret_cast(context));
}
}
virtual void VisitFunction(JSFunction* function) {
Deoptimizer::DeoptimizeFunction(function);
}
virtual void LeaveContext(Context* context) {
context->ClearOptimizedFunctions();
}
};
void Deoptimizer::DeoptimizeAll() {
AssertNoAllocation no_allocation;
if (FLAG_trace_deopt) {
PrintF("[deoptimize all contexts]\n");
}
DeoptimizingVisitor visitor;
VisitAllOptimizedFunctions(&visitor);
}
void Deoptimizer::DeoptimizeGlobalObject(JSObject* object) {
AssertNoAllocation no_allocation;
DeoptimizingVisitor visitor;
VisitAllOptimizedFunctionsForGlobalObject(object, &visitor);
}
void Deoptimizer::VisitAllOptimizedFunctionsForContext(
Context* context, OptimizedFunctionVisitor* visitor) {
AssertNoAllocation no_allocation;
ASSERT(context->IsGlobalContext());
visitor->EnterContext(context);
// Run through the list of optimized functions and deoptimize them.
Object* element = context->OptimizedFunctionsListHead();
while (!element->IsUndefined()) {
JSFunction* element_function = JSFunction::cast(element);
// Get the next link before deoptimizing as deoptimizing will clear the
// next link.
element = element_function->next_function_link();
visitor->VisitFunction(element_function);
}
visitor->LeaveContext(context);
}
void Deoptimizer::VisitAllOptimizedFunctionsForGlobalObject(
JSObject* object, OptimizedFunctionVisitor* visitor) {
AssertNoAllocation no_allocation;
if (object->IsJSGlobalProxy()) {
Object* proto = object->GetPrototype();
ASSERT(proto->IsJSGlobalObject());
VisitAllOptimizedFunctionsForContext(
GlobalObject::cast(proto)->global_context(), visitor);
} else if (object->IsGlobalObject()) {
VisitAllOptimizedFunctionsForContext(
GlobalObject::cast(object)->global_context(), visitor);
}
}
void Deoptimizer::VisitAllOptimizedFunctions(
OptimizedFunctionVisitor* visitor) {
AssertNoAllocation no_allocation;
// Run through the list of all global contexts and deoptimize.
Object* global = Isolate::Current()->heap()->global_contexts_list();
while (!global->IsUndefined()) {
VisitAllOptimizedFunctionsForGlobalObject(Context::cast(global)->global(),
visitor);
global = Context::cast(global)->get(Context::NEXT_CONTEXT_LINK);
}
}
void Deoptimizer::HandleWeakDeoptimizedCode(
v8::Persistent obj, void* data) {
DeoptimizingCodeListNode* node =
reinterpret_cast(data);
RemoveDeoptimizingCode(*node->code());
#ifdef DEBUG
node = Isolate::Current()->deoptimizer_data()->deoptimizing_code_list_;
while (node != NULL) {
ASSERT(node != reinterpret_cast(data));
node = node->next();
}
#endif
}
void Deoptimizer::ComputeOutputFrames(Deoptimizer* deoptimizer) {
deoptimizer->DoComputeOutputFrames();
}
Deoptimizer::Deoptimizer(Isolate* isolate,
JSFunction* function,
BailoutType type,
unsigned bailout_id,
Address from,
int fp_to_sp_delta,
Code* optimized_code)
: isolate_(isolate),
function_(function),
bailout_id_(bailout_id),
bailout_type_(type),
from_(from),
fp_to_sp_delta_(fp_to_sp_delta),
input_(NULL),
output_count_(0),
output_(NULL),
deferred_heap_numbers_(0) {
if (FLAG_trace_deopt && type != OSR) {
if (type == DEBUGGER) {
PrintF("**** DEOPT FOR DEBUGGER: ");
} else {
PrintF("**** DEOPT: ");
}
function->PrintName();
PrintF(" at bailout #%u, address 0x%" V8PRIxPTR ", frame size %d\n",
bailout_id,
reinterpret_cast(from),
fp_to_sp_delta - (2 * kPointerSize));
} else if (FLAG_trace_osr && type == OSR) {
PrintF("**** OSR: ");
function->PrintName();
PrintF(" at ast id #%u, address 0x%" V8PRIxPTR ", frame size %d\n",
bailout_id,
reinterpret_cast(from),
fp_to_sp_delta - (2 * kPointerSize));
}
// Find the optimized code.
if (type == EAGER) {
ASSERT(from == NULL);
optimized_code_ = function_->code();
} else if (type == LAZY) {
optimized_code_ = FindDeoptimizingCodeFromAddress(from);
ASSERT(optimized_code_ != NULL);
} else if (type == OSR) {
// The function has already been optimized and we're transitioning
// from the unoptimized shared version to the optimized one in the
// function. The return address (from) points to unoptimized code.
optimized_code_ = function_->code();
ASSERT(optimized_code_->kind() == Code::OPTIMIZED_FUNCTION);
ASSERT(!optimized_code_->contains(from));
} else if (type == DEBUGGER) {
optimized_code_ = optimized_code;
ASSERT(optimized_code_->contains(from));
}
ASSERT(HEAP->allow_allocation(false));
unsigned size = ComputeInputFrameSize();
input_ = new(size) FrameDescription(size, function);
#ifdef DEBUG
input_->SetKind(Code::OPTIMIZED_FUNCTION);
#endif
}
Deoptimizer::~Deoptimizer() {
ASSERT(input_ == NULL && output_ == NULL);
}
void Deoptimizer::DeleteFrameDescriptions() {
delete input_;
for (int i = 0; i < output_count_; ++i) {
if (output_[i] != input_) delete output_[i];
}
delete[] output_;
input_ = NULL;
output_ = NULL;
ASSERT(!HEAP->allow_allocation(true));
}
Address Deoptimizer::GetDeoptimizationEntry(int id, BailoutType type) {
ASSERT(id >= 0);
if (id >= kNumberOfEntries) return NULL;
LargeObjectChunk* base = NULL;
DeoptimizerData* data = Isolate::Current()->deoptimizer_data();
if (type == EAGER) {
if (data->eager_deoptimization_entry_code_ == NULL) {
data->eager_deoptimization_entry_code_ = CreateCode(type);
}
base = data->eager_deoptimization_entry_code_;
} else {
if (data->lazy_deoptimization_entry_code_ == NULL) {
data->lazy_deoptimization_entry_code_ = CreateCode(type);
}
base = data->lazy_deoptimization_entry_code_;
}
return
static_cast(base->GetStartAddress()) + (id * table_entry_size_);
}
int Deoptimizer::GetDeoptimizationId(Address addr, BailoutType type) {
LargeObjectChunk* base = NULL;
DeoptimizerData* data = Isolate::Current()->deoptimizer_data();
if (type == EAGER) {
base = data->eager_deoptimization_entry_code_;
} else {
base = data->lazy_deoptimization_entry_code_;
}
if (base == NULL ||
addr < base->GetStartAddress() ||
addr >= base->GetStartAddress() +
(kNumberOfEntries * table_entry_size_)) {
return kNotDeoptimizationEntry;
}
ASSERT_EQ(0,
static_cast(addr - base->GetStartAddress()) % table_entry_size_);
return static_cast(addr - base->GetStartAddress()) / table_entry_size_;
}
int Deoptimizer::GetOutputInfo(DeoptimizationOutputData* data,
unsigned id,
SharedFunctionInfo* shared) {
// TODO(kasperl): For now, we do a simple linear search for the PC
// offset associated with the given node id. This should probably be
// changed to a binary search.
int length = data->DeoptPoints();
Smi* smi_id = Smi::FromInt(id);
for (int i = 0; i < length; i++) {
if (data->AstId(i) == smi_id) {
return data->PcAndState(i)->value();
}
}
PrintF("[couldn't find pc offset for node=%u]\n", id);
PrintF("[method: %s]\n", *shared->DebugName()->ToCString());
// Print the source code if available.
HeapStringAllocator string_allocator;
StringStream stream(&string_allocator);
shared->SourceCodePrint(&stream, -1);
PrintF("[source:\n%s\n]", *stream.ToCString());
UNREACHABLE();
return -1;
}
int Deoptimizer::GetDeoptimizedCodeCount(Isolate* isolate) {
int length = 0;
DeoptimizingCodeListNode* node =
isolate->deoptimizer_data()->deoptimizing_code_list_;
while (node != NULL) {
length++;
node = node->next();
}
return length;
}
void Deoptimizer::DoComputeOutputFrames() {
if (bailout_type_ == OSR) {
DoComputeOsrOutputFrame();
return;
}
// Print some helpful diagnostic information.
int64_t start = OS::Ticks();
if (FLAG_trace_deopt) {
PrintF("[deoptimizing%s: begin 0x%08" V8PRIxPTR " ",
(bailout_type_ == LAZY ? " (lazy)" : ""),
reinterpret_cast(function_));
function_->PrintName();
PrintF(" @%d]\n", bailout_id_);
}
// Determine basic deoptimization information. The optimized frame is
// described by the input data.
DeoptimizationInputData* input_data =
DeoptimizationInputData::cast(optimized_code_->deoptimization_data());
unsigned node_id = input_data->AstId(bailout_id_)->value();
ByteArray* translations = input_data->TranslationByteArray();
unsigned translation_index =
input_data->TranslationIndex(bailout_id_)->value();
// Do the input frame to output frame(s) translation.
TranslationIterator iterator(translations, translation_index);
Translation::Opcode opcode =
static_cast(iterator.Next());
ASSERT(Translation::BEGIN == opcode);
USE(opcode);
// Read the number of output frames and allocate an array for their
// descriptions.
int count = iterator.Next();
ASSERT(output_ == NULL);
output_ = new FrameDescription*[count];
for (int i = 0; i < count; ++i) {
output_[i] = NULL;
}
output_count_ = count;
// Translate each output frame.
for (int i = 0; i < count; ++i) {
DoComputeFrame(&iterator, i);
}
// Print some helpful diagnostic information.
if (FLAG_trace_deopt) {
double ms = static_cast(OS::Ticks() - start) / 1000;
int index = output_count_ - 1; // Index of the topmost frame.
JSFunction* function = output_[index]->GetFunction();
PrintF("[deoptimizing: end 0x%08" V8PRIxPTR " ",
reinterpret_cast(function));
function->PrintName();
PrintF(" => node=%u, pc=0x%08" V8PRIxPTR ", state=%s, took %0.3f ms]\n",
node_id,
output_[index]->GetPc(),
FullCodeGenerator::State2String(
static_cast(
output_[index]->GetState()->value())),
ms);
}
}
void Deoptimizer::MaterializeHeapNumbers() {
ASSERT_NE(DEBUGGER, bailout_type_);
for (int i = 0; i < deferred_heap_numbers_.length(); i++) {
HeapNumberMaterializationDescriptor d = deferred_heap_numbers_[i];
Handle