<commit_before>
#include <scm/core/math/math.h>

#include <iostream>
#include <string>

#include <scm/core/utilities/boost_warning_disable.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/scoped_array.hpp>
#include <scm/core/utilities/boost_warning_enable.h>

#include <scm/data/volume/volume_data_loader_vgeo.h>
#include <scm/data/volume/volume_data_loader_raw.h>
#include <scm/data/volume/volume_data_loader_svol.h>

#include <scm/data/volume/scm_vol/scm_vol.h>

unsigned        max_dim_x;
unsigned        max_dim_y;
unsigned        max_dim_z;

std::string     input_file;
std::string     output_file;

int main(int argc, char **argv)
{
    try {
        boost::program_options::options_description  cmd_options("program options");

        cmd_options.add_options()
            ("help", "show this help message")
            ("mx", boost::program_options::value<unsigned>(&max_dim_x)->default_value(512), "maximal volume texture resolution x axis")
            ("my", boost::program_options::value<unsigned>(&max_dim_y)->default_value(512), "maximal volume texture resolution x axis")
            ("mz", boost::program_options::value<unsigned>(&max_dim_z)->default_value(512), "maximal volume texture resolution x axis")
            ("i", boost::program_options::value<std::string>(&input_file), "input volume file (.vol, .raw)")
            ("o", boost::program_options::value<std::string>(&output_file), "output volume file (.svol)");

        boost::program_options::variables_map           command_line;
        boost::program_options::parsed_options          parsed_cmd_line =  boost::program_options::parse_command_line(argc, argv, cmd_options);

        boost::program_options::store(parsed_cmd_line, command_line);
        boost::program_options::notify(command_line);

        if (command_line.count("help")) {
            std::cout << "usage: " << std::endl;
            std::cout << cmd_options;
            return (0);
        }
        if (   !command_line.count("i")
            || !command_line.count("o")) {
            std::cout << "<error>: no input or output file specified!" << std::endl;
            std::cout << "usage: " << std::endl;
            std::cout << cmd_options;
            return (0);
        }
    }
    catch (std::exception& e) {
        std::cout << e.what() << std::endl;
        return (-1);
    }

    using namespace boost::filesystem;

    path                    ifile_path(input_file);
    std::string             ifile_name       = ifile_path.leaf();
    std::string             ifile_extension  = extension(ifile_path);

    path                    ofile_path(output_file);
    std::string             ofile_name       = ofile_path.leaf();
    std::string             ofile_extension  = extension(ofile_path);

    bool                    overwrite_ofile  = false;

    if (ofile_extension != ".svol") {
        ofile_path = ofile_path.branch_path() / (basename(ofile_path) + ".svol");
        ofile_extension  = extension(ofile_path);
    }

    std::cout << "input file:\t\t" << ifile_path.file_string() << std::endl
              << "output file:\t\t" << ofile_path.file_string() << std::endl
              << "volume dimensions:\t(" << max_dim_x << ", " << max_dim_y << ", " << max_dim_z << ")" << std::endl << std::endl;

    // check if input file exists and has valid extension
    if (!exists(ifile_path) || is_directory(ifile_path)) {
        std::cout << "<error> input file ('" << ifile_path.file_string() << "') "
                  << "does not exist or is a directory" << std::endl;
        return (-1);
    }

    if (   ifile_extension != ".vol"
        && ifile_extension != ".raw") {
        std::cout << "<error> input file ('" << ifile_path.file_string() << "') "
                  << "is not of a supported volume type (.raw, .vol)" << std::endl;
        return (-1);
    }

    // now check if output file exists, i yes ask i overwrite is ok
    if (is_directory(ofile_path)) {
        std::cout << "<error> output file ('" << ofile_path.file_string() << "') "
                  << "is a directory" << std::endl;
        return (-1);
    }
    if (exists(ofile_path)) {
        std::cout << "output file ('" << ofile_path.file_string() << "') "
                  << "allready exists" << std::endl;

        std::cout << "overwrite? (y/n): ";
        char a;
        std::cin  >> a;

        if (a == 'y' || a == 'Y') {
            overwrite_ofile = true;
        }
        else {
            std::cout << std::endl << "please choose another output file" << std::endl;
            return (-1);
        }
    }

    boost::scoped_ptr<scm::data::volume_data_loader> vol_loader;
    if (ifile_extension == ".vol") {
        vol_loader.reset(new scm::data::volume_data_loader_vgeo());
    }
    else if (ifile_extension == ".raw") {
        vol_loader.reset(new scm::data::volume_data_loader_raw());
    }
    else if (ifile_extension == ".svol") {
        vol_loader.reset(new scm::data::volume_data_loader_svol());
    }

    if (!vol_loader->open_file(ifile_path.file_string())) {
        std::cout << "<error> during opening of file ('" << ifile_path.file_string() << "')"
                  << std::endl;
        return (-1);
    }

    const scm::data::volume_descriptor&  vol_desc = vol_loader->get_volume_descriptor();

    math::vec3ui_t data_dimensions = vol_desc._data_dimensions;

    std::cout << std::endl
              << "input volume data dimensions: "
              << "("  << data_dimensions.x
              << ", " << data_dimensions.y
              << ", " << data_dimensions.z << ")" << std::endl;

    unsigned int tiles_x, tiles_y, tiles_z;

    tiles_x = unsigned(math::ceil(float(data_dimensions.x) / float(max_dim_x)));
    tiles_y = unsigned(math::ceil(float(data_dimensions.y) / float(max_dim_y)));
    tiles_z = unsigned(math::ceil(float(data_dimensions.z) / float(max_dim_z)));

    std::cout << std::endl
              << "outputting volume tiles (num_x, num_y, num_z): "
              << "("  << tiles_x
              << ", " << tiles_y
              << ", " << tiles_z << ")" << std::endl;

    unsigned off_x, off_y, off_z;
    unsigned d_x, d_y, d_z;
    unsigned rem_x, rem_y, rem_z;

    rem_x = data_dimensions.x % max_dim_x;
    rem_y = data_dimensions.y % max_dim_y;
    rem_z = data_dimensions.z % max_dim_z;

    boost::scoped_array<unsigned char> buffer;

    std::string out_filename_svol;
    std::string out_filename_sraw;

    std::ofstream out_file_svol;
    std::ofstream out_file_sraw;

    scm::data::volume_descriptor out_vol_desc;

    out_vol_desc._data_num_channels     = vol_desc._data_num_channels;
    out_vol_desc._data_byte_per_channel = vol_desc._data_byte_per_channel;
    out_vol_desc._volume_aspect         = vol_desc._volume_aspect;
    out_vol_desc._name                  = basename(ifile_path);

    for (unsigned z = 0; z < tiles_z; z++) {
        for (unsigned y = 0; y < tiles_y; y++) {
            for (unsigned x = 0; x < tiles_x; x++) {

                off_x = x * max_dim_x;
                off_y = y * max_dim_y;
                off_z = z * max_dim_z;

                d_x = (off_x + max_dim_x) > data_dimensions.x ? rem_x : max_dim_x;
                d_y = (off_y + max_dim_y) > data_dimensions.y ? rem_y : max_dim_y;
                d_z = (off_z + max_dim_z) > data_dimensions.z ? rem_z : max_dim_z;

                buffer.reset(new unsigned char[d_x * d_y * d_z]);

                if (!vol_loader->read_sub_volume_data(math::vec<unsigned, 3>(off_x, off_y, off_z),
                                                      math::vec<unsigned, 3>(d_x, d_y, d_z), buffer.get())) {
                    std::cout << "error reading data" << std::endl;
                    vol_loader->close_file();
                    return (-1);
                }

                out_vol_desc._data_dimensions = math::vec3ui_t(d_x, d_y, d_z);
                out_vol_desc._volume_origin   = vol_desc._volume_origin + math::vec3f_t(float(off_x), float(off_y), float(off_z));
                out_vol_desc._brick_index     = math::vec3ui_t(x, y, z);

                // do we have to put out multiple bricks
                if (tiles_x != 1 || tiles_y != 1 || tiles_z != 1) {
                    out_filename_svol =   (basename(ofile_path)
                                         + "_" + boost::lexical_cast<std::string>(x)
                                         + "_" + boost::lexical_cast<std::string>(y)
                                         + "_" + boost::lexical_cast<std::string>(z));

                    out_filename_sraw = out_filename_svol + ".sraw";
                    out_filename_svol = (ofile_path.branch_path() / (out_filename_svol + ofile_extension)).file_string();
                }
                else {
                    out_filename_svol = (ofile_path.branch_path() / (basename(ofile_path) + ofile_extension)).file_string();
                    out_filename_sraw = (basename(ofile_path) + ".sraw");
                }

                out_vol_desc._sraw_file = out_filename_sraw;

                out_filename_sraw = (ofile_path.branch_path() / out_filename_sraw).file_string();

                out_file_sraw.open(out_filename_sraw.c_str(), std::ios::out | std::ios::binary);
                if (!out_file_sraw) {
                    std::cout << "error opening output file: " << out_filename_sraw << std::endl;
                    vol_loader->close_file();
                    return (-1);
                }

                out_file_sraw.write(reinterpret_cast<const char*>(buffer.get()), d_x * d_y * d_z);

                if (out_file_sraw.fail()) {
                    out_file_sraw.close();
                    std::cout << "error writing output file: " << out_filename_sraw << std::endl;
                    vol_loader->close_file();
                    return (-1);
                }

                out_file_sraw.close();

                out_file_svol.open(out_filename_svol.c_str(), std::ios::out);
                if (!out_file_svol) {
                    std::cout << "error opening output file: " << out_filename_svol << std::endl;
                    vol_loader->close_file();
                    return (-1);
                }

                out_file_svol << out_vol_desc;

                if (out_file_svol.fail()) {
                    out_file_svol.close();
                    std::cout << "error writing output file: " << out_filename_svol << std::endl;
                    vol_loader->close_file();
                    return (-1);
                }

                out_file_svol.close();
            }
        }
    }

    vol_loader->close_file();

    return (0);
}<commit_msg>working copy structure work<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2007-2008 The Florida State University
 * 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 the copyright holders 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.
 *
 * Authors: Stephen Hines
 */
