<commit_before>#include "./window.h"
#include <QOpenGLContext>
#include <QOpenGLDebugLogger>
#include <QDebug>
#include <QCoreApplication>
#include <QStateMachine>
#include <QAbstractState>
#include <QAbstractTransition>
#include <QLoggingCategory>
#include "./graphics/gl.h"
#include "./abstract_scene.h"
#include "./video_recorder.h"

QLoggingCategory openGlChan("OpenGl");

Window::Window(std::shared_ptr<AbstractScene> scene,
               std::shared_ptr<VideoRecorder> videoRecorder,
               double offlineRenderingFrameTime, QWindow *parent)
  : QQuickView(parent), scene(scene), videoRecorder(videoRecorder),
    offlineRenderingFrameTime(offlineRenderingFrameTime)
{
  setClearBeforeRendering(false);

  connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeOpenGL()));
  connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeOpenGL()));
  connect(this, &Window::sceneGraphInvalidated, this, &Window::onInvalidated,
          Qt::DirectConnection);

  connect(reinterpret_cast<QObject *>(engine()), SIGNAL(quit()), this,
          SLOT(close()));

  connect(this, SIGNAL(beforeRendering()), this, SLOT(render()),
          Qt::DirectConnection);

  auto format = createSurfaceFormat();
  setFormat(format);

  timer.start();
}

Window::~Window()
{
  disconnect(logger, &QOpenGLDebugLogger::messageLogged, this,
             &Window::onMessageLogged);
}

QSurfaceFormat Window::createSurfaceFormat()
{
  QSurfaceFormat format;
  format.setDepthBufferSize(24);
  format.setMajorVersion(4);
  format.setMinorVersion(5);
  format.setSamples(4);
  format.setOption(QSurfaceFormat::DebugContext);
  format.setSwapInterval(0);

  return format;
}

void Window::initializeOpenGL()
{
  qCInfo(openGlChan) << "initializeOpenGL";
  context = openglContext();
  bool success = context->makeCurrent(this);
  qCInfo(openGlChan) << "success: " << success;

  gl = new Graphics::Gl();
  gl->initialize(context, size());

  logger = new QOpenGLDebugLogger(context);
  connect(context, &QOpenGLContext::aboutToBeDestroyed, this,
          &Window::contextAboutToBeDestroyed, Qt::DirectConnection);

  connect(logger, &QOpenGLDebugLogger::messageLogged, this,
          &Window::onMessageLogged, Qt::DirectConnection);

  if (logger->initialize())
  {
    logger->startLogging(QOpenGLDebugLogger::SynchronousLogging);
    logger->enableMessages();
  }

  glAssert(gl->glDisable(GL_CULL_FACE));
  glAssert(gl->glDisable(GL_DEPTH_TEST));
  glAssert(gl->glDisable(GL_STENCIL_TEST));
  glAssert(gl->glDisable(GL_BLEND));
  glAssert(gl->glDepthMask(GL_FALSE));

  videoRecorder->initialize(gl);
  videoRecorder->resize(this->width(), this->height());
}

void Window::onInvalidated()
{
  qCInfo(openGlChan) << "on invalidated: delete logger";
  scene->cleanup();
  delete logger;
}

void Window::handleLazyInitialization()
{
  static bool initialized = false;
  if (!initialized)
  {
    initializeOpenGL();

    scene->setContext(context, gl);
    scene->resize(size().width(), size().height());
    scene->initialize();
    initialized = true;
  }
}

void Window::render()
{
  handleLazyInitialization();

  update();
  scene->render();

  // Use to check for missing release calls
  // resetOpenGLState();

  QQuickView::update();

  videoRecorder->captureVideoFrame();
}

void Window::resizeOpenGL()
{
  if (!gl)
    return;

  qCWarning(openGlChan) << "Resize not supported for now";
  /*
  scene->resize(width(), height());
  gl->setSize(this->size());
  */
}

void Window::update()
{
  double frameTime = timer.restart() / 1000.0;
  updateAverageFrameTime(frameTime);

  scene->update(offlineRenderingFrameTime != 0.0f ? offlineRenderingFrameTime
                                                  : frameTime);
}

void Window::toggleFullscreen()
{
  setVisibility(visibility() == QWindow::Windowed ? QWindow::FullScreen
                                                  : QWindow::Windowed);
}

void Window::contextAboutToBeDestroyed()
{
  qCInfo(openGlChan) << "Closing rendering thread";
}

void Window::updateAverageFrameTime(double frameTime)
{
  runningTime += frameTime;
  ++framesInSecond;

  if (runningTime > 1.0)
  {
    avgFrameTime = runningTime / framesInSecond;
    emit averageFrameTimeUpdated();

    framesInSecond = 0;
    runningTime = 0;
  }
}

void Window::uiFocusChanged(bool hasFocus)
{
  qCDebug(openGlChan) << "uiFocusChanged" << hasFocus;
  if (hasFocus)
    emit uiGotFocus();
  else
    emit uiLostFocus();
}

void Window::onMessageLogged(QOpenGLDebugMessage message)
{
  // Ignore buffer detailed info which cannot be fixed
  if (message.id() == 131185)
    return;

  // Ignore buffer performance warning
  if (message.id() == 131186)
    return;

  // Ignore generic vertex attribute array 1 uses a pointer with a small value
  if (message.id() == 131076)
    return;

  switch (message.severity())
  {
  case QOpenGLDebugMessage::Severity::NotificationSeverity:
    qCInfo(openGlChan) << message;
    break;

  case QOpenGLDebugMessage::Severity::LowSeverity:
    qCDebug(openGlChan) << message;
    break;
  case QOpenGLDebugMessage::Severity::MediumSeverity:
    qCWarning(openGlChan) << message;
    break;
  case QOpenGLDebugMessage::Severity::HighSeverity:
    qCCritical(openGlChan) << message;
    throw std::runtime_error(message.message().toStdString());
    break;
  default:
    return;
  }
}

<commit_msg>Add stencial buffer also to Qt surface.<commit_after>#include "./window.h"
#include <QOpenGLContext>
#include <QOpenGLDebugLogger>
#include <QDebug>
#include <QCoreApplication>
#include <QStateMachine>
#include <QAbstractState>
#include <QAbstractTransition>
#include <QLoggingCategory>
#include "./graphics/gl.h"
#include "./abstract_scene.h"
#include "./video_recorder.h"

QLoggingCategory openGlChan("OpenGl");

Window::Window(std::shared_ptr<AbstractScene> scene,
               std::shared_ptr<VideoRecorder> videoRecorder,
               double offlineRenderingFrameTime, QWindow *parent)
  : QQuickView(parent), scene(scene), videoRecorder(videoRecorder),
    offlineRenderingFrameTime(offlineRenderingFrameTime)
{
  setClearBeforeRendering(false);

  connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeOpenGL()));
  connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeOpenGL()));
  connect(this, &Window::sceneGraphInvalidated, this, &Window::onInvalidated,
          Qt::DirectConnection);

  connect(reinterpret_cast<QObject *>(engine()), SIGNAL(quit()), this,
          SLOT(close()));

  connect(this, SIGNAL(beforeRendering()), this, SLOT(render()),
          Qt::DirectConnection);

  auto format = createSurfaceFormat();
  setFormat(format);

  timer.start();
}

Window::~Window()
{
  disconnect(logger, &QOpenGLDebugLogger::messageLogged, this,
             &Window::onMessageLogged);
}

QSurfaceFormat Window::createSurfaceFormat()
{
  QSurfaceFormat format;
  format.setDepthBufferSize(24);
  format.setStencilBufferSize(8);
  format.setMajorVersion(4);
  format.setMinorVersion(5);
  format.setSamples(4);
  format.setOption(QSurfaceFormat::DebugContext);
  format.setSwapInterval(0);

  return format;
}

void Window::initializeOpenGL()
{
  qCInfo(openGlChan) << "initializeOpenGL";
  context = openglContext();
  bool success = context->makeCurrent(this);
  qCInfo(openGlChan) << "success: " << success;

  gl = new Graphics::Gl();
  gl->initialize(context, size());

  logger = new QOpenGLDebugLogger(context);
  connect(context, &QOpenGLContext::aboutToBeDestroyed, this,
          &Window::contextAboutToBeDestroyed, Qt::DirectConnection);

  connect(logger, &QOpenGLDebugLogger::messageLogged, this,
          &Window::onMessageLogged, Qt::DirectConnection);

  if (logger->initialize())
  {
    logger->startLogging(QOpenGLDebugLogger::SynchronousLogging);
    logger->enableMessages();
  }

  glAssert(gl->glDisable(GL_CULL_FACE));
  glAssert(gl->glDisable(GL_DEPTH_TEST));
  glAssert(gl->glDisable(GL_STENCIL_TEST));
  glAssert(gl->glDisable(GL_BLEND));
  glAssert(gl->glDepthMask(GL_FALSE));

  videoRecorder->initialize(gl);
  videoRecorder->resize(this->width(), this->height());
}

void Window::onInvalidated()
{
  qCInfo(openGlChan) << "on invalidated: delete logger";
  scene->cleanup();
  delete logger;
}

void Window::handleLazyInitialization()
{
  static bool initialized = false;
  if (!initialized)
  {
    initializeOpenGL();

    scene->setContext(context, gl);
    scene->resize(size().width(), size().height());
    scene->initialize();
    initialized = true;
  }
}

void Window::render()
{
  handleLazyInitialization();

  update();
  scene->render();

  // Use to check for missing release calls
  // resetOpenGLState();

  QQuickView::update();

  videoRecorder->captureVideoFrame();
}

void Window::resizeOpenGL()
{
  if (!gl)
    return;

  qCWarning(openGlChan) << "Resize not supported for now";
  /*
  scene->resize(width(), height());
  gl->setSize(this->size());
  */
}

void Window::update()
{
  double frameTime = timer.restart() / 1000.0;
  updateAverageFrameTime(frameTime);

  scene->update(offlineRenderingFrameTime != 0.0f ? offlineRenderingFrameTime
                                                  : frameTime);
}

void Window::toggleFullscreen()
{
  setVisibility(visibility() == QWindow::Windowed ? QWindow::FullScreen
                                                  : QWindow::Windowed);
}

