/*
 * Copyright (C) 2012 David Anderson
 *
 * This file is part of JITCraft.
 *
 * JITCraft is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * JITCraft. If not, see http://www.gnu.org/licenses/.
 */
#include <new>
#include <stdlib.h>
#include "Stack.h"

using namespace jc;

Stack::Stack()
  : buffer_(NULL),
    top_(NULL),
    end_(NULL)
{
}

Stack::~Stack()
{
    free(buffer_);
}

bool
Stack::initialize()
{
    buffer_ = (char *)malloc(STACK_SIZE);
    if (!buffer_)
        return false;

    top_ = NULL;
    end_ = buffer_ + STACK_SIZE;
    return true;
}

static inline size_t
SizeForCodeFrame(Code *code)
{
    return sizeof(Frame) + sizeof(LocalSlot) * (code->nlocals() + code->maxStackDepth());
}

Frame *
Stack::pushFrame(Frame *prev, Code *code)
{
    size_t nbytes = SizeForCodeFrame(code);
    if (reinterpret_cast<char *>(top_->sp) + nbytes >= end_)
        return NULL;

    Frame *frame = reinterpret_cast<Frame *>(top_->sp);
    new (frame) Frame(prev, top_->pc, code);
    memset(frame->locals(), 0, sizeof(LocalSlot) * code->nlocals());

    top_->pc = frame->code()->start();
    top_->sp = frame->stackBase();

    return frame;
}


Frame *
Stack::popFrame(Frame *frame)
{
    Frame *prev = frame->prev();
    Code *code = frame->code();
    size_t nbytes = sizeof(LocalSlot) * code->nlocals() +
                    sizeof(Frame) +
                    sizeof(LocalSlot) * code->nargs();
    top_->pc = frame->prevpc();
    top_->sp = reinterpret_cast<LocalSlot *>(reinterpret_cast<char *>(top_->sp) - nbytes);
    return prev;
}

UnsafeStack::UnsafeStack()
  : buffer_(NULL),
    pos_(NULL),
    end_(NULL)
{
}

UnsafeStack::~UnsafeStack()
{
    free(buffer_);
}

bool
UnsafeStack::initialize()
{
    buffer_ = (char *)malloc(STACK_SIZE);
    if (!buffer_)
        return false;

    pos_ = NULL;
    end_ = buffer_ + STACK_SIZE;
    return true;
}