#ifndef __ARCH_ARM_INSTS_STATICINST_HH__
#define __ARCH_ARM_INSTS_STATICINST_HH__

#include "base/trace.hh"
#include "cpu/static_inst.hh"

namespace ArmISA
{
class ArmStaticInst : public StaticInst
{
  protected:
    int32_t shift_rm_imm(uint32_t base, uint32_t shamt,
                         uint32_t type, uint32_t cfval) const;
    int32_t shift_rm_rs(uint32_t base, uint32_t shamt,
                        uint32_t type, uint32_t cfval) const;

    bool shift_carry_imm(uint32_t base, uint32_t shamt,
                         uint32_t type, uint32_t cfval) const;
    bool shift_carry_rs(uint32_t base, uint32_t shamt,
                        uint32_t type, uint32_t cfval) const;

    template<int width>
    static bool
    saturateOp(int32_t &res, int64_t op1, int64_t op2, bool sub=false)
    {
        int64_t midRes = sub ? (op1 - op2) : (op1 + op2);
        if (bits(midRes, width) != bits(midRes, width - 1)) {
            if (midRes > 0)
                res = (LL(1) << (width - 1)) - 1;
            else
                res = -(LL(1) << (width - 1));
            return true;
        } else {
            res = midRes;
            return false;
        }
    }