void Window::contextAboutToBeDestroyed()
{
  qCInfo(openGlChan) << "Closing rendering thread";
}

void Window::updateAverageFrameTime(double frameTime)
{
  runningTime += frameTime;
  ++framesInSecond;

  if (runningTime > 1.0)
  {
    avgFrameTime = runningTime / framesInSecond;
    emit averageFrameTimeUpdated();

    framesInSecond = 0;
    runningTime = 0;
  }
}

void Window::uiFocusChanged(bool hasFocus)
{
  qCDebug(openGlChan) << "uiFocusChanged" << hasFocus;
  if (hasFocus)
    emit uiGotFocus();
  else
    emit uiLostFocus();
}

void Window::onMessageLogged(QOpenGLDebugMessage message)
{
  // Ignore buffer detailed info which cannot be fixed
  if (message.id() == 131185)
    return;

  // Ignore buffer performance warning
  if (message.id() == 131186)
    return;

  // Ignore generic vertex attribute array 1 uses a pointer with a small value
  if (message.id() == 131076)
    return;

  switch (message.severity())
  {
  case QOpenGLDebugMessage::Severity::NotificationSeverity:
    qCInfo(openGlChan) << message;
    break;

  case QOpenGLDebugMessage::Severity::LowSeverity:
    qCDebug(openGlChan) << message;
    break;
  case QOpenGLDebugMessage::Severity::MediumSeverity:
    qCWarning(openGlChan) << message;
    break;
  case QOpenGLDebugMessage::Severity::HighSeverity:
    qCCritical(openGlChan) << message;
    throw std::runtime_error(message.message().toStdString());
    break;
  default:
    return;
  }
}

<|endoftext|>


<commit_before>
// The files containing the tree of child classes of |Body| must be included in
// the order of inheritance to avoid circular dependencies.
#ifndef PRINCIPIA_PHYSICS_ROTATING_BODY_HPP_
#include "physics/rotating_body.hpp"
#endif  // PRINCIPIA_PHYSICS_ROTATING_BODY_HPP_
#ifndef PRINCIPIA_PHYSICS_OBLATE_BODY_HPP_
#define PRINCIPIA_PHYSICS_OBLATE_BODY_HPP_

#include <optional>
#include <vector>

#include "geometry/grassmann.hpp"
#include "numerics/fixed_arrays.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"

namespace principia {
namespace physics {
namespace internal_oblate_body {

using base::not_null;
using geometry::Vector;
using numerics::FixedLowerTriangularMatrix;
using quantities::Degree2SphericalHarmonicCoefficient;
using quantities::Degree3SphericalHarmonicCoefficient;
using quantities::GravitationalParameter;
using quantities::Length;
using quantities::Quotient;

// TODO(phl): c22, s22 and j3 in this class are temporary until we get the
// general geopotential model to work at least as well as c22/s22/j3.
template<typename Frame>
class OblateBody : public RotatingBody<Frame> {
  static_assert(Frame::is_inertial, "Frame must be inertial");

 public:
  static constexpr int max_geopotential_degree = 10;
  using GeopotentialCoefficients =
      FixedLowerTriangularMatrix<double, max_geopotential_degree + 1>;

  class PHYSICS_DLL Parameters final {
   public:
    Parameters(double j2,
               Length const& reference_radius);

    static Parameters ReadFromMessage(
        serialization::OblateBody::Geopotential const& message,
        Length const& reference_radius);

    void WriteToMessage(
        not_null<serialization::OblateBody::Geopotential*> message) const;

   private:
    // Only for use when building from a geopotential.
    explicit Parameters(Length const& reference_radius);

    Length reference_radius_;

    double j2_;
    Quotient<Degree2SphericalHarmonicCoefficient, GravitationalParameter>
        j2_over_μ_;
    GeopotentialCoefficients cos_;
    GeopotentialCoefficients sin_;
    int degree_;

    template<typename F>
    friend class OblateBody;
  };

  OblateBody(MassiveBody::Parameters const& massive_body_parameters,
             typename RotatingBody<Frame>::Parameters const&
                 rotating_body_parameters,
             Parameters const& parameters);

  // These parameters are unnormalized.
  double j2() const;
  Quotient<Degree2SphericalHarmonicCoefficient,
           GravitationalParameter> const& j2_over_μ() const;

  // These parameters are normalized.
  GeopotentialCoefficients const& cos() const;
  GeopotentialCoefficients const& sin() const;
  int geopotential_degree() const;

  Length const& reference_radius() const;

  // Returns false.
  bool is_massless() const override;

  // Returns true.
  bool is_oblate() const override;

  void WriteToMessage(not_null<serialization::Body*> message) const override;

  void WriteToMessage(
      not_null<serialization::MassiveBody*> message) const override;

  static not_null<std::unique_ptr<OblateBody<Frame>>> ReadFromMessage(
      serialization::OblateBody const& message,
      MassiveBody::Parameters const& massive_body_parameters,
      typename RotatingBody<Frame>::Parameters const& rotating_body_parameters);

 private:
  Parameters parameters_;
};

}  // namespace internal_oblate_body

using internal_oblate_body::OblateBody;

}  // namespace physics
}  // namespace principia

#if !PHYSICS_DLL_IMPORT
#include "physics/oblate_body_body.hpp"
#endif

#endif  // PRINCIPIA_PHYSICS_OBLATE_BODY_HPP_
<commit_msg>Cleanup.<commit_after>
// The files containing the tree of child classes of |Body| must be included in
// the order of inheritance to avoid circular dependencies.
#ifndef PRINCIPIA_PHYSICS_ROTATING_BODY_HPP_
#include "physics/rotating_body.hpp"
#endif  // PRINCIPIA_PHYSICS_ROTATING_BODY_HPP_
#ifndef PRINCIPIA_PHYSICS_OBLATE_BODY_HPP_
#define PRINCIPIA_PHYSICS_OBLATE_BODY_HPP_

#include <vector>

#include "geometry/grassmann.hpp"
#include "numerics/fixed_arrays.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/quantities.hpp"

namespace principia {
namespace physics {
namespace internal_oblate_body {

using base::not_null;
using geometry::Vector;
using numerics::FixedLowerTriangularMatrix;
using quantities::Degree2SphericalHarmonicCoefficient;
using quantities::Degree3SphericalHarmonicCoefficient;
using quantities::GravitationalParameter;
using quantities::Length;
using quantities::Quotient;

template<typename Frame>
class OblateBody : public RotatingBody<Frame> {
  static_assert(Frame::is_inertial, "Frame must be inertial");

 public:
  static constexpr int max_geopotential_degree = 10;
  using GeopotentialCoefficients =
      FixedLowerTriangularMatrix<double, max_geopotential_degree + 1>;

  class PHYSICS_DLL Parameters final {
   public:
    Parameters(double j2,
               Length const& reference_radius);

    static Parameters ReadFromMessage(
        serialization::OblateBody::Geopotential const& message,
        Length const& reference_radius);

    void WriteToMessage(
        not_null<serialization::OblateBody::Geopotential*> message) const;

   private:
    // Only for use when building from a geopotential.
    explicit Parameters(Length const& reference_radius);

    Length reference_radius_;

    double j2_;
    Quotient<Degree2SphericalHarmonicCoefficient, GravitationalParameter>
        j2_over_μ_;
    GeopotentialCoefficients cos_;
    GeopotentialCoefficients sin_;
    int degree_;

    template<typename F>
    friend class OblateBody;
  };

  OblateBody(MassiveBody::Parameters const& massive_body_parameters,
             typename RotatingBody<Frame>::Parameters const&
                 rotating_body_parameters,
             Parameters const& parameters);

  // These parameters are unnormalized.
  double j2() const;
  Quotient<Degree2SphericalHarmonicCoefficient,
           GravitationalParameter> const& j2_over_μ() const;

  // These parameters are normalized.
  GeopotentialCoefficients const& cos() const;
  GeopotentialCoefficients const& sin() const;
  int geopotential_degree() const;

  Length const& reference_radius() const;

  // Returns false.
  bool is_massless() const override;

  // Returns true.
  bool is_oblate() const override;

  void WriteToMessage(not_null<serialization::Body*> message) const override;

  void WriteToMessage(
      not_null<serialization::MassiveBody*> message) const override;

  static not_null<std::unique_ptr<OblateBody<Frame>>> ReadFromMessage(
      serialization::OblateBody const& message,
      MassiveBody::Parameters const& massive_body_parameters,
      typename RotatingBody<Frame>::Parameters const& rotating_body_parameters);

 private:
  Parameters parameters_;
};

}  // namespace internal_oblate_body

using internal_oblate_body::OblateBody;

}  // namespace physics
}  // namespace principia

#if !PHYSICS_DLL_IMPORT
#include "physics/oblate_body_body.hpp"
#endif

#endif  // PRINCIPIA_PHYSICS_OBLATE_BODY_HPP_
<|endoftext|>


<commit_before>#include <fstream>
#include "picpac.h"
#include "picpac-cv.h"
#include "picpac-util.h"

using namespace std;
using namespace picpac;

static size_t constexpr WIDTH = 32;
static size_t constexpr HEIGHT = 32;
static size_t constexpr AREA = WIDTH * HEIGHT;
static size_t constexpr CHANNELS = 3;
static size_t constexpr DIM = WIDTH * HEIGHT * CHANNELS;

void load (string const &path, FileWriter &writer) {
    ImageEncoder encoder("raw");
    ifstream is(path.c_str(), ios::binary);
    size_t sz = 1 + DIM;
    is.seekg(0, ios::end);
    size_t total = is.tellg();
    is.seekg(0, ios::beg);
    BOOST_VERIFY(total % sz == 0);
    total /= sz;
    //cv::Mat image(HEIGHT, WIDTH,
    vector<cv::Mat> channels(3);
    for (auto &m: channels) {
        m.create(HEIGHT, WIDTH, CV_8UC1);
    }
    cv::Mat image;
    string buf;
    for (unsigned i = 0; i < total; ++i) {
        uint8_t label;
        is.read((char *)&label, sizeof(label));
        is.read(channels[2].ptr<char>(0), DIM);
        is.read(channels[1].ptr<char>(0), DIM);
        is.read(channels[0].ptr<char>(0), DIM);
        cv::merge(channels, image);
        encoder.encode(image, &buf);
        picpac::Record rec((int)label, buf);
        writer.append(rec);
    }
}

