/*
 * Copyright (C) 2016 Yusuke Suzuki <utatane.tea@gmail.com>
 * Copyright (C) 2016 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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.
 */

#pragma once

#include "CallFrameClosure.h"
#include "Exception.h"
#include "ExceptionHelpers.h"
#include "Instruction.h"
#include "Interpreter.h"
#include "Profiler.h"
#include "SamplingTool.h"
//#include "UnlinkedCodeBlock.h"
#include <wtf/MemoryMonitor.h>

namespace JSC {

inline OpcodeID Interpreter::getOpcodeID(const Instruction& instruction)
{
    return getOpcodeID(instruction.u.opcode);
}

#if 0
inline OpcodeID Interpreter::getOpcodeID(const UnlinkedInstruction& instruction)
{
    return instruction.u.opcode;
}
#endif

ALWAYS_INLINE bool canGrowHeap(VM& vm, CallFrame* callFrame)
{
	if(UNLIKELY(WTF::isLowMemory()))
		return false;

	if (auto* mmapMonitor = WTF::MmapMonitorBase::instance()) {
		if(LIKELY(mmapMonitor->canGrowFastCheck(0)))
			return true;

		if(vm.heap.shouldCollect())
			vm.heap.collect(false, true);

		return mmapMonitor->canGrow(callFrame, callFrame->vmEntryGlobalObject(), 0);
	}

	return true;
}

class SamplingScope {
public:
	ALWAYS_INLINE SamplingScope(Interpreter* interpreter)
        : m_interpreter(interpreter)
    {
        interpreter->startSampling();
    }
	ALWAYS_INLINE ~SamplingScope()
    {
        m_interpreter->stopSampling();
    }
private:
    Interpreter* m_interpreter;
};

ALWAYS_INLINE JSValue Interpreter::execute(CallFrameClosure& closure)
{
    JSGlobalData& vm = *closure.globalData;
    SamplingScope samplingScope(this);

    ASSERT(!vm.isCollectorBusy());
    if (vm.isCollectorBusy())
        return jsNull();

    if(!canGrowHeap(vm, closure.oldCallFrame)) {
    	throwTerminatedExecutionException(closure.oldCallFrame);
        return jsUndefined();
    }

    StackStats::CheckPoint stackCheckPoint;
    m_registerFile.validateFence(closure.newCallFrame, "BEFORE");
    m_registerFile.validateFence(closure.newCallFrame, "STEP 1");

    if (UNLIKELY(vm.watchdog && vm.watchdog->didFire(closure.oldCallFrame))) {
    	throwTerminatedExecutionException(closure.oldCallFrame);
        return jsUndefined();
    }

    if (LegacyProfiler* profiler = vm.enabledProfiler())
        profiler->willExecute(closure.oldCallFrame, closure.function);

    // The code execution below may push more frames and point the topCallFrame
    // to those newer frames, or it may pop to the top frame to the caller of
    // the current repeat frame, or it may leave the top frame pointing to the
    // current repeat frame.
    //
    // Hence, we need to preserve the topCallFrame here ourselves before
    // repeating this call on a second callback function.

    TopCallFrameSetter topCallFrame(vm, closure.newCallFrame);

    // Execute the code:
    JSValue result;
    {
        SamplingTool::CallRecord callRecord(m_sampler.get());
        Watchdog::Scope watchdogScope(vm.watchdog.get());

#if ENABLE(LLINT_C_LOOP)
        result = LLInt::CLoop::execute(closure.newCallFrame, llint_function_for_call_prologue);
#elif ENABLE(JIT)
        result = closure.functionExecutable->generatedJITCodeForCall()->execute(&m_registerFile, closure.newCallFrame, &vm);
#endif // ENABLE(JIT)
    }

    if (LegacyProfiler* profiler = vm.enabledProfiler())
        profiler->didExecute(closure.oldCallFrame, closure.function);

    m_registerFile.validateFence(closure.newCallFrame, "AFTER");
    return checkedReturn(result);
}

} // namespace JSC