    static bool
    satInt(int32_t &res, int64_t op, int width)
    {
        width--;
        if (op >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (op < -(LL(1) << width)) {
            res = -(LL(1) << width);
            return true;
        } else {
            res = op;
            return false;
        }
    }

    template<int width>
    static bool
    uSaturateOp(uint32_t &res, int64_t op1, int64_t op2, bool sub=false)
    {
        int64_t midRes = sub ? (op1 - op2) : (op1 + op2);
        if (midRes >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (midRes < 0) {
            res = 0;
            return true;
        } else {
            res = midRes;
            return false;
        }
    }

    static bool
    uSatInt(int32_t &res, int64_t op, int width)
    {
        if (op >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (op < 0) {
            res = 0;
            return true;
        } else {
            res = op;
            return false;
        }
    }

    // Constructor
    ArmStaticInst(const char *mnem, ExtMachInst _machInst,
                  OpClass __opClass)
        : StaticInst(mnem, _machInst, __opClass)
    {
    }

    /// Print a register name for disassembly given the unique
    /// dependence tag number (FP or int).
    void printReg(std::ostream &os, int reg) const;
    void printMnemonic(std::ostream &os,
                       const std::string &suffix = "",
                       bool withPred = true) const;
    void printMemSymbol(std::ostream &os, const SymbolTable *symtab,
                        const std::string &prefix, const Addr addr,
                        const std::string &suffix) const;
    void printShiftOperand(std::ostream &os, IntRegIndex rm,
                           bool immShift, uint32_t shiftAmt,
                           IntRegIndex rs, ArmShiftType type) const;

    void printDataInst(std::ostream &os, bool withImm) const;
    void printDataInst(std::ostream &os, bool withImm, bool immShift, bool s,
                       IntRegIndex rd, IntRegIndex rn, IntRegIndex rm,
                       IntRegIndex rs, uint32_t shiftAmt, ArmShiftType type,
                       uint32_t imm) const;

    std::string generateDisassembly(Addr pc, const SymbolTable *symtab) const;

    static uint32_t
    cpsrWriteByInstr(CPSR cpsr, uint32_t val,
            uint8_t byteMask, bool affectState, bool nmfi)
    {
        bool privileged = (cpsr.mode != MODE_USER);

        uint32_t bitMask = 0;

        if (bits(byteMask, 3)) {
            unsigned lowIdx = affectState ? 24 : 27;
            bitMask = bitMask | mask(31, lowIdx);
        }
        if (bits(byteMask, 2)) {
            bitMask = bitMask | mask(19, 16);
        }
        if (bits(byteMask, 1)) {
            unsigned highIdx = affectState ? 15 : 9;
            unsigned lowIdx = privileged ? 8 : 9;
            bitMask = bitMask | mask(highIdx, lowIdx);
        }
        if (bits(byteMask, 0)) {
            if (privileged) {
                bitMask = bitMask | mask(7, 6);
                if (!badMode((OperatingMode)(val & mask(5)))) {
                    bitMask = bitMask | mask(5);
                } else {
                    warn_once("Ignoring write of bad mode to CPSR.\n");
                }
            }
            if (affectState)
                bitMask = bitMask | (1 << 5);
        }

        bool cpsr_f = cpsr.f;
        uint32_t new_cpsr = ((uint32_t)cpsr & ~bitMask) | (val & bitMask);
        if (nmfi && !cpsr_f)
            new_cpsr &= ~(1 << 6);
        return new_cpsr;
    }

    static uint32_t
    spsrWriteByInstr(uint32_t spsr, uint32_t val,
            uint8_t byteMask, bool affectState)
    {
        uint32_t bitMask = 0;

        if (bits(byteMask, 3))
            bitMask = bitMask | mask(31, 24);
        if (bits(byteMask, 2))
            bitMask = bitMask | mask(19, 16);
        if (bits(byteMask, 1))
            bitMask = bitMask | mask(15, 8);
        if (bits(byteMask, 0))
            bitMask = bitMask | mask(7, 0);

        return ((spsr & ~bitMask) | (val & bitMask));
    }

    template<class XC>
    static Addr
    readPC(XC *xc)
    {
        Addr pc = xc->readPC();
        Addr tBit = pc & (ULL(1) << PcTBitShift);
        if (tBit)
            return pc + 4;
        else
            return pc + 8;
    }

    // Perform an regular branch.
    template<class XC>
    static void
    setNextPC(XC *xc, Addr val)
    {
        Addr npc = xc->readNextPC();
        if (npc & (ULL(1) << PcTBitShift)) {
            val &= ~mask(1);
        } else {
            val &= ~mask(2);
        }
        xc->setNextPC((npc & PcModeMask) |
                      (val & ~PcModeMask));
    }

    template<class T>
    static T
    cSwap(T val, bool big)
    {
        if (big) {
            return gtobe(val);
        } else {
            return gtole(val);
        }
    }

    // Perform an interworking branch.
    template<class XC>
    static void
    setIWNextPC(XC *xc, Addr val)
    {
        Addr stateBits = xc->readPC() & PcModeMask;
        Addr jBit = (ULL(1) << PcJBitShift);
        Addr tBit = (ULL(1) << PcTBitShift);
        bool thumbEE = (stateBits == (tBit | jBit));

        Addr newPc = (val & ~PcModeMask);
        if (thumbEE) {
            if (bits(newPc, 0)) {
                newPc = newPc & ~mask(1);
            } else {
                panic("Bad thumbEE interworking branch address %#x.\n", newPc);
            }
        } else {
            if (bits(newPc, 0)) {
                stateBits = tBit;
                newPc = newPc & ~mask(1);
            } else if (!bits(newPc, 1)) {
                stateBits = 0;
            } else {
                warn("Bad interworking branch address %#x.\n", newPc);
            }
        }
        newPc = newPc | stateBits;
        xc->setNextPC(newPc);
    }

    // Perform an interworking branch in ARM mode, a regular branch
    // otherwise.
    template<class XC>
    static void
    setAIWNextPC(XC *xc, Addr val)
    {
        Addr stateBits = xc->readPC() & PcModeMask;
        Addr jBit = (ULL(1) << PcJBitShift);
        Addr tBit = (ULL(1) << PcTBitShift);
        if (!jBit && !tBit) {
            setIWNextPC(xc, val);
        } else {
            setNextPC(xc, val);
        }
    }
};
}

#endif //__ARCH_ARM_INSTS_STATICINST_HH__
<commit_msg>ARM: Mark some ARM static inst functions as inline.<commit_after>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2007-2008 The Florida State University
 * 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 the copyright holders 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.
 *
 * Authors: Stephen Hines
 */
#ifndef __ARCH_ARM_INSTS_STATICINST_HH__
#define __ARCH_ARM_INSTS_STATICINST_HH__

#include "base/trace.hh"
#include "cpu/static_inst.hh"

namespace ArmISA
{

class ArmStaticInst : public StaticInst
{
  protected:
    int32_t shift_rm_imm(uint32_t base, uint32_t shamt,
                         uint32_t type, uint32_t cfval) const;
    int32_t shift_rm_rs(uint32_t base, uint32_t shamt,
                        uint32_t type, uint32_t cfval) const;

    bool shift_carry_imm(uint32_t base, uint32_t shamt,
                         uint32_t type, uint32_t cfval) const;
    bool shift_carry_rs(uint32_t base, uint32_t shamt,
                        uint32_t type, uint32_t cfval) const;

    template<int width>
    static inline bool
    saturateOp(int32_t &res, int64_t op1, int64_t op2, bool sub=false)
    {
        int64_t midRes = sub ? (op1 - op2) : (op1 + op2);
        if (bits(midRes, width) != bits(midRes, width - 1)) {
            if (midRes > 0)
                res = (LL(1) << (width - 1)) - 1;
            else
                res = -(LL(1) << (width - 1));
            return true;
        } else {
            res = midRes;
            return false;
        }
    }

    static inline bool
    satInt(int32_t &res, int64_t op, int width)
    {
        width--;
        if (op >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (op < -(LL(1) << width)) {
            res = -(LL(1) << width);
            return true;
        } else {
            res = op;
            return false;
        }
    }

    template<int width>
    static inline bool
    uSaturateOp(uint32_t &res, int64_t op1, int64_t op2, bool sub=false)
    {
        int64_t midRes = sub ? (op1 - op2) : (op1 + op2);
        if (midRes >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (midRes < 0) {
            res = 0;
            return true;
        } else {
            res = midRes;
            return false;
        }
    }

    static inline bool
    uSatInt(int32_t &res, int64_t op, int width)
    {
        if (op >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (op < 0) {
            res = 0;
            return true;
        } else {
            res = op;
            return false;
        }
    }

    // Constructor
    ArmStaticInst(const char *mnem, ExtMachInst _machInst,
                  OpClass __opClass)
        : StaticInst(mnem, _machInst, __opClass)
    {
    }

    /// Print a register name for disassembly given the unique
    /// dependence tag number (FP or int).
    void printReg(std::ostream &os, int reg) const;
    void printMnemonic(std::ostream &os,
                       const std::string &suffix = "",
                       bool withPred = true) const;
    void printMemSymbol(std::ostream &os, const SymbolTable *symtab,
                        const std::string &prefix, const Addr addr,
                        const std::string &suffix) const;
    void printShiftOperand(std::ostream &os, IntRegIndex rm,
                           bool immShift, uint32_t shiftAmt,
                           IntRegIndex rs, ArmShiftType type) const;

    void printDataInst(std::ostream &os, bool withImm) const;
    void printDataInst(std::ostream &os, bool withImm, bool immShift, bool s,
                       IntRegIndex rd, IntRegIndex rn, IntRegIndex rm,
                       IntRegIndex rs, uint32_t shiftAmt, ArmShiftType type,
                       uint32_t imm) const;

    std::string generateDisassembly(Addr pc, const SymbolTable *symtab) const;

    static inline uint32_t
    cpsrWriteByInstr(CPSR cpsr, uint32_t val,
            uint8_t byteMask, bool affectState, bool nmfi)
    {
        bool privileged = (cpsr.mode != MODE_USER);

        uint32_t bitMask = 0;

        if (bits(byteMask, 3)) {
            unsigned lowIdx = affectState ? 24 : 27;
            bitMask = bitMask | mask(31, lowIdx);
        }
        if (bits(byteMask, 2)) {
            bitMask = bitMask | mask(19, 16);
        }
        if (bits(byteMask, 1)) {
            unsigned highIdx = affectState ? 15 : 9;
            unsigned lowIdx = privileged ? 8 : 9;
            bitMask = bitMask | mask(highIdx, lowIdx);
        }
        if (bits(byteMask, 0)) {
            if (privileged) {
                bitMask = bitMask | mask(7, 6);
                if (!badMode((OperatingMode)(val & mask(5)))) {
                    bitMask = bitMask | mask(5);
                } else {
                    warn_once("Ignoring write of bad mode to CPSR.\n");
                }
            }
            if (affectState)
                bitMask = bitMask | (1 << 5);
        }

        bool cpsr_f = cpsr.f;
        uint32_t new_cpsr = ((uint32_t)cpsr & ~bitMask) | (val & bitMask);
        if (nmfi && !cpsr_f)
            new_cpsr &= ~(1 << 6);
        return new_cpsr;
    }

    static inline uint32_t
    spsrWriteByInstr(uint32_t spsr, uint32_t val,
            uint8_t byteMask, bool affectState)
    {
        uint32_t bitMask = 0;

        if (bits(byteMask, 3))
            bitMask = bitMask | mask(31, 24);
        if (bits(byteMask, 2))
            bitMask = bitMask | mask(19, 16);
        if (bits(byteMask, 1))
            bitMask = bitMask | mask(15, 8);
        if (bits(byteMask, 0))
            bitMask = bitMask | mask(7, 0);

        return ((spsr & ~bitMask) | (val & bitMask));
    }

    template<class XC>
    static inline Addr
    readPC(XC *xc)
    {
        Addr pc = xc->readPC();
        Addr tBit = pc & (ULL(1) << PcTBitShift);
        if (tBit)
            return pc + 4;
        else
            return pc + 8;
    }

    // Perform an regular branch.
    template<class XC>
    static inline void
    setNextPC(XC *xc, Addr val)
    {
        Addr npc = xc->readNextPC();
        if (npc & (ULL(1) << PcTBitShift)) {
            val &= ~mask(1);
        } else {
            val &= ~mask(2);
        }
        xc->setNextPC((npc & PcModeMask) |
                      (val & ~PcModeMask));
    }

    template<class T>
    static inline T
    cSwap(T val, bool big)
    {
        if (big) {
            return gtobe(val);
        } else {
            return gtole(val);
        }
    }

    // Perform an interworking branch.
    template<class XC>
    static inline void
    setIWNextPC(XC *xc, Addr val)
    {
        Addr stateBits = xc->readPC() & PcModeMask;
        Addr jBit = (ULL(1) << PcJBitShift);
        Addr tBit = (ULL(1) << PcTBitShift);
        bool thumbEE = (stateBits == (tBit | jBit));

        Addr newPc = (val & ~PcModeMask);
        if (thumbEE) {
            if (bits(newPc, 0)) {
                newPc = newPc & ~mask(1);
            } else {
                panic("Bad thumbEE interworking branch address %#x.\n", newPc);
            }
        } else {
            if (bits(newPc, 0)) {
                stateBits = tBit;
                newPc = newPc & ~mask(1);
            } else if (!bits(newPc, 1)) {
                stateBits = 0;
            } else {
                warn("Bad interworking branch address %#x.\n", newPc);
            }
        }
        newPc = newPc | stateBits;
        xc->setNextPC(newPc);
    }

    // Perform an interworking branch in ARM mode, a regular branch
    // otherwise.
    template<class XC>
    static inline void
    setAIWNextPC(XC *xc, Addr val)
    {
        Addr stateBits = xc->readPC() & PcModeMask;
        Addr jBit = (ULL(1) << PcJBitShift);
        Addr tBit = (ULL(1) << PcTBitShift);
        if (!jBit && !tBit) {
            setIWNextPC(xc, val);
        } else {
            setNextPC(xc, val);
        }
    }
};
}

#endif //__ARCH_ARM_INSTS_STATICINST_HH__
<|endoftext|>


<commit_before>/*

Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.

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 HOLDER 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 "GeometryCompressor.h"

int current_free_list_maximum = 0;
int UniqueNumber () { return ++current_free_list_maximum; }

GeometryCompressor::GeometryCompressor() {
    m_free_list.resize(100);
    IncreaseFreeList();
}

void GeometryCompressor::IncreaseFreeList() {
    m_compressed_geometries.resize(m_compressed_geometries.size() + 100);
    std::generate_n (m_free_list.rend(), 100, UniqueNumber);
}

void GeometryCompressor::AppendNodeIDsToGeomtry( NodeID node_id, NodeID contracted_node_id ) {
    //check if node_id already has a list
    boost::unordered_map<unsigned, unsigned>::const_iterator map_iterator;
    map_iterator = m_node_id_to_index_map.find( node_id );

    unsigned geometry_bucket_index = std::numeric_limits<unsigned>::max();
    if( m_node_id_to_index_map.end() == map_iterator ) {
        //if not, create one
        if( m_free_list.empty() ) {
            IncreaseFreeList();
        }
        geometry_bucket_index = m_free_list.back();
        m_free_list.pop_back();
    } else {
        geometry_bucket_index = map_iterator->second;
    }

    BOOST_ASSERT( std::numeric_limits<unsigned>::max() != geometry_bucket_index );
    BOOST_ASSERT( geometry_bucket_index < m_compressed_geometries.size() );

    //append contracted_node_id to m_compressed_geometries[node_id]
    m_compressed_geometries[geometry_bucket_index].push_back(contracted_node_id);

    //append m_compressed_geometries[contracted_node_id] to m_compressed_geometries[node_id]
    map_iterator = m_node_id_to_index_map.find(contracted_node_id);
    if ( m_node_id_to_index_map.end() != map_iterator) {
        const unsigned bucket_index_to_remove = map_iterator->second;
        BOOST_ASSERT( bucket_index_to_remove < m_compressed_geometries.size() );

        m_compressed_geometries[geometry_bucket_index].insert(
            m_compressed_geometries[geometry_bucket_index].end(),
            m_compressed_geometries[bucket_index_to_remove].begin(),
            m_compressed_geometries[bucket_index_to_remove].end()
        );
        //remove m_compressed_geometries[contracted_node_id], add to free list
        m_compressed_geometries[bucket_index_to_remove].clear();
        m_free_list.push_back(bucket_index_to_remove);
    }
}

void GeometryCompressor::PrintStatistics() const {
    unsigned compressed_node_count = 0;
    const unsigned surviving_node_count = m_compressed_geometries.size();

    BOOST_FOREACH(const std::vector<unsigned> & current_vector, m_compressed_geometries) {
        compressed_node_count += current_vector.size();
    }
    SimpleLogger().Write() <<
        "surv: " << surviving_node_count <<
        ", comp: " << compressed_node_count <<
        ", comp ratio: " << ((float)surviving_node_count/std::max(compressed_node_count), 1);
}
<commit_msg>use explicit unsigned type in max operation<commit_after>/*

Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.

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 HOLDER 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 "GeometryCompressor.h"

int current_free_list_maximum = 0;
int UniqueNumber () { return ++current_free_list_maximum; }

GeometryCompressor::GeometryCompressor() {
    m_free_list.resize(100);
    IncreaseFreeList();
}

void GeometryCompressor::IncreaseFreeList() {
    m_compressed_geometries.resize(m_compressed_geometries.size() + 100);
    std::generate_n (m_free_list.rend(), 100, UniqueNumber);
}

void GeometryCompressor::AppendNodeIDsToGeomtry( NodeID node_id, NodeID contracted_node_id ) {
    //check if node_id already has a list
    boost::unordered_map<unsigned, unsigned>::const_iterator map_iterator;
    map_iterator = m_node_id_to_index_map.find( node_id );

    unsigned geometry_bucket_index = std::numeric_limits<unsigned>::max();
    if( m_node_id_to_index_map.end() == map_iterator ) {
        //if not, create one
        if( m_free_list.empty() ) {
            IncreaseFreeList();
        }
        geometry_bucket_index = m_free_list.back();
        m_free_list.pop_back();
    } else {
        geometry_bucket_index = map_iterator->second;
    }

    BOOST_ASSERT( std::numeric_limits<unsigned>::max() != geometry_bucket_index );
    BOOST_ASSERT( geometry_bucket_index < m_compressed_geometries.size() );

    //append contracted_node_id to m_compressed_geometries[node_id]
    m_compressed_geometries[geometry_bucket_index].push_back(contracted_node_id);

    //append m_compressed_geometries[contracted_node_id] to m_compressed_geometries[node_id]
    map_iterator = m_node_id_to_index_map.find(contracted_node_id);
    if ( m_node_id_to_index_map.end() != map_iterator) {
        const unsigned bucket_index_to_remove = map_iterator->second;
        BOOST_ASSERT( bucket_index_to_remove < m_compressed_geometries.size() );

        m_compressed_geometries[geometry_bucket_index].insert(
            m_compressed_geometries[geometry_bucket_index].end(),
            m_compressed_geometries[bucket_index_to_remove].begin(),
            m_compressed_geometries[bucket_index_to_remove].end()
        );
        //remove m_compressed_geometries[contracted_node_id], add to free list
        m_compressed_geometries[bucket_index_to_remove].clear();
        m_free_list.push_back(bucket_index_to_remove);
    }
}

void GeometryCompressor::PrintStatistics() const {
    unsigned compressed_node_count = 0;
    const unsigned surviving_node_count = m_compressed_geometries.size();

    BOOST_FOREACH(const std::vector<unsigned> & current_vector, m_compressed_geometries) {
        compressed_node_count += current_vector.size();
    }
    SimpleLogger().Write() <<
        "surv: " << surviving_node_count <<
        ", comp: " << compressed_node_count <<
        ", comp ratio: " << ((float)surviving_node_count/std::max(compressed_node_count, 1u) );
}
<|endoftext|>


<commit_before>//===-- core_main.cpp - Core Index Tool testbed ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/LangOptions.h"
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Index/IndexingAction.h"
#include "clang/Index/IndexDataConsumer.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Index/CodegenNameGenerator.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Serialization/ASTReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/PrettyStackTrace.h"

using namespace clang;
using namespace clang::index;
using namespace llvm;

extern "C" int indextest_core_main(int argc, const char **argv);

namespace {

enum class ActionType {
  None,
  PrintSourceSymbols,
};

namespace options {

static cl::OptionCategory IndexTestCoreCategory("index-test-core options");

static cl::opt<ActionType>
Action(cl::desc("Action:"), cl::init(ActionType::None),
       cl::values(
          clEnumValN(ActionType::PrintSourceSymbols,
                     "print-source-symbols", "Print symbols from source")),
       cl::cat(IndexTestCoreCategory));

static cl::extrahelp MoreHelp(
  "\nAdd \"-- <compiler arguments>\" at the end to setup the compiler "
  "invocation\n"
);

static cl::opt<bool>
DumpModuleImports("dump-imported-module-files",
               cl::desc("Print symbols and input files from imported modules"));

static cl::opt<bool>
IncludeLocals("include-locals", cl::desc("Print local symbols"));

static cl::opt<std::string>
ModuleFilePath("module-file",
               cl::desc("Path to module file to print symbols from"));
static cl::opt<std::string>
  ModuleFormat("fmodule-format", cl::init("raw"),
        cl::desc("Container format for clang modules and PCH, 'raw' or 'obj'"));

}
} // anonymous namespace

static void printSymbolInfo(SymbolInfo SymInfo, raw_ostream &OS);
static void printSymbolNameAndUSR(const Decl *D, ASTContext &Ctx,
                                  raw_ostream &OS);

namespace {

class PrintIndexDataConsumer : public IndexDataConsumer {
  raw_ostream &OS;
  std::unique_ptr<CodegenNameGenerator> CGNameGen;
  std::shared_ptr<Preprocessor> PP;

public:
  PrintIndexDataConsumer(raw_ostream &OS) : OS(OS) {
  }

  void initialize(ASTContext &Ctx) override {
    CGNameGen.reset(new CodegenNameGenerator(Ctx));
  }

  void setPreprocessor(std::shared_ptr<Preprocessor> PP) override {
    this->PP = std::move(PP);
  }

  bool handleDeclOccurence(const Decl *D, SymbolRoleSet Roles,
                           ArrayRef<SymbolRelation> Relations,
                           SourceLocation Loc, ASTNodeInfo ASTNode) override {
    ASTContext &Ctx = D->getASTContext();
    SourceManager &SM = Ctx.getSourceManager();

    Loc = SM.getFileLoc(Loc);
    FileID FID = SM.getFileID(Loc);
    unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
    unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
    OS << Line << ':' << Col << " | ";

    printSymbolInfo(getSymbolInfo(D), OS);
    OS << " | ";

    printSymbolNameAndUSR(D, Ctx, OS);
    OS << " | ";

    if (CGNameGen->writeName(D, OS))
      OS << "<no-cgname>";
    OS << " | ";

    printSymbolRoles(Roles, OS);
    OS << " | ";

    OS << "rel: " << Relations.size() << '\n';

    for (auto &SymRel : Relations) {
      OS << '\t';
      printSymbolRoles(SymRel.Roles, OS);
      OS << " | ";
      printSymbolNameAndUSR(SymRel.RelatedSymbol, Ctx, OS);
      OS << '\n';
    }

    return true;
  }

  bool handleModuleOccurence(const ImportDecl *ImportD, SymbolRoleSet Roles,
                             SourceLocation Loc) override {
    ASTContext &Ctx = ImportD->getASTContext();
    SourceManager &SM = Ctx.getSourceManager();

    Loc = SM.getFileLoc(Loc);
    FileID FID = SM.getFileID(Loc);
    unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
    unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
    OS << Line << ':' << Col << " | ";

    printSymbolInfo(getSymbolInfo(ImportD), OS);
    OS << " | ";

    OS << ImportD->getImportedModule()->getFullModuleName() << " | ";

    printSymbolRoles(Roles, OS);
    OS << " |\n";

    return true;
  }

  bool handleMacroOccurence(const IdentifierInfo *Name, const MacroInfo *MI,
                            SymbolRoleSet Roles, SourceLocation Loc) override {
    assert(PP);
    SourceManager &SM = PP->getSourceManager();

    Loc = SM.getFileLoc(Loc);
    FileID FID = SM.getFileID(Loc);
    unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
    unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
    OS << Line << ':' << Col << " | ";

    printSymbolInfo(getSymbolInfoForMacro(*MI), OS);
    OS << " | ";

    OS << Name->getName();
    OS << " | ";

    SmallString<256> USRBuf;
    if (generateUSRForMacro(Name->getName(), MI->getDefinitionLoc(), SM,
                            USRBuf)) {
      OS << "<no-usr>";
    } else {
      OS << USRBuf;
    }
    OS << " | ";

    printSymbolRoles(Roles, OS);
    OS << " |\n";
    return true;
  }
};

} // anonymous namespace

//===----------------------------------------------------------------------===//
// Print Source Symbols
//===----------------------------------------------------------------------===//

static void dumpModuleFileInputs(serialization::ModuleFile &Mod,
                                 ASTReader &Reader,
                                 raw_ostream &OS) {
  OS << "---- Module Inputs ----\n";
  Reader.visitInputFiles(Mod, /*IncludeSystem=*/true, /*Complain=*/false,
                        [&](const serialization::InputFile &IF, bool isSystem) {
    OS << (isSystem ? "system" : "user") << " | ";
    OS << IF.getFile()->getName() << '\n';
  });
}

static bool printSourceSymbols(ArrayRef<const char *> Args,
                               bool dumpModuleImports,
                               bool indexLocals) {
  SmallVector<const char *, 4> ArgsWithProgName;
  ArgsWithProgName.push_back("clang");
  ArgsWithProgName.append(Args.begin(), Args.end());
  IntrusiveRefCntPtr<DiagnosticsEngine>
    Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
  auto CInvok = createInvocationFromCommandLine(ArgsWithProgName, Diags);
  if (!CInvok)
    return true;

  raw_ostream &OS = outs();
  auto DataConsumer = std::make_shared<PrintIndexDataConsumer>(OS);
  IndexingOptions IndexOpts;
  IndexOpts.IndexFunctionLocals = indexLocals;
  std::unique_ptr<FrontendAction> IndexAction;
  IndexAction = createIndexingAction(DataConsumer, IndexOpts,
                                     /*WrappedAction=*/nullptr);

  auto PCHContainerOps = std::make_shared<PCHContainerOperations>();
  std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCompilerInvocationAction(
      std::move(CInvok), PCHContainerOps, Diags, IndexAction.get()));

  if (!Unit)
    return true;

  if (dumpModuleImports) {
    if (auto Reader = Unit->getASTReader()) {
      Reader->getModuleManager().visit([&](serialization::ModuleFile &Mod) -> bool {
        OS << "==== Module " << Mod.ModuleName << " ====\n";
        indexModuleFile(Mod, *Reader, *DataConsumer, IndexOpts);
        dumpModuleFileInputs(Mod, *Reader, OS);
        return true; // skip module dependencies.
      });
    }
  }

  return false;
}

static bool printSourceSymbolsFromModule(StringRef modulePath,
                                         StringRef format) {
  FileSystemOptions FileSystemOpts;
  auto pchContOps = std::make_shared<PCHContainerOperations>();
  // Register the support for object-file-wrapped Clang modules.
  pchContOps->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>());
  auto pchRdr = pchContOps->getReaderOrNull(format);
  if (!pchRdr) {
    errs() << "unknown module format: " << format << '\n';
    return true;
  }

  IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
      CompilerInstance::createDiagnostics(new DiagnosticOptions());
  std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
      modulePath, *pchRdr, ASTUnit::LoadASTOnly, Diags,
      FileSystemOpts, /*UseDebugInfo=*/false,
      /*OnlyLocalDecls=*/true, None,
      /*CaptureDiagnostics=*/false,
      /*AllowPCHWithCompilerErrors=*/true,
      /*UserFilesAreVolatile=*/false);
  if (!AU) {
    errs() << "failed to create TU for: " << modulePath << '\n';
    return true;
  }