int main(int argc, char **argv) {
    google::InitGoogleLogging(argv[0]);
    {
        picpac::FileWriter writer("train.db");
        load("cifar-10-batches-bin/data_batch_1.bin", writer);
        load("cifar-10-batches-bin/data_batch_2.bin", writer);
        load("cifar-10-batches-bin/data_batch_3.bin", writer);
        load("cifar-10-batches-bin/data_batch_4.bin", writer);
        load("cifar-10-batches-bin/data_batch_5.bin", writer);
    }
    {
        picpac::FileWriter writer("test.db");
        load("cifar-10-batches-bin/test_batch.bin", writer);
    }

    return 0;
}

<commit_msg>fix size error<commit_after>#include <fstream>
#include "picpac.h"
#include "picpac-cv.h"
#include "picpac-util.h"

using namespace std;
using namespace picpac;

static size_t constexpr WIDTH = 32;
static size_t constexpr HEIGHT = 32;
static size_t constexpr AREA = WIDTH * HEIGHT;
static size_t constexpr CHANNELS = 3;
static size_t constexpr DIM = WIDTH * HEIGHT * CHANNELS;

void load (string const &path, FileWriter &writer) {
    ImageEncoder encoder("raw");
    ifstream is(path.c_str(), ios::binary);
    size_t sz = 1 + DIM;
    is.seekg(0, ios::end);
    size_t total = is.tellg();
    is.seekg(0, ios::beg);
    BOOST_VERIFY(total % sz == 0);
    total /= sz;
    //cv::Mat image(HEIGHT, WIDTH,
    vector<cv::Mat> channels(3);
    for (auto &m: channels) {
        m.create(HEIGHT, WIDTH, CV_8UC1);
    }
    cv::Mat image;
    string buf;
    for (unsigned i = 0; i < total; ++i) {
        uint8_t label;
        is.read((char *)&label, sizeof(label));
        is.read(channels[2].ptr<char>(0), AREA);
        is.read(channels[1].ptr<char>(0), AREA);
        is.read(channels[0].ptr<char>(0), AREA);
        CHECK(is);
        cv::merge(channels, image);
        encoder.encode(image, &buf);
        picpac::Record rec((int)label, buf);
        writer.append(rec);
    }
}

int main(int argc, char **argv) {
    google::InitGoogleLogging(argv[0]);
    {
        picpac::FileWriter writer("train.db");
        load("cifar-10-batches-bin/data_batch_1.bin", writer);
        load("cifar-10-batches-bin/data_batch_2.bin", writer);
        load("cifar-10-batches-bin/data_batch_3.bin", writer);
        load("cifar-10-batches-bin/data_batch_4.bin", writer);
        load("cifar-10-batches-bin/data_batch_5.bin", writer);
    }
    {
        picpac::FileWriter writer("test.db");
        load("cifar-10-batches-bin/test_batch.bin", writer);
    }

    return 0;
}

<|endoftext|>


<commit_before>//===-- MipsMachineFunctionInfo.cpp - Private data used for Mips ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "MipsMachineFunction.h"
#include "MCTargetDesc/MipsBaseInfo.h"
#include "MipsInstrInfo.h"
#include "MipsSubtarget.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

static cl::opt<bool>
FixGlobalBaseReg("mips-fix-global-base-reg", cl::Hidden, cl::init(true),
                 cl::desc("Always use $gp as the global base register."));

// class MipsCallEntry.
MipsCallEntry::MipsCallEntry(const StringRef &N) {
#ifndef NDEBUG
  Name = N;
  Val = nullptr;
#endif
}

MipsCallEntry::MipsCallEntry(const GlobalValue *V) {
#ifndef NDEBUG
  Val = V;
#endif
}

bool MipsCallEntry::isConstant(const MachineFrameInfo *) const {
  return false;
}

bool MipsCallEntry::isAliased(const MachineFrameInfo *) const {
  return false;
}

bool MipsCallEntry::mayAlias(const MachineFrameInfo *) const {
  return false;
}

void MipsCallEntry::printCustom(raw_ostream &O) const {
  O << "MipsCallEntry: ";
#ifndef NDEBUG
  if (Val)
    O << Val->getName();
  else
    O << Name;
#endif
}

MipsFunctionInfo::~MipsFunctionInfo() {
  for (StringMap<const MipsCallEntry *>::iterator
       I = ExternalCallEntries.begin(), E = ExternalCallEntries.end(); I != E;
       ++I)
    delete I->getValue();

  for (ValueMap<const GlobalValue *, const MipsCallEntry *>::iterator
       I = GlobalCallEntries.begin(), E = GlobalCallEntries.end(); I != E; ++I)
    delete I->second;
}

bool MipsFunctionInfo::globalBaseRegSet() const {
  return GlobalBaseReg;
}

unsigned MipsFunctionInfo::getGlobalBaseReg() {
  // Return if it has already been initialized.
  if (GlobalBaseReg)
    return GlobalBaseReg;

  const MipsSubtarget &ST = MF.getTarget().getSubtarget<MipsSubtarget>();

  const TargetRegisterClass *RC;
  if (ST.inMips16Mode())
    RC=(const TargetRegisterClass*)&Mips::CPU16RegsRegClass;
  else
    RC = ST.isABI_N64() ?
      (const TargetRegisterClass*)&Mips::GPR64RegClass :
      (const TargetRegisterClass*)&Mips::GPR32RegClass;
  return GlobalBaseReg = MF.getRegInfo().createVirtualRegister(RC);
}

bool MipsFunctionInfo::mips16SPAliasRegSet() const {
  return Mips16SPAliasReg;
}
unsigned MipsFunctionInfo::getMips16SPAliasReg() {
  // Return if it has already been initialized.
  if (Mips16SPAliasReg)
    return Mips16SPAliasReg;

  const TargetRegisterClass *RC;
  RC=(const TargetRegisterClass*)&Mips::CPU16RegsRegClass;
  return Mips16SPAliasReg = MF.getRegInfo().createVirtualRegister(RC);
}

void MipsFunctionInfo::createEhDataRegsFI() {
  for (int I = 0; I < 4; ++I) {
    const MipsSubtarget &ST = MF.getTarget().getSubtarget<MipsSubtarget>();
    const TargetRegisterClass *RC = ST.isABI_N64() ?
        &Mips::GPR64RegClass : &Mips::GPR32RegClass;

    EhDataRegFI[I] = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
        RC->getAlignment(), false);
  }
}

bool MipsFunctionInfo::isEhDataRegFI(int FI) const {
  return CallsEhReturn && (FI == EhDataRegFI[0] || FI == EhDataRegFI[1]
                        || FI == EhDataRegFI[2] || FI == EhDataRegFI[3]);
}

MachinePointerInfo MipsFunctionInfo::callPtrInfo(const StringRef &Name) {
  const MipsCallEntry *&E = ExternalCallEntries[Name];

  if (!E)
    E = new MipsCallEntry(Name);

  return MachinePointerInfo(E);
}

MachinePointerInfo MipsFunctionInfo::callPtrInfo(const GlobalValue *Val) {
  const MipsCallEntry *&E = GlobalCallEntries[Val];

  if (!E)
    E = new MipsCallEntry(Val);

  return MachinePointerInfo(E);
}

void MipsFunctionInfo::anchor() { }
<commit_msg>Use range loop.<commit_after>//===-- MipsMachineFunctionInfo.cpp - Private data used for Mips ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "MipsMachineFunction.h"
#include "MCTargetDesc/MipsBaseInfo.h"
#include "MipsInstrInfo.h"
#include "MipsSubtarget.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

static cl::opt<bool>
FixGlobalBaseReg("mips-fix-global-base-reg", cl::Hidden, cl::init(true),
                 cl::desc("Always use $gp as the global base register."));

// class MipsCallEntry.
MipsCallEntry::MipsCallEntry(const StringRef &N) {
#ifndef NDEBUG
  Name = N;
  Val = nullptr;
#endif
}

MipsCallEntry::MipsCallEntry(const GlobalValue *V) {
#ifndef NDEBUG
  Val = V;
#endif
}

bool MipsCallEntry::isConstant(const MachineFrameInfo *) const {
  return false;
}

bool MipsCallEntry::isAliased(const MachineFrameInfo *) const {
  return false;
}

bool MipsCallEntry::mayAlias(const MachineFrameInfo *) const {
  return false;
}

void MipsCallEntry::printCustom(raw_ostream &O) const {
  O << "MipsCallEntry: ";
#ifndef NDEBUG
  if (Val)
    O << Val->getName();
  else
    O << Name;
#endif
}

MipsFunctionInfo::~MipsFunctionInfo() {
  for (StringMap<const MipsCallEntry *>::iterator
       I = ExternalCallEntries.begin(), E = ExternalCallEntries.end(); I != E;
       ++I)
    delete I->getValue();

  for (const auto &Entry : GlobalCallEntries)
    delete Entry.second;
}

bool MipsFunctionInfo::globalBaseRegSet() const {
  return GlobalBaseReg;
}

unsigned MipsFunctionInfo::getGlobalBaseReg() {
  // Return if it has already been initialized.
  if (GlobalBaseReg)
    return GlobalBaseReg;

  const MipsSubtarget &ST = MF.getTarget().getSubtarget<MipsSubtarget>();

  const TargetRegisterClass *RC;
  if (ST.inMips16Mode())
    RC=(const TargetRegisterClass*)&Mips::CPU16RegsRegClass;
  else
    RC = ST.isABI_N64() ?
      (const TargetRegisterClass*)&Mips::GPR64RegClass :
      (const TargetRegisterClass*)&Mips::GPR32RegClass;
  return GlobalBaseReg = MF.getRegInfo().createVirtualRegister(RC);
}

