/*
 * 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/.
 */
#ifndef _include_opcodes_h_
#define _include_opcodes_h_

#include <assert.h>
#include <stdio.h>

namespace ke {

enum Opcode
{
#define OPDEF(name, number, text, length, uses, defs)   \
    name = number,
#include "Opcodes.tbl"
#undef OPDEF
    OPCODES_TOTAL
};

#define OPDEF(name, number, text, length, uses, defs)   \
static const unsigned name##_LENGTH = length;
#include "Opcodes.tbl"
#undef OPDEF

struct OpInfo
{
    const char *name;
    int length;
    int nuses;
    int ndefs;
};

typedef unsigned char bytecode;

extern OpInfo OpcodeInfo[];

static inline Opcode
Invert(Opcode op)
{
    switch (op) {
      case OP_JEQ:
        return OP_JNE;
      case OP_JNE:
        return OP_JEQ;
      case OP_JG:
        return OP_JLE;
      case OP_JGE:
        return OP_JL;
      case OP_JL:
        return OP_JGE;
      default:
        assert(op == OP_JLE);
        return OP_JG;
    }
}

static inline int
READ_INT32(bytecode *pc)
{
    return *reinterpret_cast<int *>(pc + 1);
}
static inline unsigned
READ_UINT32(bytecode *pc)
{
    return *reinterpret_cast<unsigned *>(pc + 1);
}
static inline float
READ_FLOAT(bytecode *pc)
{
    return *reinterpret_cast<float *>(pc + 1);
}

class Code;

void Disassemble(Code *code, FILE *fp);

}

#endif // _include_opcodes_h_