  PrintIndexDataConsumer DataConsumer(outs());
  IndexingOptions IndexOpts;
  indexASTUnit(*AU, DataConsumer, IndexOpts);

  return false;
}

//===----------------------------------------------------------------------===//
// Helper Utils
//===----------------------------------------------------------------------===//

static void printSymbolInfo(SymbolInfo SymInfo, raw_ostream &OS) {
  OS << getSymbolKindString(SymInfo.Kind);
  if (SymInfo.SubKind != SymbolSubKind::None)
    OS << '/' << getSymbolSubKindString(SymInfo.SubKind);
  if (SymInfo.Properties) {
    OS << '(';
    printSymbolProperties(SymInfo.Properties, OS);
    OS << ')';
  }
  OS << '/' << getSymbolLanguageString(SymInfo.Lang);
}

static void printSymbolNameAndUSR(const Decl *D, ASTContext &Ctx,
                                  raw_ostream &OS) {
  if (printSymbolName(D, Ctx.getLangOpts(), OS)) {
    OS << "<no-name>";
  }
  OS << " | ";

  SmallString<256> USRBuf;
  if (generateUSRForDecl(D, USRBuf)) {
    OS << "<no-usr>";
  } else {
    OS << USRBuf;
  }
}

//===----------------------------------------------------------------------===//
// Command line processing.
//===----------------------------------------------------------------------===//

int indextest_core_main(int argc, const char **argv) {
  sys::PrintStackTraceOnErrorSignal(argv[0]);
  PrettyStackTraceProgram X(argc, argv);

  assert(argv[1] == StringRef("core"));
  ++argv;
  --argc;

  std::vector<const char *> CompArgs;
  const char **DoubleDash = std::find(argv, argv + argc, StringRef("--"));
  if (DoubleDash != argv + argc) {
    CompArgs = std::vector<const char *>(DoubleDash + 1, argv + argc);
    argc = DoubleDash - argv;
  }

  cl::HideUnrelatedOptions(options::IndexTestCoreCategory);
  cl::ParseCommandLineOptions(argc, argv, "index-test-core");

  if (options::Action == ActionType::None) {
    errs() << "error: action required; pass '-help' for options\n";
    return 1;
  }

  if (options::Action == ActionType::PrintSourceSymbols) {
    if (!options::ModuleFilePath.empty()) {
      return printSourceSymbolsFromModule(options::ModuleFilePath,
                                          options::ModuleFormat);
    }
    if (CompArgs.empty()) {
      errs() << "error: missing compiler args; pass '-- <compiler arguments>'\n";
      return 1;
    }
    return printSourceSymbols(CompArgs, options::DumpModuleImports, options::IncludeLocals);
  }

  return 0;
}
<commit_msg>[c-index-test] Use correct executable path to discover resource directory.<commit_after>//===-- core_main.cpp - Core Index Tool testbed ---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/LangOptions.h"
#include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Index/IndexingAction.h"
#include "clang/Index/IndexDataConsumer.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Index/CodegenNameGenerator.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Serialization/ASTReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/PrettyStackTrace.h"

using namespace clang;
using namespace clang::index;
using namespace llvm;

extern "C" int indextest_core_main(int argc, const char **argv);

namespace {

enum class ActionType {
  None,
  PrintSourceSymbols,
};

namespace options {

static cl::OptionCategory IndexTestCoreCategory("index-test-core options");

static cl::opt<ActionType>
Action(cl::desc("Action:"), cl::init(ActionType::None),
       cl::values(
          clEnumValN(ActionType::PrintSourceSymbols,
                     "print-source-symbols", "Print symbols from source")),
       cl::cat(IndexTestCoreCategory));

static cl::extrahelp MoreHelp(
  "\nAdd \"-- <compiler arguments>\" at the end to setup the compiler "
  "invocation\n"
);

static cl::opt<bool>
DumpModuleImports("dump-imported-module-files",
               cl::desc("Print symbols and input files from imported modules"));

static cl::opt<bool>
IncludeLocals("include-locals", cl::desc("Print local symbols"));

static cl::opt<std::string>
ModuleFilePath("module-file",
               cl::desc("Path to module file to print symbols from"));
static cl::opt<std::string>
  ModuleFormat("fmodule-format", cl::init("raw"),
        cl::desc("Container format for clang modules and PCH, 'raw' or 'obj'"));

}
} // anonymous namespace

static void printSymbolInfo(SymbolInfo SymInfo, raw_ostream &OS);
static void printSymbolNameAndUSR(const Decl *D, ASTContext &Ctx,
                                  raw_ostream &OS);

namespace {

class PrintIndexDataConsumer : public IndexDataConsumer {
  raw_ostream &OS;
  std::unique_ptr<CodegenNameGenerator> CGNameGen;
  std::shared_ptr<Preprocessor> PP;

public:
  PrintIndexDataConsumer(raw_ostream &OS) : OS(OS) {
  }