bool MipsFunctionInfo::mips16SPAliasRegSet() const {
  return Mips16SPAliasReg;
}
unsigned MipsFunctionInfo::getMips16SPAliasReg() {
  // Return if it has already been initialized.
  if (Mips16SPAliasReg)
    return Mips16SPAliasReg;

  const TargetRegisterClass *RC;
  RC=(const TargetRegisterClass*)&Mips::CPU16RegsRegClass;
  return Mips16SPAliasReg = MF.getRegInfo().createVirtualRegister(RC);
}

void MipsFunctionInfo::createEhDataRegsFI() {
  for (int I = 0; I < 4; ++I) {
    const MipsSubtarget &ST = MF.getTarget().getSubtarget<MipsSubtarget>();
    const TargetRegisterClass *RC = ST.isABI_N64() ?
        &Mips::GPR64RegClass : &Mips::GPR32RegClass;

    EhDataRegFI[I] = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
        RC->getAlignment(), false);
  }
}

bool MipsFunctionInfo::isEhDataRegFI(int FI) const {
  return CallsEhReturn && (FI == EhDataRegFI[0] || FI == EhDataRegFI[1]
                        || FI == EhDataRegFI[2] || FI == EhDataRegFI[3]);
}

MachinePointerInfo MipsFunctionInfo::callPtrInfo(const StringRef &Name) {
  const MipsCallEntry *&E = ExternalCallEntries[Name];

  if (!E)
    E = new MipsCallEntry(Name);

  return MachinePointerInfo(E);
}

MachinePointerInfo MipsFunctionInfo::callPtrInfo(const GlobalValue *Val) {
  const MipsCallEntry *&E = GlobalCallEntries[Val];

  if (!E)
    E = new MipsCallEntry(Val);

  return MachinePointerInfo(E);
}

void MipsFunctionInfo::anchor() { }
<|endoftext|>


<commit_before>//===-- CondPropagate.cpp - Propagate Conditional Expressions -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass propagates information about conditional expressions through the
// program, allowing it to eliminate conditional branches in some cases.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "condprop"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Pass.h"
#include "llvm/Type.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Streams.h"
using namespace llvm;

STATISTIC(NumBrThread, "Number of CFG edges threaded through branches");
STATISTIC(NumSwThread, "Number of CFG edges threaded through switches");

namespace {
  struct VISIBILITY_HIDDEN CondProp : public FunctionPass {
    static char ID; // Pass identification, replacement for typeid
    CondProp() : FunctionPass(&ID) {}

    virtual bool runOnFunction(Function &F);

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.addRequiredID(BreakCriticalEdgesID);
      //AU.addRequired<DominanceFrontier>();
    }

  private:
    bool MadeChange;
    SmallVector<BasicBlock *, 4> DeadBlocks;
    void SimplifyBlock(BasicBlock *BB);
    void SimplifyPredecessors(BranchInst *BI);
    void SimplifyPredecessors(SwitchInst *SI);
    void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
  };
}

char CondProp::ID = 0;
static RegisterPass<CondProp> X("condprop", "Conditional Propagation");

FunctionPass *llvm::createCondPropagationPass() {
  return new CondProp();
}

bool CondProp::runOnFunction(Function &F) {
  bool EverMadeChange = false;
  DeadBlocks.clear();

  // While we are simplifying blocks, keep iterating.
  do {
    MadeChange = false;
    for (Function::iterator BB = F.begin(), E = F.end(); BB != E;)
      SimplifyBlock(BB++);
    EverMadeChange = EverMadeChange || MadeChange;
  } while (MadeChange);

  if (EverMadeChange) {
    while (!DeadBlocks.empty()) {
      BasicBlock *BB = DeadBlocks.back(); DeadBlocks.pop_back();
      DeleteDeadBlock(BB);
    }
  }
  return EverMadeChange;
}

void CondProp::SimplifyBlock(BasicBlock *BB) {
  if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
    // If this is a conditional branch based on a phi node that is defined in
    // this block, see if we can simplify predecessors of this block.
    if (BI->isConditional() && isa<PHINode>(BI->getCondition()) &&
        cast<PHINode>(BI->getCondition())->getParent() == BB)
      SimplifyPredecessors(BI);

  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
    if (isa<PHINode>(SI->getCondition()) &&
        cast<PHINode>(SI->getCondition())->getParent() == BB)
      SimplifyPredecessors(SI);
  }

  // If possible, simplify the terminator of this block.
  if (ConstantFoldTerminator(BB))
    MadeChange = true;

  // If this block ends with an unconditional branch and the only successor has
  // only this block as a predecessor, merge the two blocks together.
  if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
    if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor() &&
        BB != BI->getSuccessor(0)) {
      BasicBlock *Succ = BI->getSuccessor(0);

      // If Succ has any PHI nodes, they are all single-entry PHI's.  Eliminate
      // them.
      FoldSingleEntryPHINodes(Succ);

      // Remove BI.
      BI->eraseFromParent();

      // Move over all of the instructions.
      BB->getInstList().splice(BB->end(), Succ->getInstList());

      // Any phi nodes that had entries for Succ now have entries from BB.
      Succ->replaceAllUsesWith(BB);

      // Succ is now dead, but we cannot delete it without potentially
      // invalidating iterators elsewhere.  Just insert an unreachable
      // instruction in it and delete this block later on.
      new UnreachableInst(Succ);
      DeadBlocks.push_back(Succ);
      MadeChange = true;
    }
}

// SimplifyPredecessors(branches) - We know that BI is a conditional branch
// based on a PHI node defined in this block.  If the phi node contains constant
// operands, then the blocks corresponding to those operands can be modified to
// jump directly to the destination instead of going through this block.
void CondProp::SimplifyPredecessors(BranchInst *BI) {
  // TODO: We currently only handle the most trival case, where the PHI node has
  // one use (the branch), and is the only instruction besides the branch and dbg
  // intrinsics in the block.
  PHINode *PN = cast<PHINode>(BI->getCondition());

  if (PN->getNumIncomingValues() == 1) {
    // Eliminate single-entry PHI nodes.
    FoldSingleEntryPHINodes(PN->getParent());
    return;
  }

  if (!PN->hasOneUse()) return;

  BasicBlock *BB = BI->getParent();
  if (&*BB->begin() != PN)
    return;
  BasicBlock::iterator BBI = BB->begin();
  BasicBlock::iterator BBE = BB->end();
  while (BBI != BBE && isa<DbgInfoIntrinsic>(++BBI));
  if (&*BBI != BI)
    return;

  // Ok, we have this really simple case, walk the PHI operands, looking for
  // constants.  Walk from the end to remove operands from the end when
  // possible, and to avoid invalidating "i".
  for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
    if (ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
      // If we have a constant, forward the edge from its current to its
      // ultimate destination.
      RevectorBlockTo(PN->getIncomingBlock(i-1),
                      BI->getSuccessor(CB->isZero()));
      ++NumBrThread;

      // If there were two predecessors before this simplification, or if the
      // PHI node contained all the same value except for the one we just
      // substituted, the PHI node may be deleted.  Don't iterate through it the
      // last time.
      if (BI->getCondition() != PN) return;
    }
}

// SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
// defined in this block.  If the phi node contains constant operands, then the
// blocks corresponding to those operands can be modified to jump directly to
// the destination instead of going through this block.
void CondProp::SimplifyPredecessors(SwitchInst *SI) {
  // TODO: We currently only handle the most trival case, where the PHI node has
  // one use (the branch), and is the only instruction besides the branch and
  // dbg intrinsics in the block.
  PHINode *PN = cast<PHINode>(SI->getCondition());
  if (!PN->hasOneUse()) return;

  BasicBlock *BB = SI->getParent();
  if (&*BB->begin() != PN)
    return;
  BasicBlock::iterator BBI = BB->begin();
  BasicBlock::iterator BBE = BB->end();
  while (BBI != BBE && isa<DbgInfoIntrinsic>(++BBI));
  if (&*BBI != SI)
    return;

  bool RemovedPreds = false;

  // Ok, we have this really simple case, walk the PHI operands, looking for
  // constants.  Walk from the end to remove operands from the end when
  // possible, and to avoid invalidating "i".
  for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
    if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
      // If we have a constant, forward the edge from its current to its
      // ultimate destination.
      unsigned DestCase = SI->findCaseValue(CI);
      RevectorBlockTo(PN->getIncomingBlock(i-1),
                      SI->getSuccessor(DestCase));
      ++NumSwThread;
      RemovedPreds = true;

      // If there were two predecessors before this simplification, or if the
      // PHI node contained all the same value except for the one we just
      // substituted, the PHI node may be deleted.  Don't iterate through it the
      // last time.
      if (SI->getCondition() != PN) return;
    }
}

// RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
// the ToBB block, which is one of the successors of its current successor.
void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
  BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
  assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");

  // Get the old block we are threading through.
  BasicBlock *OldSucc = FromBr->getSuccessor(0);

  // OldSucc had multiple successors. If ToBB has multiple predecessors, then
  // the edge between them would be critical, which we already took care of.
  // If ToBB has single operand PHI node then take care of it here.
  FoldSingleEntryPHINodes(ToBB);

  // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
  OldSucc->removePredecessor(FromBB);

  // Change FromBr to branch to the new destination.
  FromBr->setSuccessor(0, ToBB);

  MadeChange = true;
}
<commit_msg>Insert space to avoid warning and make code more readable.<commit_after>//===-- CondPropagate.cpp - Propagate Conditional Expressions -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass propagates information about conditional expressions through the
// program, allowing it to eliminate conditional branches in some cases.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "condprop"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Pass.h"
#include "llvm/Type.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Streams.h"
using namespace llvm;

STATISTIC(NumBrThread, "Number of CFG edges threaded through branches");
STATISTIC(NumSwThread, "Number of CFG edges threaded through switches");

namespace {
  struct VISIBILITY_HIDDEN CondProp : public FunctionPass {
    static char ID; // Pass identification, replacement for typeid
    CondProp() : FunctionPass(&ID) {}

    virtual bool runOnFunction(Function &F);

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.addRequiredID(BreakCriticalEdgesID);
      //AU.addRequired<DominanceFrontier>();
    }

  private:
    bool MadeChange;
    SmallVector<BasicBlock *, 4> DeadBlocks;
    void SimplifyBlock(BasicBlock *BB);
    void SimplifyPredecessors(BranchInst *BI);
    void SimplifyPredecessors(SwitchInst *SI);
    void RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB);
  };
}