  void initialize(ASTContext &Ctx) override {
    CGNameGen.reset(new CodegenNameGenerator(Ctx));
  }

  void setPreprocessor(std::shared_ptr<Preprocessor> PP) override {
    this->PP = std::move(PP);
  }

  bool handleDeclOccurence(const Decl *D, SymbolRoleSet Roles,
                           ArrayRef<SymbolRelation> Relations,
                           SourceLocation Loc, ASTNodeInfo ASTNode) override {
    ASTContext &Ctx = D->getASTContext();
    SourceManager &SM = Ctx.getSourceManager();

    Loc = SM.getFileLoc(Loc);
    FileID FID = SM.getFileID(Loc);
    unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
    unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
    OS << Line << ':' << Col << " | ";

    printSymbolInfo(getSymbolInfo(D), OS);
    OS << " | ";

    printSymbolNameAndUSR(D, Ctx, OS);
    OS << " | ";

    if (CGNameGen->writeName(D, OS))
      OS << "<no-cgname>";
    OS << " | ";

    printSymbolRoles(Roles, OS);
    OS << " | ";

    OS << "rel: " << Relations.size() << '\n';

    for (auto &SymRel : Relations) {
      OS << '\t';
      printSymbolRoles(SymRel.Roles, OS);
      OS << " | ";
      printSymbolNameAndUSR(SymRel.RelatedSymbol, Ctx, OS);
      OS << '\n';
    }

    return true;
  }

  bool handleModuleOccurence(const ImportDecl *ImportD, SymbolRoleSet Roles,
                             SourceLocation Loc) override {
    ASTContext &Ctx = ImportD->getASTContext();
    SourceManager &SM = Ctx.getSourceManager();

    Loc = SM.getFileLoc(Loc);
    FileID FID = SM.getFileID(Loc);
    unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
    unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
    OS << Line << ':' << Col << " | ";

    printSymbolInfo(getSymbolInfo(ImportD), OS);
    OS << " | ";

    OS << ImportD->getImportedModule()->getFullModuleName() << " | ";

    printSymbolRoles(Roles, OS);
    OS << " |\n";

    return true;
  }

  bool handleMacroOccurence(const IdentifierInfo *Name, const MacroInfo *MI,
                            SymbolRoleSet Roles, SourceLocation Loc) override {
    assert(PP);
    SourceManager &SM = PP->getSourceManager();

    Loc = SM.getFileLoc(Loc);
    FileID FID = SM.getFileID(Loc);
    unsigned Line = SM.getLineNumber(FID, SM.getFileOffset(Loc));
    unsigned Col = SM.getColumnNumber(FID, SM.getFileOffset(Loc));
    OS << Line << ':' << Col << " | ";

    printSymbolInfo(getSymbolInfoForMacro(*MI), OS);
    OS << " | ";

    OS << Name->getName();
    OS << " | ";

    SmallString<256> USRBuf;
    if (generateUSRForMacro(Name->getName(), MI->getDefinitionLoc(), SM,
                            USRBuf)) {
      OS << "<no-usr>";
    } else {
      OS << USRBuf;
    }
    OS << " | ";

    printSymbolRoles(Roles, OS);
    OS << " |\n";
    return true;
  }
};

} // anonymous namespace

//===----------------------------------------------------------------------===//
// Print Source Symbols
//===----------------------------------------------------------------------===//

static void dumpModuleFileInputs(serialization::ModuleFile &Mod,
                                 ASTReader &Reader,
                                 raw_ostream &OS) {
  OS << "---- Module Inputs ----\n";
  Reader.visitInputFiles(Mod, /*IncludeSystem=*/true, /*Complain=*/false,
                        [&](const serialization::InputFile &IF, bool isSystem) {
    OS << (isSystem ? "system" : "user") << " | ";
    OS << IF.getFile()->getName() << '\n';
  });
}

static bool printSourceSymbols(const char *Executable,
                               ArrayRef<const char *> Args,
                               bool dumpModuleImports, bool indexLocals) {
  SmallVector<const char *, 4> ArgsWithProgName;
  ArgsWithProgName.push_back(Executable);
  ArgsWithProgName.append(Args.begin(), Args.end());
  IntrusiveRefCntPtr<DiagnosticsEngine>
    Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions));
  auto CInvok = createInvocationFromCommandLine(ArgsWithProgName, Diags);
  if (!CInvok)
    return true;

  raw_ostream &OS = outs();
  auto DataConsumer = std::make_shared<PrintIndexDataConsumer>(OS);
  IndexingOptions IndexOpts;
  IndexOpts.IndexFunctionLocals = indexLocals;
  std::unique_ptr<FrontendAction> IndexAction;
  IndexAction = createIndexingAction(DataConsumer, IndexOpts,
                                     /*WrappedAction=*/nullptr);

  auto PCHContainerOps = std::make_shared<PCHContainerOperations>();
  std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCompilerInvocationAction(
      std::move(CInvok), PCHContainerOps, Diags, IndexAction.get()));

  if (!Unit)
    return true;

  if (dumpModuleImports) {
    if (auto Reader = Unit->getASTReader()) {
      Reader->getModuleManager().visit([&](serialization::ModuleFile &Mod) -> bool {
        OS << "==== Module " << Mod.ModuleName << " ====\n";
        indexModuleFile(Mod, *Reader, *DataConsumer, IndexOpts);
        dumpModuleFileInputs(Mod, *Reader, OS);
        return true; // skip module dependencies.
      });
    }
  }

  return false;
}

static bool printSourceSymbolsFromModule(StringRef modulePath,
                                         StringRef format) {
  FileSystemOptions FileSystemOpts;
  auto pchContOps = std::make_shared<PCHContainerOperations>();
  // Register the support for object-file-wrapped Clang modules.
  pchContOps->registerReader(llvm::make_unique<ObjectFilePCHContainerReader>());
  auto pchRdr = pchContOps->getReaderOrNull(format);
  if (!pchRdr) {
    errs() << "unknown module format: " << format << '\n';
    return true;
  }

  IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
      CompilerInstance::createDiagnostics(new DiagnosticOptions());
  std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
      modulePath, *pchRdr, ASTUnit::LoadASTOnly, Diags,
      FileSystemOpts, /*UseDebugInfo=*/false,
      /*OnlyLocalDecls=*/true, None,
      /*CaptureDiagnostics=*/false,
      /*AllowPCHWithCompilerErrors=*/true,
      /*UserFilesAreVolatile=*/false);
  if (!AU) {
    errs() << "failed to create TU for: " << modulePath << '\n';
    return true;
  }

  PrintIndexDataConsumer DataConsumer(outs());
  IndexingOptions IndexOpts;
  indexASTUnit(*AU, DataConsumer, IndexOpts);

  return false;
}

//===----------------------------------------------------------------------===//
// Helper Utils
//===----------------------------------------------------------------------===//

static void printSymbolInfo(SymbolInfo SymInfo, raw_ostream &OS) {
  OS << getSymbolKindString(SymInfo.Kind);
  if (SymInfo.SubKind != SymbolSubKind::None)
    OS << '/' << getSymbolSubKindString(SymInfo.SubKind);
  if (SymInfo.Properties) {
    OS << '(';
    printSymbolProperties(SymInfo.Properties, OS);
    OS << ')';
  }
  OS << '/' << getSymbolLanguageString(SymInfo.Lang);
}

static void printSymbolNameAndUSR(const Decl *D, ASTContext &Ctx,
                                  raw_ostream &OS) {
  if (printSymbolName(D, Ctx.getLangOpts(), OS)) {
    OS << "<no-name>";
  }
  OS << " | ";

  SmallString<256> USRBuf;
  if (generateUSRForDecl(D, USRBuf)) {
    OS << "<no-usr>";
  } else {
    OS << USRBuf;
  }
}

//===----------------------------------------------------------------------===//
// Command line processing.
//===----------------------------------------------------------------------===//

int indextest_core_main(int argc, const char **argv) {
  sys::PrintStackTraceOnErrorSignal(argv[0]);
  PrettyStackTraceProgram X(argc, argv);
  void *MainAddr = (void*) (intptr_t) indextest_core_main;
  std::string Executable = llvm::sys::fs::getMainExecutable(argv[0], MainAddr);

  assert(argv[1] == StringRef("core"));
  ++argv;
  --argc;

  std::vector<const char *> CompArgs;
  const char **DoubleDash = std::find(argv, argv + argc, StringRef("--"));
  if (DoubleDash != argv + argc) {
    CompArgs = std::vector<const char *>(DoubleDash + 1, argv + argc);
    argc = DoubleDash - argv;
  }

  cl::HideUnrelatedOptions(options::IndexTestCoreCategory);
  cl::ParseCommandLineOptions(argc, argv, "index-test-core");

  if (options::Action == ActionType::None) {
    errs() << "error: action required; pass '-help' for options\n";
    return 1;
  }

  if (options::Action == ActionType::PrintSourceSymbols) {
    if (!options::ModuleFilePath.empty()) {
      return printSourceSymbolsFromModule(options::ModuleFilePath,
                                          options::ModuleFormat);
    }
    if (CompArgs.empty()) {
      errs() << "error: missing compiler args; pass '-- <compiler arguments>'\n";
      return 1;
    }
    return printSourceSymbols(Executable.c_str(), CompArgs,
                              options::DumpModuleImports,
                              options::IncludeLocals);
  }

  return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (C) 2010 Shantanu Tushar Jha <jhahoneyk@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "gamesmodel.h"

#include <QDir>
#include <QCoreApplication>

using namespace GluonPlayer;

GamesModel::GamesModel(QObject* parent): QAbstractTableModel(parent)
{
    m_dir.cd(QCoreApplication::applicationDirPath() + "/../share/gluon/games");
}

QVariant GamesModel::data(const QModelIndex& index, int role) const
{
    if (role == Qt::DisplayRole) {
        QString gameDirName = m_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot).at(index.row());
        QDir gameDir = m_dir;
        gameDir.cd(gameDirName);
        QStringList gluonProjectFiles = gameDir.entryList(QStringList("*.gluon"));

        if (!gluonProjectFiles.isEmpty()) {
            return gameDir.absoluteFilePath(gluonProjectFiles.at(0));
        } else {
            return QVariant();
        }
    }
}

int GamesModel::columnCount(const QModelIndex& parent) const
{
    return 1;   //Later we will add more columns for more details about each game
}

int GamesModel::rowCount(const QModelIndex& parent) const
{
    return m_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot).count();
}

QVariant GamesModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (section == 0) {
        return QString("Game");
    }
    return QAbstractItemModel::headerData(section, orientation, role);
}
<commit_msg>Fix a crash when using normal itemviews<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (C) 2010 Shantanu Tushar Jha <jhahoneyk@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "gamesmodel.h"

#include <QDir>
#include <QCoreApplication>

using namespace GluonPlayer;

GamesModel::GamesModel(QObject* parent): QAbstractTableModel(parent)
{
    m_dir.cd(QCoreApplication::applicationDirPath() + "/../share/gluon/games");
}

QVariant GamesModel::data(const QModelIndex& index, int role) const
{
    if (role == Qt::DisplayRole) {
        QString gameDirName = m_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot).at(index.row());
        QDir gameDir = m_dir;
        gameDir.cd(gameDirName);
        QStringList gluonProjectFiles = gameDir.entryList(QStringList("*.gluon"));

        if (!gluonProjectFiles.isEmpty()) {
            return gameDir.absoluteFilePath(gluonProjectFiles.at(0));
        } else {
            return QVariant();
        }
    }

    return QVariant();
}

int GamesModel::columnCount(const QModelIndex& parent) const
{
    return 1;   //Later we will add more columns for more details about each game
}

int GamesModel::rowCount(const QModelIndex& parent) const
{
    return m_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot).count();
}

QVariant GamesModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (section == 0) {
        return QString("Game");
    }
    return QAbstractItemModel::headerData(section, orientation, role);
}
<|endoftext|>