char CondProp::ID = 0;
static RegisterPass<CondProp> X("condprop", "Conditional Propagation");

FunctionPass *llvm::createCondPropagationPass() {
  return new CondProp();
}

bool CondProp::runOnFunction(Function &F) {
  bool EverMadeChange = false;
  DeadBlocks.clear();

  // While we are simplifying blocks, keep iterating.
  do {
    MadeChange = false;
    for (Function::iterator BB = F.begin(), E = F.end(); BB != E;)
      SimplifyBlock(BB++);
    EverMadeChange = EverMadeChange || MadeChange;
  } while (MadeChange);

  if (EverMadeChange) {
    while (!DeadBlocks.empty()) {
      BasicBlock *BB = DeadBlocks.back(); DeadBlocks.pop_back();
      DeleteDeadBlock(BB);
    }
  }
  return EverMadeChange;
}

void CondProp::SimplifyBlock(BasicBlock *BB) {
  if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
    // If this is a conditional branch based on a phi node that is defined in
    // this block, see if we can simplify predecessors of this block.
    if (BI->isConditional() && isa<PHINode>(BI->getCondition()) &&
        cast<PHINode>(BI->getCondition())->getParent() == BB)
      SimplifyPredecessors(BI);

  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
    if (isa<PHINode>(SI->getCondition()) &&
        cast<PHINode>(SI->getCondition())->getParent() == BB)
      SimplifyPredecessors(SI);
  }

  // If possible, simplify the terminator of this block.
  if (ConstantFoldTerminator(BB))
    MadeChange = true;

  // If this block ends with an unconditional branch and the only successor has
  // only this block as a predecessor, merge the two blocks together.
  if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
    if (BI->isUnconditional() && BI->getSuccessor(0)->getSinglePredecessor() &&
        BB != BI->getSuccessor(0)) {
      BasicBlock *Succ = BI->getSuccessor(0);

      // If Succ has any PHI nodes, they are all single-entry PHI's.  Eliminate
      // them.
      FoldSingleEntryPHINodes(Succ);

      // Remove BI.
      BI->eraseFromParent();

      // Move over all of the instructions.
      BB->getInstList().splice(BB->end(), Succ->getInstList());

      // Any phi nodes that had entries for Succ now have entries from BB.
      Succ->replaceAllUsesWith(BB);

      // Succ is now dead, but we cannot delete it without potentially
      // invalidating iterators elsewhere.  Just insert an unreachable
      // instruction in it and delete this block later on.
      new UnreachableInst(Succ);
      DeadBlocks.push_back(Succ);
      MadeChange = true;
    }
}

// SimplifyPredecessors(branches) - We know that BI is a conditional branch
// based on a PHI node defined in this block.  If the phi node contains constant
// operands, then the blocks corresponding to those operands can be modified to
// jump directly to the destination instead of going through this block.
void CondProp::SimplifyPredecessors(BranchInst *BI) {
  // TODO: We currently only handle the most trival case, where the PHI node has
  // one use (the branch), and is the only instruction besides the branch and dbg
  // intrinsics in the block.
  PHINode *PN = cast<PHINode>(BI->getCondition());

  if (PN->getNumIncomingValues() == 1) {
    // Eliminate single-entry PHI nodes.
    FoldSingleEntryPHINodes(PN->getParent());
    return;
  }

  if (!PN->hasOneUse()) return;

  BasicBlock *BB = BI->getParent();
  if (&*BB->begin() != PN)
    return;
  BasicBlock::iterator BBI = BB->begin();
  BasicBlock::iterator BBE = BB->end();
  while (BBI != BBE && isa<DbgInfoIntrinsic>(++BBI)) ;
  if (&*BBI != BI)
    return;

  // Ok, we have this really simple case, walk the PHI operands, looking for
  // constants.  Walk from the end to remove operands from the end when
  // possible, and to avoid invalidating "i".
  for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
    if (ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
      // If we have a constant, forward the edge from its current to its
      // ultimate destination.
      RevectorBlockTo(PN->getIncomingBlock(i-1),
                      BI->getSuccessor(CB->isZero()));
      ++NumBrThread;

      // If there were two predecessors before this simplification, or if the
      // PHI node contained all the same value except for the one we just
      // substituted, the PHI node may be deleted.  Don't iterate through it the
      // last time.
      if (BI->getCondition() != PN) return;
    }
}

// SimplifyPredecessors(switch) - We know that SI is switch based on a PHI node
// defined in this block.  If the phi node contains constant operands, then the
// blocks corresponding to those operands can be modified to jump directly to
// the destination instead of going through this block.
void CondProp::SimplifyPredecessors(SwitchInst *SI) {
  // TODO: We currently only handle the most trival case, where the PHI node has
  // one use (the branch), and is the only instruction besides the branch and
  // dbg intrinsics in the block.
  PHINode *PN = cast<PHINode>(SI->getCondition());
  if (!PN->hasOneUse()) return;

  BasicBlock *BB = SI->getParent();
  if (&*BB->begin() != PN)
    return;
  BasicBlock::iterator BBI = BB->begin();
  BasicBlock::iterator BBE = BB->end();
  while (BBI != BBE && isa<DbgInfoIntrinsic>(++BBI)) ;
  if (&*BBI != SI)
    return;

  bool RemovedPreds = false;

  // Ok, we have this really simple case, walk the PHI operands, looking for
  // constants.  Walk from the end to remove operands from the end when
  // possible, and to avoid invalidating "i".
  for (unsigned i = PN->getNumIncomingValues(); i != 0; --i)
    if (ConstantInt *CI = dyn_cast<ConstantInt>(PN->getIncomingValue(i-1))) {
      // If we have a constant, forward the edge from its current to its
      // ultimate destination.
      unsigned DestCase = SI->findCaseValue(CI);
      RevectorBlockTo(PN->getIncomingBlock(i-1),
                      SI->getSuccessor(DestCase));
      ++NumSwThread;
      RemovedPreds = true;

      // If there were two predecessors before this simplification, or if the
      // PHI node contained all the same value except for the one we just
      // substituted, the PHI node may be deleted.  Don't iterate through it the
      // last time.
      if (SI->getCondition() != PN) return;
    }
}

// RevectorBlockTo - Revector the unconditional branch at the end of FromBB to
// the ToBB block, which is one of the successors of its current successor.
void CondProp::RevectorBlockTo(BasicBlock *FromBB, BasicBlock *ToBB) {
  BranchInst *FromBr = cast<BranchInst>(FromBB->getTerminator());
  assert(FromBr->isUnconditional() && "FromBB should end with uncond br!");

  // Get the old block we are threading through.
  BasicBlock *OldSucc = FromBr->getSuccessor(0);

  // OldSucc had multiple successors. If ToBB has multiple predecessors, then
  // the edge between them would be critical, which we already took care of.
  // If ToBB has single operand PHI node then take care of it here.
  FoldSingleEntryPHINodes(ToBB);

  // Update PHI nodes in OldSucc to know that FromBB no longer branches to it.
  OldSucc->removePredecessor(FromBB);

  // Change FromBr to branch to the new destination.
  FromBr->setSuccessor(0, ToBB);

  MadeChange = true;
}
<|endoftext|>


<commit_before>#include "fast++.hpp"
#include <vif/core/main.hpp>

#ifndef FASTPP_GIT_HASH
#define FASTPP_GIT_HASH ""
#endif

const char* fastpp_version = "1.3.0";
const char* fastpp_git_hash = FASTPP_GIT_HASH;

const constexpr uint_t grid_id::z;
const constexpr uint_t grid_id::av;
const constexpr uint_t grid_id::age;
const constexpr uint_t grid_id::metal;
const constexpr uint_t grid_id::custom;

const constexpr uint_t prop_id::scale;
const constexpr uint_t prop_id::spec_scale;
const constexpr uint_t prop_id::mass;
const constexpr uint_t prop_id::sfr;
const constexpr uint_t prop_id::ssfr;
const constexpr uint_t prop_id::ldust;
const constexpr uint_t prop_id::lion;
const constexpr uint_t prop_id::mform;
const constexpr uint_t prop_id::custom;

const constexpr uint_t log_style::none;
const constexpr uint_t log_style::decimal;
const constexpr uint_t log_style::abmag;

int vif_main(int argc, char* argv[]) {
    std::string param_file = (argc >= 2 ? argv[1] : "fast.param");

    // Read input data
    options_t opts;
    input_state_t input;
    if (!read_input(opts, input, param_file)) {
        return 1;
    }

    // Initialize the grid
    output_state_t output;
    gridder_t gridder(opts, input, output);
    if (!gridder.check_options()) {
        return 1;
    }

    if (!opts.make_seds.empty()) {
        // Write SEDs if asked, then terminate
        gridder.write_seds();
        return 0;
    }

    if (gridder.read_from_cache && opts.parallel == parallel_choice::generators &&
        opts.n_thread > 0) {
        if (opts.verbose) {
            note("using cache, switched parallel execution from 'generators' to 'models'");
        }

        opts.parallel = parallel_choice::models;
    }

    // Initizalize the fitter
    fitter_t fitter(opts, input, gridder, output);

    // Build/read the grid and fit galaxies
    if (!gridder.build_and_send(fitter)) {
        return 1;
    }

    // Compile results
    fitter.find_best_fits();

    // Write output to disk
    write_output(opts, input, gridder, fitter, output);

    return 0;
}
<commit_msg>Added missing definitions for lir_component::*<commit_after>#include "fast++.hpp"
#include <vif/core/main.hpp>

#ifndef FASTPP_GIT_HASH
#define FASTPP_GIT_HASH ""
#endif

const char* fastpp_version = "1.3.0";
const char* fastpp_git_hash = FASTPP_GIT_HASH;

const constexpr uint_t grid_id::z;
const constexpr uint_t grid_id::av;
const constexpr uint_t grid_id::age;
const constexpr uint_t grid_id::metal;
const constexpr uint_t grid_id::custom;

const constexpr uint_t prop_id::scale;
const constexpr uint_t prop_id::spec_scale;
const constexpr uint_t prop_id::mass;
const constexpr uint_t prop_id::sfr;
const constexpr uint_t prop_id::ssfr;
const constexpr uint_t prop_id::ldust;
const constexpr uint_t prop_id::lion;
const constexpr uint_t prop_id::mform;
const constexpr uint_t prop_id::custom;

const constexpr uint_t log_style::none;
const constexpr uint_t log_style::decimal;
const constexpr uint_t log_style::abmag;

const constexpr uint_t lir_component::all;
const constexpr uint_t lir_component::bc;
const constexpr uint_t lir_component::cirrus;

int vif_main(int argc, char* argv[]) {
    std::string param_file = (argc >= 2 ? argv[1] : "fast.param");

    // Read input data
    options_t opts;
    input_state_t input;
    if (!read_input(opts, input, param_file)) {
        return 1;
    }

    // Initialize the grid
    output_state_t output;
    gridder_t gridder(opts, input, output);
    if (!gridder.check_options()) {
        return 1;
    }

    if (!opts.make_seds.empty()) {
        // Write SEDs if asked, then terminate
        gridder.write_seds();
        return 0;
    }

    if (gridder.read_from_cache && opts.parallel == parallel_choice::generators &&
        opts.n_thread > 0) {
        if (opts.verbose) {
            note("using cache, switched parallel execution from 'generators' to 'models'");
        }

        opts.parallel = parallel_choice::models;
    }

    // Initizalize the fitter
    fitter_t fitter(opts, input, gridder, output);

    // Build/read the grid and fit galaxies
    if (!gridder.build_and_send(fitter)) {
        return 1;
    }

    // Compile results
    fitter.find_best_fits();

    // Write output to disk
    write_output(opts, input, gridder, fitter, output);

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Axel Isouard <axel@isouard.fr>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <webrtc/base/ssladapter.h>
#include "globals.h"

rtc::Thread *Globals::_signalingThread = NULL;
rtc::Thread *Globals::_workerThread = NULL;
webrtc::PeerConnectionFactoryInterface *Globals::_peerConnectionFactory = NULL;

bool Globals::Init() {
  rtc::InitializeSSL();
  rtc::InitRandom(rtc::Time());
  rtc::ThreadManager::Instance()->WrapCurrentThread();

  _signalingThread = new rtc::Thread();
  _workerThread = new rtc::Thread();

  _signalingThread->SetName("signaling_thread", NULL);
  _workerThread->SetName("worker_thread", NULL);

  if (!_signalingThread->Start() || !_workerThread->Start()) {
    return false;
  }

  _peerConnectionFactory =
      webrtc::CreatePeerConnectionFactory(_signalingThread,
                                          _workerThread,
                                          NULL, NULL, NULL).release();

  return true;
}

bool Globals::Update() {
  return rtc::Thread::Current()->ProcessMessages(0);
}

void Globals::Cleanup(void* args) {
  _peerConnectionFactory->Release();
  _peerConnectionFactory = NULL;

  _signalingThread->Stop();
  _workerThread->Stop();

  delete _signalingThread;
  delete _workerThread;

  _signalingThread = NULL;
  _workerThread = NULL;

  rtc::CleanupSSL();
}

rtc::Thread *Globals::GetSignalingThread() {
  return _signalingThread;
}

rtc::Thread *Globals::GetWorkerThread() {
  return _workerThread;
}

webrtc::PeerConnectionFactoryInterface *Globals::GetPeerConnectionFactory() {
  return _peerConnectionFactory;
}
<commit_msg>Globals: Add Win32 related code, set the current thread, deinit them correctly<commit_after>/*
 * Copyright (c) 2017 Axel Isouard <axel@isouard.fr>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <nan.h>

#if WEBRTC_WIN
#include <webrtc/base/win32socketinit.h>
#include <webrtc/base/win32socketserver.h>
#endif

#include <webrtc/base/ssladapter.h>
#include "globals.h"

rtc::Thread *Globals::_signalingThread = NULL;
rtc::Thread *Globals::_workerThread = NULL;
webrtc::PeerConnectionFactoryInterface *Globals::_peerConnectionFactory = NULL;

bool Globals::Init() {
#if WEBRTC_WIN
  rtc::EnsureWinsockInit();
#endif

  rtc::InitializeSSL();
  rtc::InitRandom(rtc::Time());
  rtc::ThreadManager::Instance()->WrapCurrentThread();

  _signalingThread = new rtc::Thread();
  _workerThread = new rtc::Thread();

  _signalingThread->SetName("signaling_thread", NULL);
  _workerThread->SetName("worker_thread", NULL);

  if (!_signalingThread->Start() || !_workerThread->Start()) {
    return false;
  }

  rtc::ThreadManager::Instance()->SetCurrentThread(_signalingThread);

  if (rtc::ThreadManager::Instance()->CurrentThread() != _signalingThread) {
    Nan::ThrowError("Failed to set the current thread.");
  }

  _peerConnectionFactory =
      webrtc::CreatePeerConnectionFactory(_signalingThread,
                                          _workerThread,
                                          NULL, NULL, NULL).release();

  return true;
}

bool Globals::Update() {
  return rtc::Thread::Current()->ProcessMessages(0);
}

void Globals::Cleanup(void* args) {
  _peerConnectionFactory->Release();
  _peerConnectionFactory = NULL;

  _signalingThread->SetAllowBlockingCalls(true);
  _signalingThread->Stop();

  _workerThread->SetAllowBlockingCalls(true);
  _workerThread->Stop();

  if (rtc::ThreadManager::Instance()->CurrentThread() == _signalingThread) {
    rtc::ThreadManager::Instance()->SetCurrentThread(NULL);
  }

  delete _signalingThread;
  delete _workerThread;

  _signalingThread = NULL;
  _workerThread = NULL;

  rtc::CleanupSSL();
}

rtc::Thread *Globals::GetSignalingThread() {
  return _signalingThread;
}

rtc::Thread *Globals::GetWorkerThread() {
  return _workerThread;
}

webrtc::PeerConnectionFactoryInterface *Globals::GetPeerConnectionFactory() {
  return _peerConnectionFactory;
}
<|endoftext|>


<commit_before>//
// keyvi - A key value store.
//
// Copyright 2015 Hendrik Muhs<hendrik.muhs@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

/*
 * fsa_predictive_compression_test.cpp
 *
 *  Created on: Apr 10, 2015
 *      Author: hendrik
 */

#include <sstream>
#include <boost/test/unit_test.hpp>
#include "dictionary/testing/temp_dictionary.h"
#include "compression/predictive_compression.h"

namespace keyvi {
namespace compression {

BOOST_AUTO_TEST_SUITE( PredictiveCompressionTests )

BOOST_AUTO_TEST_CASE( CompressAndUncompress ) {
  std::istringstream corpus(
      "ht\x05""tp://" "tt\x05""ps://" "//\x04""www." "th\x01""e");

  auto compressor = PredictiveCompression(corpus);

  std::string input = "http://www.the-test.com";
  std::string output = compressor.Compress(input);
  std::string uncompressed = compressor.Uncompress(output);
  BOOST_CHECK_EQUAL(2 + 13, output.size());
  BOOST_CHECK_EQUAL(input, uncompressed);

  input = "aa";
  output = compressor.Compress(input);
  BOOST_CHECK_EQUAL(input, compressor.Uncompress(output));

  input = std::string("null\0http://www.\0-byte.com", 26);
  output = compressor.Compress(input);
  uncompressed = compressor.Uncompress(output);
  BOOST_CHECK_EQUAL(input, uncompressed);
  BOOST_CHECK_EQUAL(26, input.size());
  BOOST_CHECK_EQUAL(26, uncompressed.size());
}

BOOST_AUTO_TEST_SUITE_END()

}
}

<commit_msg>Additional tests for the compressor constructor.<commit_after>//
// keyvi - A key value store.
//
// Copyright 2015 Hendrik Muhs<hendrik.muhs@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

/*
 * fsa_predictive_compression_test.cpp
 *
 *  Created on: Apr 10, 2015
 *      Author: hendrik
 */

#include <sstream>
#include <boost/test/unit_test.hpp>
#include "dictionary/testing/temp_dictionary.h"
#include "compression/predictive_compression.h"

namespace keyvi {
namespace compression {

BOOST_AUTO_TEST_SUITE( PredictiveCompressionTests )

BOOST_AUTO_TEST_CASE( CompressAndUncompress ) {
  std::istringstream corpus(
      "ht\x05""tp://" "tt\x05""ps://" "//\x04""www." "th\x01""e");

  auto compressor = PredictiveCompression(corpus);

  std::string input = "http://www.the-test.com";
  std::string output = compressor.Compress(input);
  std::string uncompressed = compressor.Uncompress(output);
  BOOST_CHECK_EQUAL(2 + 13, output.size());
  BOOST_CHECK_EQUAL(input, uncompressed);

  input = "aa";
  output = compressor.Compress(input);
  BOOST_CHECK_EQUAL(input, compressor.Uncompress(output));

  input = std::string("null\0http://www.\0-byte.com", 26);
  output = compressor.Compress(input);
  uncompressed = compressor.Uncompress(output);
  BOOST_CHECK_EQUAL(input, uncompressed);
  BOOST_CHECK_EQUAL(26, input.size());
  BOOST_CHECK_EQUAL(26, uncompressed.size());
}

BOOST_AUTO_TEST_CASE( CompressTooLongValue ) {
  std::istringstream corpus(
      "ht\x05""tp://" "tt\x05""ps://" "//\x04""www." "th\x14""too_long_value");

  BOOST_CHECK_THROW(PredictiveCompression compressor(corpus),
                    std::invalid_argument);
}

BOOST_AUTO_TEST_CASE( CompressIncomplete ) {
  std::istringstream corpus(
      "ht\x05""tp://" "tt\x05""ps://" "//\x04""www");

  BOOST_CHECK_THROW(PredictiveCompression compressor(corpus),
                    std::istream::failure);
}

BOOST_AUTO_TEST_SUITE_END()

}
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sddll.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:30:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif

#include <svx/editeng.hxx>

#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX
#include <svtools/moduleoptions.hxx>
#endif
#ifndef _FM_FMOBJFAC_HXX
#include <svx/fmobjfac.hxx>
#endif
#ifndef _SVDFIELD_HXX
#include <svx/svdfield.hxx>
#endif
#ifndef _OBJFAC3D_HXX
#include <svx/objfac3d.hxx>
#endif

#include "sddll.hxx"
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#ifndef SD_GRAPHIC_DOC_SHELL_HXX
#include "GraphicDocShell.hxx"
#endif
#include "sdresid.hxx"
#include "sdobjfac.hxx"
#include "cfgids.hxx"
#include "strmname.h"
#include "SdShapeTypes.hxx"

#include <svx/SvxShapeTypes.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/fcontnr.hxx>
#include <tools/urlobj.hxx>
#include <svx/impgrf.hxx>
#include <svtools/FilterConfigItem.hxx>

#ifndef _COM_SUN_STAR_UTIL_XARCHIVER_HPP_
#include <com/sun/star/util/XArchiver.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;

/*************************************************************************
|*
|* Init
|*
\************************************************************************/

void SdDLL::Init()
{
    if ( SD_MOD() )
        return;

    SfxObjectFactory* pDrawFact = NULL;
    SfxObjectFactory* pImpressFact = NULL;

    if (SvtModuleOptions().IsImpress())
        pImpressFact = &::sd::DrawDocShell::Factory();

    if (SvtModuleOptions().IsDraw())
        pDrawFact = &::sd::GraphicDocShell::Factory();

    // the SdModule must be created
     SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW);

     // #i46427#
     // The SfxModule::SfxModule stops when the first given factory
     // is 0, so we must not give a 0 as first factory
     if( pImpressFact )
     {
        (*ppShlPtr) = new SdModule( pImpressFact, pDrawFact );
     }
     else
     {
        (*ppShlPtr) = new SdModule( pDrawFact, pImpressFact );
     }

    if (SvtModuleOptions().IsImpress())
    {
        // Register the Impress shape types in order to make the shapes accessible.
        ::accessibility::RegisterImpressShapeTypes ();
        ::sd::DrawDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.presentation.PresentationDocument" ) ) );
    }

    if (SvtModuleOptions().IsDraw())
    {
        ::sd::GraphicDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) );
    }

    // register your view-factories here
    RegisterFactorys();

    // register your shell-interfaces here
    RegisterInterfaces();

    // register your controllers here
    RegisterControllers();

    // SvDraw-Felder registrieren
    SdrRegisterFieldClasses();

    // 3D-Objekt-Factory eintragen
    E3dObjFactory();

    // ::com::sun::star::form::component::Form-Objekt-Factory eintragen
    FmFormObjFactory();

    // factory for dummy import of old si-controls in 3.1 documents