<commit_before>/* -*-c++-*-
 *
 * Copyright (C) 2005-2006 Mathias Froehlich
 *
 * This program 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 2 of the
 * License, or (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

#ifndef SGReferenced_HXX
#define SGReferenced_HXX

#include "SGAtomic.hxx"

/// Base class for all reference counted SimGear objects
/// Classes derived from this one are meant to be managed with
/// the SGSharedPtr class.
/// For more info see @SGSharedPtr.

class SGReferenced {
public:
  SGReferenced(void) : _refcount(0u)
  {}
  /// Do not copy reference counts. Each new object has it's own counter
  SGReferenced(const SGReferenced&) : _refcount(0u)
  {}
  /// Do not copy reference counts. Each object has it's own counter
  SGReferenced& operator=(const SGReferenced&)
  { return *this; }

  static unsigned get(const SGReferenced* ref)
  { if (ref) return ++(ref->_refcount); else return ~0u; }
  static unsigned put(const SGReferenced* ref)
  { if (ref) return --(ref->_refcount); else return ~0u; }
  static unsigned count(const SGReferenced* ref)
  { if (ref) return ref->_refcount; else return ~0u; }
  static bool shared(const SGReferenced* ref)
  { if (ref) return 1u < ref->_refcount; else return false; }

private:
  mutable SGAtomic _refcount;
};

#endif
<commit_msg>Add virtual destructor to SGReferenced.<commit_after>/* -*-c++-*-
 *
 * Copyright (C) 2005-2006 Mathias Froehlich
 *
 * This program 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 2 of the
 * License, or (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

#ifndef SGReferenced_HXX
#define SGReferenced_HXX

#include "SGAtomic.hxx"

/// Base class for all reference counted SimGear objects
/// Classes derived from this one are meant to be managed with
/// the SGSharedPtr class.
/// For more info see @SGSharedPtr.

class SGReferenced {
public:
  SGReferenced(void) : _refcount(0u)
  {}
  virtual ~SGReferenced()
  {}
  /// Do not copy reference counts. Each new object has it's own counter
  SGReferenced(const SGReferenced&) : _refcount(0u)
  {}
  /// Do not copy reference counts. Each object has it's own counter
  SGReferenced& operator=(const SGReferenced&)
  { return *this; }

  static unsigned get(const SGReferenced* ref)
  { if (ref) return ++(ref->_refcount); else return ~0u; }
  static unsigned put(const SGReferenced* ref)
  { if (ref) return --(ref->_refcount); else return ~0u; }
  static unsigned count(const SGReferenced* ref)
  { if (ref) return ref->_refcount; else return ~0u; }
  static bool shared(const SGReferenced* ref)
  { if (ref) return 1u < ref->_refcount; else return false; }

private:
  mutable SGAtomic _refcount;
};

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include "Game.h"
#include "Texture_manager.h"
#include "Input_handler.h"
#include "Player.h"
#include "Enemy.h"
#include "Menu_state.h"
#include "Play_state.h"
#include "utils.h"

#define DEF_RENDER_COLOR_ALPHA 0, 255, 0, 255

Game* Game::s_instance = 0;

bool Game::init(const char* title, int xpos, int ypos, int width, int height, bool fullscreen) {
	int flags = fullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_SHOWN;

	if (SDL_Init(SDL_INIT_EVERYTHING) >= 0) {
		LOG << "[SUCC] SDL Init";
		m_window = SDL_CreateWindow(title, xpos, ypos, width, height, flags);

		if (m_window != 0) {
			LOG << "[SUCC] Window Init";
			m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED);

			if (m_renderer != 0) {
				LOG << "[SUCC] Renderer Init";
				SDL_SetRenderDrawColor(m_renderer, DEF_RENDER_COLOR_ALPHA);

				if (!The_Texture_manager->load("../assets/BombExploding.png", "bomb", m_renderer))
					return false;

			} else {
				LOG << "[FAIL] Renderer Init";
				return false;
			}
		} else {
			LOG << "[FAIL] Windows Init";
			return false;
		}
	} else {
		LOG << "[FAIL] SDL Init";
		return false;
	}
	LOG << "[SUCC] Game Init";
	m_running = true;

	The_Input_handler->init_joysticks();
	m_game_state_machine = new Game_state_machine();
	m_game_state_machine->change_state(new Menu_state());

	return true;
}

void Game::update() {
	m_game_state_machine->update();
}

void Game::render() {
	SDL_RenderClear(m_renderer);

	m_game_state_machine->render();

	SDL_RenderPresent(m_renderer);
}

void Game::clean() {
	LOG << "[INFO] Cleanup";

	The_Input_handler->clean();

	SDL_DestroyWindow(m_window);
	SDL_DestroyRenderer(m_renderer);
	SDL_Quit();
}

void Game::handleEvents() {
	The_Input_handler->update();
	if (The_Input_handler->joysticks_initialized())
		if (The_Input_handler->get_joy_button_state(0, 1))
			m_game_state_machine->change_state(new Play_state());
	if (The_Input_handler->is_key_down(SDL_SCANCODE_ESCAPE))
		The_Game->quit();
}

void Game::quit() {
	m_running = false;
}<commit_msg>removed temp code<commit_after>#include <iostream>
#include "Game.h"
#include "Texture_manager.h"
#include "Input_handler.h"
#include "Player.h"
#include "Enemy.h"
#include "Menu_state.h"
#include "Play_state.h"
#include "utils.h"

#define DEF_RENDER_COLOR_ALPHA 0, 255, 0, 255

Game* Game::s_instance = 0;

bool Game::init(const char* title, int xpos, int ypos, int width, int height, bool fullscreen) {
	int flags = fullscreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_SHOWN;

	if (SDL_Init(SDL_INIT_EVERYTHING) >= 0) {
		LOG << "[SUCC] SDL Init";
		m_window = SDL_CreateWindow(title, xpos, ypos, width, height, flags);

		if (m_window != 0) {
			LOG << "[SUCC] Window Init";
			m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED);

			if (m_renderer != 0) {
				LOG << "[SUCC] Renderer Init";
				SDL_SetRenderDrawColor(m_renderer, DEF_RENDER_COLOR_ALPHA);

				if (!The_Texture_manager->load("../assets/BombExploding.png", "bomb", m_renderer))
					return false;

			} else {
				LOG << "[FAIL] Renderer Init";
				return false;
			}
		} else {
			LOG << "[FAIL] Windows Init";
			return false;
		}
	} else {
		LOG << "[FAIL] SDL Init";
		return false;
	}
	LOG << "[SUCC] Game Init";
	m_running = true;

	The_Input_handler->init_joysticks();
	m_game_state_machine = new Game_state_machine();
	m_game_state_machine->change_state(new Menu_state());

	return true;
}

void Game::update() {
	m_game_state_machine->update();
}

void Game::render() {
	SDL_RenderClear(m_renderer);

	m_game_state_machine->render();

	SDL_RenderPresent(m_renderer);
}

void Game::clean() {
	LOG << "[INFO] Cleanup";

	The_Input_handler->clean();

	SDL_DestroyWindow(m_window);
	SDL_DestroyRenderer(m_renderer);
	SDL_Quit();
}

void Game::handleEvents() {
	The_Input_handler->update();
}

void Game::quit() {
	m_running = false;
}<|endoftext|>


<commit_before>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>

using namespace std;

#define DEBUG       0

int main() {
    int n, m;
    scanf("%d %d", &n, &m);

    int max;
    vector<int> input, left_bounce, right_bounce, bounce;
    input.resize(m);
    left_bounce.resize(m);
    right_bounce.resize(m);
    bounce.resize(m, 0);

    for (size_t i = 0; i < n; i++) {
        int a;
        for (size_t j = 0; j < m; j++) {
            scanf("%d", &a);
            input[j] = a;
        }

        int tmp = 0;
        for (size_t j = 0; j < m; j++) {
            if (0 == j) {
                tmp = input[j];
            }
            else {
                if (tmp + input[j] > input[j]) {
                    tmp += input[j];
                }
                else {
                    tmp = input[j];
                }
            }
            left_bounce[j] = tmp;
        }

        for (int j = m - 1; j >= 0; j--) {
            if (m - 1 == j) {
                tmp = input[j];
            }
            else {
                if (tmp + input[j] > input[j]) {
                    tmp += input[j];
                }
                else {
                    tmp = input[j];
                }
            }
            right_bounce[j] = tmp;

            bounce[j] += left_bounce[j] + right_bounce[j] - input[j];

            if (n - 1 == i) {
                if (m - 1 == j) {
                    max = bounce[j];
                }
                else {
                    if (bounce[j] > max) {
                        max = bounce[j];
                    }
                }
            }
        }
    }

    printf("%d\n", max);

    return 0;
}
<commit_msg>read from file<commit_after>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>

using namespace std;

#define DEBUG       1

int main() {
    int n, m;
#if DEBUG
    FILE * fp = fopen("input.txt", "r");
    fscanf(fp, "%d %d", &n, &m);
#else
    scanf("%d %d", &n, &m);
#endif

    int max;
    vector<int> input, left_bounce, right_bounce, bounce;
    input.resize(m);
    left_bounce.resize(m);
    right_bounce.resize(m);
    bounce.resize(m, 0);

    for (size_t i = 0; i < n; i++) {
        int a;
        for (size_t j = 0; j < m; j++) {
#if DEBUG
            fscanf(fp, "%d", &a);
#else
            scanf("%d", &a);
#endif
            input[j] = a;
        }

        int tmp = 0;
        for (size_t j = 0; j < m; j++) {
            if (0 == j) {
                tmp = input[j];
            }
            else {
                if (tmp + input[j] > input[j]) {
                    tmp += input[j];
                }
                else {
                    tmp = input[j];
                }
            }
            left_bounce[j] = tmp;
        }

        for (int j = m - 1; j >= 0; j--) {
            if (m - 1 == j) {
                tmp = input[j];
            }
            else {
                if (tmp + input[j] > input[j]) {
                    tmp += input[j];
                }
                else {
                    tmp = input[j];
                }
            }
            right_bounce[j] = tmp;

            bounce[j] += left_bounce[j] + right_bounce[j] - input[j];

            if (n - 1 == i) {
                if (m - 1 == j) {
                    max = bounce[j];
                }
                else {
                    if (bounce[j] > max) {
                        max = bounce[j];
                    }
                }
            }
        }
    }

    printf("%d\n", max);

#if DEBUG
    fclose(fp);
#endif

    return 0;
}
<|endoftext|>


<commit_before>#include <clpeak.h>

#define MSTRINGIFY(...) #__VA_ARGS__

static const char *stringifiedKernels =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_dp_kernels.cl"
#include "compute_integer_kernels.cl"
;

static const char *stringifiedKernelsNoInt =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_dp_kernels.cl"
;

static const char *helpStr =
"\n clpeak [OPTIONS]"
"\n"
"\n OPTIONS:"
"\n  -p, --platform num          choose platform (num starts with 0)"
"\n  -d, --device num            choose device   (num starts with 0)"
"\n  --use-event-timer           time using cl events instead of std chrono timer"
"\n                              hide driver latencies [default: No]"
"\n  --global-bandwidth          selectively run global bandwidth test"
"\n  --compute-sp                selectively run single precision compute test"
"\n  --compute-dp                selectively run double precision compute test"
"\n  --compute-integer           selectively run integer compute test"
"\n  --transfer-bandwidth        selectively run transfer bandwidth test"
"\n  --kernel-latency            selectively run kernel latency test"
"\n  --all-tests                 run all above tests [default]"
"\n  -h, --help                  display help message"
"\n"
;

clPeak::clPeak():forcePlatform(false),forceDevice(false), specifiedPlatform(-1), specifiedDevice(-1), useEventTimer(false),
       isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true), isTransferBW(true), isKernelLatency(true)
{
}

int clPeak::parseArgs(int argc, char **argv)
{
    bool forcedTests = false;

    for(int i=1; i<argc; i++)
    {
        if((strcmp(argv[i], "-h") == 0) || (strcmp(argv[i], "--help") == 0))
        {
            cout << helpStr << endl;
            exit(0);
        } else
        if((strcmp(argv[i], "-p") == 0) || (strcmp(argv[i], "--platform") == 0))
        {
            if((i+1) < argc)
            {
                forcePlatform = true;
                specifiedPlatform = atoi(argv[i+1]);
                i++;
            }
        } else
        if((strcmp(argv[i], "-d") == 0) || (strcmp(argv[i], "--device") == 0))
        {
            if((i+1) < argc)
            {
                forceDevice = true;
                specifiedDevice = atoi(argv[i+1]);
                i++;
            }
        } else
        if(strcmp(argv[i], "--use-event-timer") == 0)
        {
            useEventTimer = true;
        } else
        if((strcmp(argv[i], "--global-bandwidth") == 0)   || (strcmp(argv[i], "--compute-sp") == 0)
                || (strcmp(argv[i], "--compute-dp") == 0) || (strcmp(argv[i], "--compute-integer") == 0)
                || (strcmp(argv[i], "--transfer-bandwidth") == 0) || (strcmp(argv[i], "--kernel-latency") == 0))
        {
            // Disable all and enable only selected ones
            if(!forcedTests) {
                isGlobalBW = isComputeSP = isComputeDP = isComputeInt = isTransferBW = isKernelLatency = false;
                forcedTests = true;
            }

            if(strcmp(argv[i], "--global-bandwidth") == 0) {
                isGlobalBW = true;
            } else
            if(strcmp(argv[i], "--compute-sp") == 0) {
                isComputeSP = true;
            } else
            if(strcmp(argv[i], "--compute-dp") == 0) {
                isComputeDP = true;
            } else
            if(strcmp(argv[i], "--compute-integer") == 0) {
                isComputeInt = true;
            } else
            if(strcmp(argv[i], "--transfer-bandwidth") == 0) {
                isTransferBW = true;
            } else
            if(strcmp(argv[i], "--kernel-latency") == 0) {
                isKernelLatency = true;
            }

        } else
        if(strcmp(argv[i], "-all-tests") == 0)
        {
            isGlobalBW = isComputeSP = isComputeDP = isComputeInt = isTransferBW = isKernelLatency = true;
        } else
        {
            cout << helpStr << endl;
            exit(-1);
        }
    }
    return 0;
}

int clPeak::runAll()
{
    try
    {
        vector<cl::Platform> platforms;
        cl::Platform::get(&platforms);

        for(int p=0; p < (int)platforms.size(); p++)
        {
            if(forcePlatform && (p != specifiedPlatform))
                continue;

            cout << NEWLINE "Platform: " << platforms[p].getInfo<CL_PLATFORM_NAME>() << endl;

            cl_context_properties cps[3] = {
                    CL_CONTEXT_PLATFORM,
                    (cl_context_properties)(platforms[p])(),
                    0
                };
            cl::Context ctx(CL_DEVICE_TYPE_ALL, cps);
            vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>();

            string plaformName = platforms[p].getInfo<CL_PLATFORM_NAME>();
            bool isIntel = (plaformName.find("Intel") != std::string::npos)? true: false;

            cl::Program prog;

            // FIXME Disabling integer compute tests on intel platform
            // Kernel build is taking much much longer time
            if(isIntel) {
                cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1)));
                isComputeInt = false;
                prog = cl::Program(ctx, source);
            } else {
                cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1)));
                prog = cl::Program(ctx, source);
            }

            for(int d=0; d < (int)devices.size(); d++)
            {
                if(forceDevice && (d != specifiedDevice))
                    continue;

                device_info_t devInfo = getDeviceInfo(devices[d]);

                cout << TAB "Device: " << devInfo.deviceName << endl;
                cout << TAB TAB "Driver version  : " << devInfo.driverVersion << " (" << OS_NAME << ")" << endl;
                cout << TAB TAB "Compute units   : " << devInfo.numCUs << endl;
                cout << TAB TAB "Clock frequency : " << devInfo.maxClockFreq << " MHz" << endl;

                try {
                    vector<cl::Device> dev = {devices[d]};
                    prog.build(dev, BUILD_OPTIONS);
                }
                catch (cl::Error error)
                {
                    cerr << TAB TAB "Build Log: " << prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[d]) << endl;
                    cout << NEWLINE;
                    continue;
                }

                cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE);

                runGlobalBandwidthTest(queue, prog, devInfo);
                runComputeSP(queue, prog, devInfo);
                runComputeDP(queue, prog, devInfo);
                runComputeInteger(queue, prog, devInfo);
                runTransferBandwidthTest(queue, prog, devInfo);
                runKernelLatency(queue, prog, devInfo);

                cout << NEWLINE;
            }
        }
    }
    catch(cl::Error error)
    {
        cerr << error.what() << "( " << error.err() << " )" << endl;
        return -1;
    }

    return 0;
}

float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, int iters)
{
    float timed = 0;

    // Dummy calls
    queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
    queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
    queue.finish();

    if(useEventTimer)
    {
        for(int i=0; i<iters; i++)
        {
            cl::Event timeEvent;

            queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent);
            queue.finish();
            timed += timeInUS(timeEvent);
        }
    } else      // std timer
    {
        Timer timer;

        timer.start();
        for(int i=0; i<iters; i++)
        {
            queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
        }
        queue.finish();
        timed = timer.stopAndTime();
    }

    return (timed / iters);
}

<commit_msg>Undo per device build in previous commit<commit_after>#include <clpeak.h>

#define MSTRINGIFY(...) #__VA_ARGS__

static const char *stringifiedKernels =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_dp_kernels.cl"
#include "compute_integer_kernels.cl"
;

static const char *stringifiedKernelsNoInt =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_dp_kernels.cl"
;

static const char *helpStr =
"\n clpeak [OPTIONS]"
"\n"
"\n OPTIONS:"
"\n  -p, --platform num          choose platform (num starts with 0)"
"\n  -d, --device num            choose device   (num starts with 0)"
"\n  --use-event-timer           time using cl events instead of std chrono timer"
"\n                              hide driver latencies [default: No]"
"\n  --global-bandwidth          selectively run global bandwidth test"
"\n  --compute-sp                selectively run single precision compute test"
"\n  --compute-dp                selectively run double precision compute test"
"\n  --compute-integer           selectively run integer compute test"
"\n  --transfer-bandwidth        selectively run transfer bandwidth test"
"\n  --kernel-latency            selectively run kernel latency test"
"\n  --all-tests                 run all above tests [default]"
"\n  -h, --help                  display help message"
"\n"
;

clPeak::clPeak():forcePlatform(false),forceDevice(false), specifiedPlatform(-1), specifiedDevice(-1), useEventTimer(false),
       isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true), isTransferBW(true), isKernelLatency(true)
{
}

int clPeak::parseArgs(int argc, char **argv)
{
    bool forcedTests = false;

    for(int i=1; i<argc; i++)
    {
        if((strcmp(argv[i], "-h") == 0) || (strcmp(argv[i], "--help") == 0))
        {
            cout << helpStr << endl;
            exit(0);
        } else
        if((strcmp(argv[i], "-p") == 0) || (strcmp(argv[i], "--platform") == 0))
        {
            if((i+1) < argc)
            {
                forcePlatform = true;
                specifiedPlatform = atoi(argv[i+1]);
                i++;
            }
        } else
        if((strcmp(argv[i], "-d") == 0) || (strcmp(argv[i], "--device") == 0))
        {
            if((i+1) < argc)
            {
                forceDevice = true;
                specifiedDevice = atoi(argv[i+1]);
                i++;
            }
        } else
        if(strcmp(argv[i], "--use-event-timer") == 0)
        {
            useEventTimer = true;
        } else
        if((strcmp(argv[i], "--global-bandwidth") == 0)   || (strcmp(argv[i], "--compute-sp") == 0)
                || (strcmp(argv[i], "--compute-dp") == 0) || (strcmp(argv[i], "--compute-integer") == 0)
                || (strcmp(argv[i], "--transfer-bandwidth") == 0) || (strcmp(argv[i], "--kernel-latency") == 0))
        {
            // Disable all and enable only selected ones
            if(!forcedTests) {
                isGlobalBW = isComputeSP = isComputeDP = isComputeInt = isTransferBW = isKernelLatency = false;
                forcedTests = true;
            }

            if(strcmp(argv[i], "--global-bandwidth") == 0) {
                isGlobalBW = true;
            } else
            if(strcmp(argv[i], "--compute-sp") == 0) {
                isComputeSP = true;
            } else
            if(strcmp(argv[i], "--compute-dp") == 0) {
                isComputeDP = true;
            } else
            if(strcmp(argv[i], "--compute-integer") == 0) {
                isComputeInt = true;
            } else
            if(strcmp(argv[i], "--transfer-bandwidth") == 0) {
                isTransferBW = true;
            } else
            if(strcmp(argv[i], "--kernel-latency") == 0) {
                isKernelLatency = true;
            }

        } else
        if(strcmp(argv[i], "-all-tests") == 0)
        {
            isGlobalBW = isComputeSP = isComputeDP = isComputeInt = isTransferBW = isKernelLatency = true;
        } else
        {
            cout << helpStr << endl;
            exit(-1);
        }
    }
    return 0;
}

int clPeak::runAll()
{
    try
    {
        vector<cl::Platform> platforms;
        cl::Platform::get(&platforms);

        for(int p=0; p < (int)platforms.size(); p++)
        {
            if(forcePlatform && (p != specifiedPlatform))
                continue;

            cout << NEWLINE "Platform: " << platforms[p].getInfo<CL_PLATFORM_NAME>() << endl;

            cl_context_properties cps[3] = {
                    CL_CONTEXT_PLATFORM,
                    (cl_context_properties)(platforms[p])(),
                    0
                };
            cl::Context ctx(CL_DEVICE_TYPE_ALL, cps);
            vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>();

            string plaformName = platforms[p].getInfo<CL_PLATFORM_NAME>();
            bool isIntel = (plaformName.find("Intel") != std::string::npos)? true: false;

            cl::Program prog;

            // FIXME Disabling integer compute tests on intel platform
            // Kernel build is taking much much longer time
            if(isIntel) {
                cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1)));
                isComputeInt = false;
                prog = cl::Program(ctx, source);
            } else {
                cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1)));
                prog = cl::Program(ctx, source);
            }

            try {
                prog.build(devices, BUILD_OPTIONS);
            }
            catch (cl::Error error)
            {
                cerr << TAB "Build Log: " << prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) << endl;
                cout << NEWLINE;
            }

            for(int d=0; d < (int)devices.size(); d++)
            {
                if(forceDevice && (d != specifiedDevice))
                    continue;

                device_info_t devInfo = getDeviceInfo(devices[d]);

                cout << TAB "Device: " << devInfo.deviceName << endl;
                cout << TAB TAB "Driver version  : " << devInfo.driverVersion << " (" << OS_NAME << ")" << endl;
                cout << TAB TAB "Compute units   : " << devInfo.numCUs << endl;
                cout << TAB TAB "Clock frequency : " << devInfo.maxClockFreq << " MHz" << endl;

                cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE);

                runGlobalBandwidthTest(queue, prog, devInfo);
                runComputeSP(queue, prog, devInfo);
                runComputeDP(queue, prog, devInfo);
                runComputeInteger(queue, prog, devInfo);
                runTransferBandwidthTest(queue, prog, devInfo);
                runKernelLatency(queue, prog, devInfo);

                cout << NEWLINE;
            }
        }
    }
    catch(cl::Error error)
    {
        cerr << error.what() << "( " << error.err() << " )" << endl;
        return -1;
    }

    return 0;
}

float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, int iters)
{
    float timed = 0;

    // Dummy calls
    queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
    queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
    queue.finish();

    if(useEventTimer)
    {
        for(int i=0; i<iters; i++)
        {
            cl::Event timeEvent;

            queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent);
            queue.finish();
            timed += timeInUS(timeEvent);
        }
    } else      // std timer
    {
        Timer timer;

        timer.start();
        for(int i=0; i<iters; i++)
        {
            queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
        }
        queue.finish();
        timed = timer.stopAndTime();
    }

    return (timed / iters);
}

<|endoftext|>