//BFS02    SiImportFactory();

    // Objekt-Factory eintragen
    SdrObjFactory::InsertMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData));
}

/*************************************************************************
|*
|* Exit
|*
\************************************************************************/

void SdDLL::Exit()
{
    // called directly befor unloading the DLL
    // do whatever you want, Sd-DLL is accessible

    // Objekt-Factory austragen
    SdrObjFactory::RemoveMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData));

    // the SdModule must be destroyed
    SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW);
    delete (*ppShlPtr);
    (*ppShlPtr) = NULL;
}

/*
ULONG SdDLL::DetectFilter(SfxMedium& rMedium, const SfxFilter** ppFilter,
                          SfxFilterFlags nMust, SfxFilterFlags nDont)
{
    ULONG nReturn = ERRCODE_ABORT;  // Erkennung fehlgeschlagen, Filter ungueltig
    BOOL bStorage = FALSE;

    if( *ppFilter && (*ppFilter)->GetFilterFlags() & SFX_FILTER_PACKED )
    {
        uno::Reference< lang::XMultiServiceFactory > xSMgr( ::comphelper::getProcessServiceFactory() );
        uno::Reference< util::XArchiver > xPacker( xSMgr->createInstance( OUString::createFromAscii( "com.sun.star.util.Archiver" ) ), uno::UNO_QUERY );
        if( xPacker.is() )
        {
            // extract extra data
            OUString aPath( rMedium.GetOrigURL() );
            OUString aExtraData( xPacker->getExtraData( aPath ) );
            const OUString aSig1= OUString::createFromAscii( "private:" );
            String aTmp;
            aTmp += sal_Unicode( '?' );
            aTmp += String::CreateFromAscii("simpress");
            const OUString aSig2( aTmp );
            INT32 nIndex1 = aExtraData.indexOf( aSig1 );
            INT32 nIndex2 = aExtraData.indexOf( aSig2 );
            if( nIndex1 == 0 && nIndex2 != -1 )
                return ERRCODE_NONE;
        }
    }
    else if (rMedium.GetError() == SVSTREAM_OK)
    {
        if ( rMedium.IsStorage() )
        {
            bStorage = TRUE;
            SotStorageRef xStorage = rMedium.GetStorage();
            if ( !xStorage.Is() )
                return ULONG_MAX;

            if( SvtModuleOptions().IsImpress() )
            {
                // Erkennung ueber contained streams (PowerPoint 97-Filter)
                String aStreamName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "PowerPoint Document" ) );
                if ( xStorage->IsContained( aStreamName ) && xStorage->IsStream( aStreamName ) )
                {
                    String aFileName(rMedium.GetName());
                    aFileName.ToUpperAscii();

                    if( aFileName.SearchAscii( ".POT" ) == STRING_NOTFOUND )
                        *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97);
                    else
                        *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97Template );

                    return ERRCODE_NONE;
                }
            }

            const SfxFilter* pFilter = *ppFilter;
            if ( *ppFilter )
            {
                if ( (*ppFilter)->GetFormat() == xStorage->GetFormat() )
                    pFilter = *ppFilter;
            }

             if( !pFilter && SvtModuleOptions().IsImpress() )
            {
                SfxFilterMatcher aMatcher( String::CreateFromAscii("simpress") );
                pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() );
                if ( pFilter )
                    *ppFilter = pFilter;
            }

            if( !pFilter && SvtModuleOptions().IsDraw() )
            {
                SfxFilterMatcher aMatcher( String::CreateFromAscii("sdraw") );
                pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() );
                if ( pFilter )
                    *ppFilter = pFilter;
            }

            if ( pFilter &&
                ( pFilter->GetFilterFlags() & nMust ) == nMust &&
                ( pFilter->GetFilterFlags() & nDont ) == 0 )
            {
                *ppFilter = pFilter;
                nReturn = ERRCODE_NONE;
            }
            else
            {
                *ppFilter = NULL;
                nReturn = ERRCODE_NONE;
            }
        }

        String aFileName( rMedium.GetName() );
        aFileName.ToUpperAscii();

        if ( nReturn == ERRCODE_ABORT )
        {
            if( bStorage )         // aber keine Clipboard-Id #55337#
            {
                *ppFilter = NULL;
            }
            else
            {
                // Vektorgraphik?
                SvStream* pStm = rMedium.GetInStream();

                if( !pStm )
                    nReturn = ERRCODE_IO_GENERAL;
                else
                {
                    pStm->Seek( STREAM_SEEK_TO_BEGIN );

                    const String        aFileName( rMedium.GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) );
                    GraphicDescriptor   aDesc( *pStm, &aFileName );
                    GraphicFilter*      pGrfFilter = GetGrfFilter();

                    if( !aDesc.Detect( FALSE ) )
                    {
                        if( SvtModuleOptions().IsImpress() )
                        {
                            *ppFilter = NULL;
                            nReturn = ERRCODE_ABORT;
                            INetURLObject aURL( aFileName );
                            if( aURL.getExtension().equalsIgnoreAsciiCaseAscii( "cgm" ) )
                            {
                                sal_uInt8 n8;
                                pStm->Seek( STREAM_SEEK_TO_BEGIN );
                                *pStm >> n8;
                                if ( ( n8 & 0xf0 ) == 0 )       // we are supporting binary cgm format only, so
                                {                               // this is a small test to exclude cgm text
                                    const String aName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "CGM - Computer Graphics Metafile" ) );
                                    SfxFilterMatcher aMatch( String::CreateFromAscii("simpress") );
                                    *ppFilter = aMatch.GetFilter4FilterName( aName );
                                    nReturn = ERRCODE_NONE;
                                }
                            }
                        }
                    }
                    else
                    {
                        if( SvtModuleOptions().IsDraw() )
                        {
                            String aShortName( aDesc.GetImportFormatShortName( aDesc.GetFileFormat() ) );
                            const String aName( pGrfFilter->GetImportFormatTypeName( pGrfFilter->GetImportFormatNumberForShortName( aShortName ) ) );

                            if ( *ppFilter && aShortName.EqualsIgnoreCaseAscii( "PCD" ) )    // there is a multiple pcd selection possible
                            {
                                sal_Int32 nBase = 2;    // default Base0
                                String aFilterTypeName( (*ppFilter)->GetRealTypeName() );
                                if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base4" ) == COMPARE_EQUAL )
                                    nBase = 1;
                                else if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base16" ) == COMPARE_EQUAL )
                                    nBase = 0;
                                String aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Import/PCD" ) );
                                FilterConfigItem aFilterConfigItem( aFilterConfigPath );
                                aFilterConfigItem.WriteInt32( String( RTL_CONSTASCII_USTRINGPARAM( "Resolution" ) ), nBase );
                            }

                            SfxFilterMatcher aMatch( String::CreateFromAscii("draw") );
                            *ppFilter = aMatch.GetFilter4FilterName( aName );
                            nReturn = ERRCODE_NONE;
                        }
                        else
                        {
                            nReturn = ERRCODE_ABORT;
                            *ppFilter = NULL;
                        }
                    }
                }
            }
        }
    }
    else
    {
        nReturn = rMedium.GetError();
    }

    return nReturn;
} */
<commit_msg>INTEGRATION: CWS aw024 (1.10.6); FILE MERGED 2006/09/21 22:57:57 aw 1.10.6.5: RESYNC: (1.14-1.15); FILE MERGED 2006/05/12 20:25:47 aw 1.10.6.4: RESYNC: (1.12-1.13); FILE MERGED 2005/09/17 10:54:34 aw 1.10.6.3: RESYNC: (1.11-1.12); FILE MERGED 2005/05/13 14:24:03 aw 1.10.6.2: RESYNC: (1.10-1.11); FILE MERGED 2004/12/27 09:58:26 aw 1.10.6.1: #i39525<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sddll.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 14:24:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif

#include <svx/editeng.hxx>

#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX
#include <svtools/moduleoptions.hxx>
#endif
#ifndef _FM_FMOBJFAC_HXX
#include <svx/fmobjfac.hxx>
#endif
#ifndef _SVDFIELD_HXX
#include <svx/svdfield.hxx>
#endif
#ifndef _OBJFAC3D_HXX
#include <svx/objfac3d.hxx>
#endif

#include "sddll.hxx"
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#ifndef SD_GRAPHIC_DOC_SHELL_HXX
#include "GraphicDocShell.hxx"
#endif
#include "sdresid.hxx"
#include "sdobjfac.hxx"
#include "cfgids.hxx"
#include "strmname.h"
#include "SdShapeTypes.hxx"

#include <svx/SvxShapeTypes.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/fcontnr.hxx>
#include <tools/urlobj.hxx>
#include <svx/impgrf.hxx>
#include <svtools/FilterConfigItem.hxx>

#ifndef _COM_SUN_STAR_UTIL_XARCHIVER_HPP_
#include <com/sun/star/util/XArchiver.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;

/*************************************************************************
|*
|* Init
|*
\************************************************************************/

void SdDLL::Init()
{
    if ( SD_MOD() )
        return;

    SfxObjectFactory* pDrawFact = NULL;
    SfxObjectFactory* pImpressFact = NULL;

    if (SvtModuleOptions().IsImpress())
        pImpressFact = &::sd::DrawDocShell::Factory();

    if (SvtModuleOptions().IsDraw())
        pDrawFact = &::sd::GraphicDocShell::Factory();

    // the SdModule must be created
     SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW);

     // #i46427#
     // The SfxModule::SfxModule stops when the first given factory
     // is 0, so we must not give a 0 as first factory
     if( pImpressFact )
     {
        (*ppShlPtr) = new SdModule( pImpressFact, pDrawFact );
     }
     else
     {
        (*ppShlPtr) = new SdModule( pDrawFact, pImpressFact );
     }

    if (SvtModuleOptions().IsImpress())
    {
        // Register the Impress shape types in order to make the shapes accessible.
        ::accessibility::RegisterImpressShapeTypes ();
        ::sd::DrawDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.presentation.PresentationDocument" ) ) );
    }

    if (SvtModuleOptions().IsDraw())
    {
        ::sd::GraphicDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) );
    }

    // register your view-factories here
    RegisterFactorys();

    // register your shell-interfaces here
    RegisterInterfaces();

    // register your controllers here
    RegisterControllers();

    // SvDraw-Felder registrieren
    SdrRegisterFieldClasses();

    // 3D-Objekt-Factory eintragen
    E3dObjFactory();

    // ::com::sun::star::form::component::Form-Objekt-Factory eintragen
    FmFormObjFactory();

    // Objekt-Factory eintragen
    SdrObjFactory::InsertMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData));
}

/*************************************************************************
|*
|* Exit
|*
\************************************************************************/

void SdDLL::Exit()
{
    // called directly befor unloading the DLL
    // do whatever you want, Sd-DLL is accessible

    // Objekt-Factory austragen
    SdrObjFactory::RemoveMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData));

    // the SdModule must be destroyed
    SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW);
    delete (*ppShlPtr);
    (*ppShlPtr) = NULL;
}

/*
ULONG SdDLL::DetectFilter(SfxMedium& rMedium, const SfxFilter** ppFilter,
                          SfxFilterFlags nMust, SfxFilterFlags nDont)
{
    ULONG nReturn = ERRCODE_ABORT;  // Erkennung fehlgeschlagen, Filter ungueltig
    BOOL bStorage = FALSE;

    if( *ppFilter && (*ppFilter)->GetFilterFlags() & SFX_FILTER_PACKED )
    {
        uno::Reference< lang::XMultiServiceFactory > xSMgr( ::comphelper::getProcessServiceFactory() );
        uno::Reference< util::XArchiver > xPacker( xSMgr->createInstance( OUString::createFromAscii( "com.sun.star.util.Archiver" ) ), uno::UNO_QUERY );
        if( xPacker.is() )
        {
            // extract extra data
            OUString aPath( rMedium.GetOrigURL() );
            OUString aExtraData( xPacker->getExtraData( aPath ) );
            const OUString aSig1= OUString::createFromAscii( "private:" );
            String aTmp;
            aTmp += sal_Unicode( '?' );
            aTmp += String::CreateFromAscii("simpress");
            const OUString aSig2( aTmp );
            INT32 nIndex1 = aExtraData.indexOf( aSig1 );
            INT32 nIndex2 = aExtraData.indexOf( aSig2 );
            if( nIndex1 == 0 && nIndex2 != -1 )
                return ERRCODE_NONE;
        }
    }
    else if (rMedium.GetError() == SVSTREAM_OK)
    {
        if ( rMedium.IsStorage() )
        {
            bStorage = TRUE;
            SotStorageRef xStorage = rMedium.GetStorage();
            if ( !xStorage.Is() )
                return ULONG_MAX;

            if( SvtModuleOptions().IsImpress() )
            {
                // Erkennung ueber contained streams (PowerPoint 97-Filter)
                String aStreamName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "PowerPoint Document" ) );
                if ( xStorage->IsContained( aStreamName ) && xStorage->IsStream( aStreamName ) )
                {
                    String aFileName(rMedium.GetName());
                    aFileName.ToUpperAscii();

                    if( aFileName.SearchAscii( ".POT" ) == STRING_NOTFOUND )
                        *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97);
                    else
                        *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97Template );

                    return ERRCODE_NONE;
                }
            }

            const SfxFilter* pFilter = *ppFilter;
            if ( *ppFilter )
            {
                if ( (*ppFilter)->GetFormat() == xStorage->GetFormat() )
                    pFilter = *ppFilter;
            }

             if( !pFilter && SvtModuleOptions().IsImpress() )
            {
                SfxFilterMatcher aMatcher( String::CreateFromAscii("simpress") );
                pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() );
                if ( pFilter )
                    *ppFilter = pFilter;
            }

            if( !pFilter && SvtModuleOptions().IsDraw() )
            {
                SfxFilterMatcher aMatcher( String::CreateFromAscii("sdraw") );
                pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() );
                if ( pFilter )
                    *ppFilter = pFilter;
            }

            if ( pFilter &&
                ( pFilter->GetFilterFlags() & nMust ) == nMust &&
                ( pFilter->GetFilterFlags() & nDont ) == 0 )
            {
                *ppFilter = pFilter;
                nReturn = ERRCODE_NONE;
            }
            else
            {
                *ppFilter = NULL;
                nReturn = ERRCODE_NONE;
            }
        }

        String aFileName( rMedium.GetName() );
        aFileName.ToUpperAscii();

        if ( nReturn == ERRCODE_ABORT )
        {
            if( bStorage )         // aber keine Clipboard-Id #55337#
            {
                *ppFilter = NULL;
            }
            else
            {
                // Vektorgraphik?
                SvStream* pStm = rMedium.GetInStream();

                if( !pStm )
                    nReturn = ERRCODE_IO_GENERAL;
                else
                {
                    pStm->Seek( STREAM_SEEK_TO_BEGIN );

                    const String        aFileName( rMedium.GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) );
                    GraphicDescriptor   aDesc( *pStm, &aFileName );
                    GraphicFilter*      pGrfFilter = GetGrfFilter();

                    if( !aDesc.Detect( FALSE ) )
                    {
                        if( SvtModuleOptions().IsImpress() )
                        {
                            *ppFilter = NULL;
                            nReturn = ERRCODE_ABORT;
                            INetURLObject aURL( aFileName );
                            if( aURL.getExtension().equalsIgnoreAsciiCaseAscii( "cgm" ) )
                            {
                                sal_uInt8 n8;
                                pStm->Seek( STREAM_SEEK_TO_BEGIN );
                                *pStm >> n8;
                                if ( ( n8 & 0xf0 ) == 0 )       // we are supporting binary cgm format only, so
                                {                               // this is a small test to exclude cgm text
                                    const String aName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "CGM - Computer Graphics Metafile" ) );
                                    SfxFilterMatcher aMatch( String::CreateFromAscii("simpress") );
                                    *ppFilter = aMatch.GetFilter4FilterName( aName );
                                    nReturn = ERRCODE_NONE;
                                }
                            }
                        }
                    }
                    else
                    {
                        if( SvtModuleOptions().IsDraw() )
                        {
                            String aShortName( aDesc.GetImportFormatShortName( aDesc.GetFileFormat() ) );
                            const String aName( pGrfFilter->GetImportFormatTypeName( pGrfFilter->GetImportFormatNumberForShortName( aShortName ) ) );

                            if ( *ppFilter && aShortName.EqualsIgnoreCaseAscii( "PCD" ) )    // there is a multiple pcd selection possible
                            {
                                sal_Int32 nBase = 2;    // default Base0
                                String aFilterTypeName( (*ppFilter)->GetRealTypeName() );
                                if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base4" ) == COMPARE_EQUAL )
                                    nBase = 1;
                                else if ( aFilterTypeName.CompareToAscii( "pcd_Photo_CD_Base16" ) == COMPARE_EQUAL )
                                    nBase = 0;
                                String aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Import/PCD" ) );
                                FilterConfigItem aFilterConfigItem( aFilterConfigPath );
                                aFilterConfigItem.WriteInt32( String( RTL_CONSTASCII_USTRINGPARAM( "Resolution" ) ), nBase );
                            }

                            SfxFilterMatcher aMatch( String::CreateFromAscii("draw") );
                            *ppFilter = aMatch.GetFilter4FilterName( aName );
                            nReturn = ERRCODE_NONE;
                        }
                        else
                        {
                            nReturn = ERRCODE_ABORT;
                            *ppFilter = NULL;
                        }
                    }
                }
            }
        }
    }
    else
    {
        nReturn = rMedium.GetError();
    }

    return nReturn;
} */
<|endoftext|>